From d3ba569091dbd6a3ee0739eea89a43baa30fd53a Mon Sep 17 00:00:00 2001 From: goldbuick Date: Sat, 28 Dec 2024 01:39:23 +0000 Subject: [PATCH] Build: (65e41c1) Dev (#54) --- assets/index-CRvaIo0f.js | 4944 ++++++++++++++++++++++++++++++++++ assets/index-VzaR3_tn.js | 4904 --------------------------------- assets/instance-BaZ499FU.js | 208 -- assets/simspace-_1023Pw3.js | 208 ++ assets/stubspace-Mt81ZBb1.js | 10 + index.html | 4 +- 6 files changed, 5164 insertions(+), 5114 deletions(-) create mode 100644 assets/index-CRvaIo0f.js delete mode 100644 assets/index-VzaR3_tn.js delete mode 100644 assets/instance-BaZ499FU.js create mode 100644 assets/simspace-_1023Pw3.js create mode 100644 assets/stubspace-Mt81ZBb1.js diff --git a/assets/index-CRvaIo0f.js b/assets/index-CRvaIo0f.js new file mode 100644 index 00000000..e7d60720 --- /dev/null +++ b/assets/index-CRvaIo0f.js @@ -0,0 +1,4944 @@ +var fz=Object.defineProperty;var dz=n=>{throw TypeError(n)};var pz=(n,e,t)=>e in n?fz(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var mz=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var yt=(n,e,t)=>pz(n,typeof e!="symbol"?e+"":e,t);var Yd=(n,e,t)=>e.has(n)?dz("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t);var t0e=mz((Bs,zs)=>{function gz(n,e){for(var t=0;tr[i]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(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"&&r(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 r(i){if(i.ep)return;i.ep=!0;const s=t(i);fetch(i.href,s)}})();var No=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function $a(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function _z(n){if(n.__esModule)return n;var e=n.default;if(typeof e=="function"){var t=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(r){var i=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return n[r]}})}),t}var wO={exports:{}},qv={},AO={exports:{}},Qt={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var um=Symbol.for("react.element"),vz=Symbol.for("react.portal"),yz=Symbol.for("react.fragment"),xz=Symbol.for("react.strict_mode"),Sz=Symbol.for("react.profiler"),Ez=Symbol.for("react.provider"),bz=Symbol.for("react.context"),Tz=Symbol.for("react.forward_ref"),wz=Symbol.for("react.suspense"),Az=Symbol.for("react.memo"),Mz=Symbol.for("react.lazy"),dR=Symbol.iterator;function Cz(n){return n===null||typeof n!="object"?null:(n=dR&&n[dR]||n["@@iterator"],typeof n=="function"?n:null)}var MO={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},CO=Object.assign,RO={};function _d(n,e,t){this.props=n,this.context=e,this.refs=RO,this.updater=t||MO}_d.prototype.isReactComponent={};_d.prototype.setState=function(n,e){if(typeof n!="object"&&typeof n!="function"&&n!=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,n,e,"setState")};_d.prototype.forceUpdate=function(n){this.updater.enqueueForceUpdate(this,n,"forceUpdate")};function kO(){}kO.prototype=_d.prototype;function LT(n,e,t){this.props=n,this.context=e,this.refs=RO,this.updater=t||MO}var PT=LT.prototype=new kO;PT.constructor=LT;CO(PT,_d.prototype);PT.isPureReactComponent=!0;var pR=Array.isArray,NO=Object.prototype.hasOwnProperty,DT={current:null},IO={key:!0,ref:!0,__self:!0,__source:!0};function OO(n,e,t){var r,i={},s=null,o=null;if(e!=null)for(r in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(s=""+e.key),e)NO.call(e,r)&&!IO.hasOwnProperty(r)&&(i[r]=e[r]);var a=arguments.length-2;if(a===1)i.children=t;else if(1>8&255]+Si[n>>16&255]+Si[n>>24&255]+"-"+Si[e&255]+Si[e>>8&255]+"-"+Si[e>>16&15|64]+Si[e>>24&255]+"-"+Si[t&63|128]+Si[t>>8&255]+"-"+Si[t>>16&255]+Si[t>>24&255]+Si[r&255]+Si[r>>8&255]+Si[r>>16&255]+Si[r>>24&255]).toLowerCase()}function zi(n,e,t){return Math.max(e,Math.min(t,n))}function WT(n,e){return(n%e+e)%e}function T8(n,e,t,r,i){return r+(n-e)*(i-r)/(t-e)}function w8(n,e,t){return n!==e?(t-n)/(e-n):0}function Mp(n,e,t){return(1-t)*n+t*e}function A8(n,e,t,r){return Mp(n,e,1-Math.exp(-t*r))}function M8(n,e=1){return e-Math.abs(WT(n,e*2)-e)}function C8(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function R8(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function k8(n,e){return n+Math.floor(Math.random()*(e-n+1))}function N8(n,e){return n+Math.random()*(e-n)}function I8(n){return n*(.5-Math.random())}function O8(n){n!==void 0&&(bR=n);let e=bR+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function L8(n){return n*Ap}function P8(n){return n*Dp}function D8(n){return(n&n-1)===0&&n!==0}function U8(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function F8(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function B8(n,e,t,r,i){const s=Math.cos,o=Math.sin,a=s(t/2),c=o(t/2),l=s((e+r)/2),u=o((e+r)/2),h=s((e-r)/2),d=o((e-r)/2),m=s((r-e)/2),g=o((r-e)/2);switch(i){case"XYX":n.set(a*u,c*h,c*d,a*l);break;case"YZY":n.set(c*d,a*u,c*h,a*l);break;case"ZXZ":n.set(c*h,c*d,a*u,a*l);break;case"XZX":n.set(a*u,c*g,c*m,a*l);break;case"YXY":n.set(c*m,a*u,c*g,a*l);break;case"ZYZ":n.set(c*g,c*m,a*u,a*l);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function pf(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function Pi(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const z8={DEG2RAD:Ap,RAD2DEG:Dp,generateUUID:yd,clamp:zi,euclideanModulo:WT,mapLinear:T8,inverseLerp:w8,lerp:Mp,damp:A8,pingpong:M8,smoothstep:C8,smootherstep:R8,randInt:k8,randFloat:N8,randFloatSpread:I8,seededRandom:O8,degToRad:L8,radToDeg:P8,isPowerOfTwo:D8,ceilPowerOfTwo:U8,floorPowerOfTwo:F8,setQuaternionFromProperEuler:B8,normalize:Pi,denormalize:pf};class Et{constructor(e=0,t=0){Et.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,r=this.y,i=e.elements;return this.x=i[0]*t+i[3]*r+i[6],this.y=i[1]*t+i[4]*r+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const r=this.dot(e)/t;return Math.acos(zi(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,r=this.y-e.y;return t*t+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const r=Math.cos(t),i=Math.sin(t),s=this.x-e.x,o=this.y-e.y;return this.x=s*r-o*i+e.x,this.y=s*i+o*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Ft{constructor(e,t,r,i,s,o,a,c,l){Ft.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,r,i,s,o,a,c,l)}set(e,t,r,i,s,o,a,c,l){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=t,u[4]=s,u[5]=c,u[6]=r,u[7]=o,u[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,r=e.elements;return t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=r[3],t[4]=r[4],t[5]=r[5],t[6]=r[6],t[7]=r[7],t[8]=r[8],this}extractBasis(e,t,r){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const r=e.elements,i=t.elements,s=this.elements,o=r[0],a=r[3],c=r[6],l=r[1],u=r[4],h=r[7],d=r[2],m=r[5],g=r[8],v=i[0],y=i[3],_=i[6],S=i[1],E=i[4],T=i[7],k=i[2],R=i[5],M=i[8];return s[0]=o*v+a*S+c*k,s[3]=o*y+a*E+c*R,s[6]=o*_+a*T+c*M,s[1]=l*v+u*S+h*k,s[4]=l*y+u*E+h*R,s[7]=l*_+u*T+h*M,s[2]=d*v+m*S+g*k,s[5]=d*y+m*E+g*R,s[8]=d*_+m*T+g*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],u=e[8];return t*o*u-t*a*l-r*s*u+r*a*c+i*s*l-i*o*c}invert(){const e=this.elements,t=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],u=e[8],h=u*o-a*l,d=a*c-u*s,m=l*s-o*c,g=t*h+r*d+i*m;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return e[0]=h*v,e[1]=(i*l-u*r)*v,e[2]=(a*r-i*o)*v,e[3]=d*v,e[4]=(u*t-i*c)*v,e[5]=(i*s-a*t)*v,e[6]=m*v,e[7]=(r*c-l*t)*v,e[8]=(o*t-r*s)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,r,i,s,o,a){const c=Math.cos(s),l=Math.sin(s);return this.set(r*c,r*l,-r*(c*o+l*a)+o+e,-i*l,i*c,-i*(-l*o+c*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(RS.makeScale(e,t)),this}rotate(e){return this.premultiply(RS.makeRotation(-e)),this}translate(e,t){return this.premultiply(RS.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,-r,0,r,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,r=e.elements;for(let i=0;i<9;i++)if(t[i]!==r[i])return!1;return!0}fromArray(e,t=0){for(let r=0;r<9;r++)this.elements[r]=e[r+t];return this}toArray(e=[],t=0){const r=this.elements;return e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3],e[t+4]=r[4],e[t+5]=r[5],e[t+6]=r[6],e[t+7]=r[7],e[t+8]=r[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const RS=new Ft;function ZO(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function Up(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function V8(){const n=Up("canvas");return n.style.display="block",n}const TR={};function dp(n){n in TR||(TR[n]=!0,console.warn(n))}function H8(n,e,t){return new Promise(function(r,i){function s(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:i();break;case n.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:r()}}setTimeout(s,t)})}function G8(n){const e=n.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function W8(n){const e=n.elements;e[11]===-1?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=-e[14]+1)}const dn={enabled:!0,workingColorSpace:Ql,spaces:{},convert:function(n,e,t){return this.enabled===!1||e===t||!e||!t||(this.spaces[e].transfer===Cn&&(n.r=Lc(n.r),n.g=Lc(n.g),n.b=Lc(n.b)),this.spaces[e].primaries!==this.spaces[t].primaries&&(n.applyMatrix3(this.spaces[e].toXYZ),n.applyMatrix3(this.spaces[t].fromXYZ)),this.spaces[t].transfer===Cn&&(n.r=If(n.r),n.g=If(n.g),n.b=If(n.b))),n},fromWorkingColorSpace:function(n,e){return this.convert(n,this.workingColorSpace,e)},toWorkingColorSpace:function(n,e){return this.convert(n,e,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===ba?Zv:this.spaces[n].transfer},getLuminanceCoefficients:function(n,e=this.workingColorSpace){return n.fromArray(this.spaces[e].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,e,t){return n.copy(this.spaces[e].toXYZ).multiply(this.spaces[t].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace}};function Lc(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function If(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}const wR=[.64,.33,.3,.6,.15,.06],AR=[.2126,.7152,.0722],MR=[.3127,.329],CR=new Ft().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),RR=new Ft().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);dn.define({[Ql]:{primaries:wR,whitePoint:MR,transfer:Zv,toXYZ:CR,fromXYZ:RR,luminanceCoefficients:AR,workingColorSpaceConfig:{unpackColorSpace:vr},outputColorSpaceConfig:{drawingBufferColorSpace:vr}},[vr]:{primaries:wR,whitePoint:MR,transfer:Cn,toXYZ:CR,fromXYZ:RR,luminanceCoefficients:AR,outputColorSpaceConfig:{drawingBufferColorSpace:vr}}});let $h;class j8{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{$h===void 0&&($h=Up("canvas")),$h.width=e.width,$h.height=e.height;const r=$h.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),t=$h}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Up("canvas");t.width=e.width,t.height=e.height;const r=t.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const i=r.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o0&&(r.userData=this.userData),t||(e.textures[this.uuid]=r),r}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==FO)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case dE:e.x=e.x-Math.floor(e.x);break;case Bu:e.x=e.x<0?0:1;break;case pE:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case dE:e.y=e.y-Math.floor(e.y);break;case Bu:e.y=e.y<0?0:1;break;case pE:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}ur.DEFAULT_IMAGE=null;ur.DEFAULT_MAPPING=FO;ur.DEFAULT_ANISOTROPY=1;class xr{constructor(e=0,t=0,r=0,i=1){xr.prototype.isVector4=!0,this.x=e,this.y=t,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,r,i){return this.x=e,this.y=t,this.z=r,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,r=this.y,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*t+o[4]*r+o[8]*i+o[12]*s,this.y=o[1]*t+o[5]*r+o[9]*i+o[13]*s,this.z=o[2]*t+o[6]*r+o[10]*i+o[14]*s,this.w=o[3]*t+o[7]*r+o[11]*i+o[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,r,i,s;const c=e.elements,l=c[0],u=c[4],h=c[8],d=c[1],m=c[5],g=c[9],v=c[2],y=c[6],_=c[10];if(Math.abs(u-d)<.01&&Math.abs(h-v)<.01&&Math.abs(g-y)<.01){if(Math.abs(u+d)<.1&&Math.abs(h+v)<.1&&Math.abs(g+y)<.1&&Math.abs(l+m+_-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const E=(l+1)/2,T=(m+1)/2,k=(_+1)/2,R=(u+d)/4,M=(h+v)/4,O=(g+y)/4;return E>T&&E>k?E<.01?(r=0,i=.707106781,s=.707106781):(r=Math.sqrt(E),i=R/r,s=M/r):T>k?T<.01?(r=.707106781,i=0,s=.707106781):(i=Math.sqrt(T),r=R/i,s=O/i):k<.01?(r=.707106781,i=.707106781,s=0):(s=Math.sqrt(k),r=M/s,i=O/s),this.set(r,i,s,t),this}let S=Math.sqrt((y-g)*(y-g)+(h-v)*(h-v)+(d-u)*(d-u));return Math.abs(S)<.001&&(S=1),this.x=(y-g)/S,this.y=(h-v)/S,this.z=(d-u)/S,this.w=Math.acos((l+m+_-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this.z=e.z+(t.z-e.z)*r,this.w=e.w+(t.w-e.w)*r,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class X8 extends Xc{constructor(e=1,t=1,r={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new xr(0,0,e,t),this.scissorTest=!1,this.viewport=new xr(0,0,e,t);const i={width:e,height:t,depth:1};r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:fs,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},r);const s=new ur(i,r.mapping,r.wrapS,r.wrapT,r.magFilter,r.minFilter,r.format,r.type,r.anisotropy,r.colorSpace);s.flipY=!1,s.generateMipmaps=r.generateMipmaps,s.internalFormat=r.internalFormat,this.textures=[];const o=r.count;for(let a=0;a=0?1:-1,E=1-_*_;if(E>Number.EPSILON){const k=Math.sqrt(E),R=Math.atan2(k,_*S);y=Math.sin(y*R)/k,a=Math.sin(a*R)/k}const T=a*S;if(c=c*y+d*T,l=l*y+m*T,u=u*y+g*T,h=h*y+v*T,y===1-a){const k=1/Math.sqrt(c*c+l*l+u*u+h*h);c*=k,l*=k,u*=k,h*=k}}e[t]=c,e[t+1]=l,e[t+2]=u,e[t+3]=h}static multiplyQuaternionsFlat(e,t,r,i,s,o){const a=r[i],c=r[i+1],l=r[i+2],u=r[i+3],h=s[o],d=s[o+1],m=s[o+2],g=s[o+3];return e[t]=a*g+u*h+c*m-l*d,e[t+1]=c*g+u*d+l*h-a*m,e[t+2]=l*g+u*m+a*d-c*h,e[t+3]=u*g-a*h-c*d-l*m,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,r,i){return this._x=e,this._y=t,this._z=r,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const r=e._x,i=e._y,s=e._z,o=e._order,a=Math.cos,c=Math.sin,l=a(r/2),u=a(i/2),h=a(s/2),d=c(r/2),m=c(i/2),g=c(s/2);switch(o){case"XYZ":this._x=d*u*h+l*m*g,this._y=l*m*h-d*u*g,this._z=l*u*g+d*m*h,this._w=l*u*h-d*m*g;break;case"YXZ":this._x=d*u*h+l*m*g,this._y=l*m*h-d*u*g,this._z=l*u*g-d*m*h,this._w=l*u*h+d*m*g;break;case"ZXY":this._x=d*u*h-l*m*g,this._y=l*m*h+d*u*g,this._z=l*u*g+d*m*h,this._w=l*u*h-d*m*g;break;case"ZYX":this._x=d*u*h-l*m*g,this._y=l*m*h+d*u*g,this._z=l*u*g-d*m*h,this._w=l*u*h+d*m*g;break;case"YZX":this._x=d*u*h+l*m*g,this._y=l*m*h+d*u*g,this._z=l*u*g-d*m*h,this._w=l*u*h-d*m*g;break;case"XZY":this._x=d*u*h-l*m*g,this._y=l*m*h-d*u*g,this._z=l*u*g+d*m*h,this._w=l*u*h+d*m*g;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const r=t/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,r=t[0],i=t[4],s=t[8],o=t[1],a=t[5],c=t[9],l=t[2],u=t[6],h=t[10],d=r+a+h;if(d>0){const m=.5/Math.sqrt(d+1);this._w=.25/m,this._x=(u-c)*m,this._y=(s-l)*m,this._z=(o-i)*m}else if(r>a&&r>h){const m=2*Math.sqrt(1+r-a-h);this._w=(u-c)/m,this._x=.25*m,this._y=(i+o)/m,this._z=(s+l)/m}else if(a>h){const m=2*Math.sqrt(1+a-r-h);this._w=(s-l)/m,this._x=(i+o)/m,this._y=.25*m,this._z=(c+u)/m}else{const m=2*Math.sqrt(1+h-r-a);this._w=(o-i)/m,this._x=(s+l)/m,this._y=(c+u)/m,this._z=.25*m}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let r=e.dot(t)+1;return rMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(zi(this.dot(e),-1,1)))}rotateTowards(e,t){const r=this.angleTo(e);if(r===0)return this;const i=Math.min(1,t/r);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const r=e._x,i=e._y,s=e._z,o=e._w,a=t._x,c=t._y,l=t._z,u=t._w;return this._x=r*u+o*a+i*l-s*c,this._y=i*u+o*c+s*a-r*l,this._z=s*u+o*l+r*c-i*a,this._w=o*u-r*a-i*c-s*l,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const r=this._x,i=this._y,s=this._z,o=this._w;let a=o*e._w+r*e._x+i*e._y+s*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=o,this._x=r,this._y=i,this._z=s,this;const c=1-a*a;if(c<=Number.EPSILON){const m=1-t;return this._w=m*o+t*this._w,this._x=m*r+t*this._x,this._y=m*i+t*this._y,this._z=m*s+t*this._z,this.normalize(),this}const l=Math.sqrt(c),u=Math.atan2(l,a),h=Math.sin((1-t)*u)/l,d=Math.sin(t*u)/l;return this._w=o*h+this._w*d,this._x=r*h+this._x*d,this._y=i*h+this._y*d,this._z=s*h+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,r){return this.copy(e).slerp(t,r)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),r=Math.random(),i=Math.sqrt(1-r),s=Math.sqrt(r);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class xe{constructor(e=0,t=0,r=0){xe.prototype.isVector3=!0,this.x=e,this.y=t,this.z=r}set(e,t,r){return r===void 0&&(r=this.z),this.x=e,this.y=t,this.z=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(kR.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(kR.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[3]*r+s[6]*i,this.y=s[1]*t+s[4]*r+s[7]*i,this.z=s[2]*t+s[5]*r+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*t+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*t+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*t+s[6]*r+s[10]*i+s[14])*o,this}applyQuaternion(e){const t=this.x,r=this.y,i=this.z,s=e.x,o=e.y,a=e.z,c=e.w,l=2*(o*i-a*r),u=2*(a*t-s*i),h=2*(s*r-o*t);return this.x=t+c*l+o*h-a*u,this.y=r+c*u+a*l-s*h,this.z=i+c*h+s*u-o*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[4]*r+s[8]*i,this.y=s[1]*t+s[5]*r+s[9]*i,this.z=s[2]*t+s[6]*r+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(t,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,r){return this.x=e.x+(t.x-e.x)*r,this.y=e.y+(t.y-e.y)*r,this.z=e.z+(t.z-e.z)*r,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const r=e.x,i=e.y,s=e.z,o=t.x,a=t.y,c=t.z;return this.x=i*c-s*a,this.y=s*o-r*c,this.z=r*a-i*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const r=e.dot(this)/t;return this.copy(e).multiplyScalar(r)}projectOnPlane(e){return NS.copy(this).projectOnVector(e),this.sub(NS)}reflect(e){return this.sub(NS.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const r=this.dot(e)/t;return Math.acos(zi(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,r=this.y-e.y,i=this.z-e.z;return t*t+r*r+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,r){const i=Math.sin(t)*e;return this.x=i*Math.sin(r),this.y=Math.cos(t)*e,this.z=i*Math.cos(r),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,r){return this.x=e*Math.sin(t),this.y=r,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),r=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=r,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,r=Math.sqrt(1-t*t);return this.x=r*Math.cos(e),this.y=t,this.z=r*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const NS=new xe,kR=new hm;class fm{constructor(e=new xe(1/0,1/0,1/0),t=new xe(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,r=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,To),To.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,r;return e.normal.x>0?(t=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),t<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Zd),c0.subVectors(this.max,Zd),qh.subVectors(e.a,Zd),Xh.subVectors(e.b,Zd),Kh.subVectors(e.c,Zd),yl.subVectors(Xh,qh),xl.subVectors(Kh,Xh),_u.subVectors(qh,Kh);let t=[0,-yl.z,yl.y,0,-xl.z,xl.y,0,-_u.z,_u.y,yl.z,0,-yl.x,xl.z,0,-xl.x,_u.z,0,-_u.x,-yl.y,yl.x,0,-xl.y,xl.x,0,-_u.y,_u.x,0];return!IS(t,qh,Xh,Kh,c0)||(t=[1,0,0,0,1,0,0,0,1],!IS(t,qh,Xh,Kh,c0))?!1:(l0.crossVectors(yl,xl),t=[l0.x,l0.y,l0.z],IS(t,qh,Xh,Kh,c0))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,To).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(To).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(uc[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),uc[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),uc[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),uc[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),uc[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),uc[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),uc[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),uc[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(uc),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const uc=[new xe,new xe,new xe,new xe,new xe,new xe,new xe,new xe],To=new xe,a0=new fm,qh=new xe,Xh=new xe,Kh=new xe,yl=new xe,xl=new xe,_u=new xe,Zd=new xe,c0=new xe,l0=new xe,vu=new xe;function IS(n,e,t,r,i){for(let s=0,o=n.length-3;s<=o;s+=3){vu.fromArray(n,s);const a=i.x*Math.abs(vu.x)+i.y*Math.abs(vu.y)+i.z*Math.abs(vu.z),c=e.dot(vu),l=t.dot(vu),u=r.dot(vu);if(Math.max(-Math.max(c,l,u),Math.min(c,l,u))>a)return!1}return!0}const Y8=new fm,Jd=new xe,OS=new xe;class Jv{constructor(e=new xe,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const r=this.center;t!==void 0?r.copy(t):Y8.setFromPoints(e).getCenter(r);let i=0;for(let s=0,o=e.length;sthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Jd.subVectors(e,this.center);const t=Jd.lengthSq();if(t>this.radius*this.radius){const r=Math.sqrt(t),i=(r-this.radius)*.5;this.center.addScaledVector(Jd,i/r),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(OS.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Jd.copy(e.center).add(OS)),this.expandByPoint(Jd.copy(e.center).sub(OS))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const hc=new xe,LS=new xe,u0=new xe,Sl=new xe,PS=new xe,h0=new xe,DS=new xe;class jT{constructor(e=new xe,t=new xe(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,hc)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const r=t.dot(this.direction);return r<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,r)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=hc.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(hc.copy(this.origin).addScaledVector(this.direction,t),hc.distanceToSquared(e))}distanceSqToSegment(e,t,r,i){LS.copy(e).add(t).multiplyScalar(.5),u0.copy(t).sub(e).normalize(),Sl.copy(this.origin).sub(LS);const s=e.distanceTo(t)*.5,o=-this.direction.dot(u0),a=Sl.dot(this.direction),c=-Sl.dot(u0),l=Sl.lengthSq(),u=Math.abs(1-o*o);let h,d,m,g;if(u>0)if(h=o*c-a,d=o*a-c,g=s*u,h>=0)if(d>=-g)if(d<=g){const v=1/u;h*=v,d*=v,m=h*(h+o*d+2*a)+d*(o*h+d+2*c)+l}else d=s,h=Math.max(0,-(o*d+a)),m=-h*h+d*(d+2*c)+l;else d=-s,h=Math.max(0,-(o*d+a)),m=-h*h+d*(d+2*c)+l;else d<=-g?(h=Math.max(0,-(-o*s+a)),d=h>0?-s:Math.min(Math.max(-s,-c),s),m=-h*h+d*(d+2*c)+l):d<=g?(h=0,d=Math.min(Math.max(-s,-c),s),m=d*(d+2*c)+l):(h=Math.max(0,-(o*s+a)),d=h>0?s:Math.min(Math.max(-s,-c),s),m=-h*h+d*(d+2*c)+l);else d=o>0?-s:s,h=Math.max(0,-(o*d+a)),m=-h*h+d*(d+2*c)+l;return r&&r.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(LS).addScaledVector(u0,d),m}intersectSphere(e,t){hc.subVectors(e.center,this.origin);const r=hc.dot(this.direction),i=hc.dot(hc)-r*r,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),a=r-o,c=r+o;return c<0?null:a<0?this.at(c,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const r=-(this.origin.dot(e.normal)+e.constant)/t;return r>=0?r:null}intersectPlane(e,t){const r=this.distanceToPlane(e);return r===null?null:this.at(r,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let r,i,s,o,a,c;const l=1/this.direction.x,u=1/this.direction.y,h=1/this.direction.z,d=this.origin;return l>=0?(r=(e.min.x-d.x)*l,i=(e.max.x-d.x)*l):(r=(e.max.x-d.x)*l,i=(e.min.x-d.x)*l),u>=0?(s=(e.min.y-d.y)*u,o=(e.max.y-d.y)*u):(s=(e.max.y-d.y)*u,o=(e.min.y-d.y)*u),r>o||s>i||((s>r||isNaN(r))&&(r=s),(o=0?(a=(e.min.z-d.z)*h,c=(e.max.z-d.z)*h):(a=(e.max.z-d.z)*h,c=(e.min.z-d.z)*h),r>c||a>i)||((a>r||r!==r)&&(r=a),(c=0?r:i,t)}intersectsBox(e){return this.intersectBox(e,hc)!==null}intersectTriangle(e,t,r,i,s){PS.subVectors(t,e),h0.subVectors(r,e),DS.crossVectors(PS,h0);let o=this.direction.dot(DS),a;if(o>0){if(i)return null;a=1}else if(o<0)a=-1,o=-o;else return null;Sl.subVectors(this.origin,e);const c=a*this.direction.dot(h0.crossVectors(Sl,h0));if(c<0)return null;const l=a*this.direction.dot(PS.cross(Sl));if(l<0||c+l>o)return null;const u=-a*Sl.dot(DS);return u<0?null:this.at(u/o,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class hr{constructor(e,t,r,i,s,o,a,c,l,u,h,d,m,g,v,y){hr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,r,i,s,o,a,c,l,u,h,d,m,g,v,y)}set(e,t,r,i,s,o,a,c,l,u,h,d,m,g,v,y){const _=this.elements;return _[0]=e,_[4]=t,_[8]=r,_[12]=i,_[1]=s,_[5]=o,_[9]=a,_[13]=c,_[2]=l,_[6]=u,_[10]=h,_[14]=d,_[3]=m,_[7]=g,_[11]=v,_[15]=y,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new hr().fromArray(this.elements)}copy(e){const t=this.elements,r=e.elements;return t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=r[3],t[4]=r[4],t[5]=r[5],t[6]=r[6],t[7]=r[7],t[8]=r[8],t[9]=r[9],t[10]=r[10],t[11]=r[11],t[12]=r[12],t[13]=r[13],t[14]=r[14],t[15]=r[15],this}copyPosition(e){const t=this.elements,r=e.elements;return t[12]=r[12],t[13]=r[13],t[14]=r[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,r){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(e,t,r){return this.set(e.x,t.x,r.x,0,e.y,t.y,r.y,0,e.z,t.z,r.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,r=e.elements,i=1/Yh.setFromMatrixColumn(e,0).length(),s=1/Yh.setFromMatrixColumn(e,1).length(),o=1/Yh.setFromMatrixColumn(e,2).length();return t[0]=r[0]*i,t[1]=r[1]*i,t[2]=r[2]*i,t[3]=0,t[4]=r[4]*s,t[5]=r[5]*s,t[6]=r[6]*s,t[7]=0,t[8]=r[8]*o,t[9]=r[9]*o,t[10]=r[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,r=e.x,i=e.y,s=e.z,o=Math.cos(r),a=Math.sin(r),c=Math.cos(i),l=Math.sin(i),u=Math.cos(s),h=Math.sin(s);if(e.order==="XYZ"){const d=o*u,m=o*h,g=a*u,v=a*h;t[0]=c*u,t[4]=-c*h,t[8]=l,t[1]=m+g*l,t[5]=d-v*l,t[9]=-a*c,t[2]=v-d*l,t[6]=g+m*l,t[10]=o*c}else if(e.order==="YXZ"){const d=c*u,m=c*h,g=l*u,v=l*h;t[0]=d+v*a,t[4]=g*a-m,t[8]=o*l,t[1]=o*h,t[5]=o*u,t[9]=-a,t[2]=m*a-g,t[6]=v+d*a,t[10]=o*c}else if(e.order==="ZXY"){const d=c*u,m=c*h,g=l*u,v=l*h;t[0]=d-v*a,t[4]=-o*h,t[8]=g+m*a,t[1]=m+g*a,t[5]=o*u,t[9]=v-d*a,t[2]=-o*l,t[6]=a,t[10]=o*c}else if(e.order==="ZYX"){const d=o*u,m=o*h,g=a*u,v=a*h;t[0]=c*u,t[4]=g*l-m,t[8]=d*l+v,t[1]=c*h,t[5]=v*l+d,t[9]=m*l-g,t[2]=-l,t[6]=a*c,t[10]=o*c}else if(e.order==="YZX"){const d=o*c,m=o*l,g=a*c,v=a*l;t[0]=c*u,t[4]=v-d*h,t[8]=g*h+m,t[1]=h,t[5]=o*u,t[9]=-a*u,t[2]=-l*u,t[6]=m*h+g,t[10]=d-v*h}else if(e.order==="XZY"){const d=o*c,m=o*l,g=a*c,v=a*l;t[0]=c*u,t[4]=-h,t[8]=l*u,t[1]=d*h+v,t[5]=o*u,t[9]=m*h-g,t[2]=g*h-m,t[6]=a*u,t[10]=v*h+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Z8,e,J8)}lookAt(e,t,r){const i=this.elements;return Ns.subVectors(e,t),Ns.lengthSq()===0&&(Ns.z=1),Ns.normalize(),El.crossVectors(r,Ns),El.lengthSq()===0&&(Math.abs(r.z)===1?Ns.x+=1e-4:Ns.z+=1e-4,Ns.normalize(),El.crossVectors(r,Ns)),El.normalize(),f0.crossVectors(Ns,El),i[0]=El.x,i[4]=f0.x,i[8]=Ns.x,i[1]=El.y,i[5]=f0.y,i[9]=Ns.y,i[2]=El.z,i[6]=f0.z,i[10]=Ns.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const r=e.elements,i=t.elements,s=this.elements,o=r[0],a=r[4],c=r[8],l=r[12],u=r[1],h=r[5],d=r[9],m=r[13],g=r[2],v=r[6],y=r[10],_=r[14],S=r[3],E=r[7],T=r[11],k=r[15],R=i[0],M=i[4],O=i[8],C=i[12],I=i[1],U=i[5],L=i[9],P=i[13],w=i[2],H=i[6],V=i[10],B=i[14],z=i[3],W=i[7],K=i[11],j=i[15];return s[0]=o*R+a*I+c*w+l*z,s[4]=o*M+a*U+c*H+l*W,s[8]=o*O+a*L+c*V+l*K,s[12]=o*C+a*P+c*B+l*j,s[1]=u*R+h*I+d*w+m*z,s[5]=u*M+h*U+d*H+m*W,s[9]=u*O+h*L+d*V+m*K,s[13]=u*C+h*P+d*B+m*j,s[2]=g*R+v*I+y*w+_*z,s[6]=g*M+v*U+y*H+_*W,s[10]=g*O+v*L+y*V+_*K,s[14]=g*C+v*P+y*B+_*j,s[3]=S*R+E*I+T*w+k*z,s[7]=S*M+E*U+T*H+k*W,s[11]=S*O+E*L+T*V+k*K,s[15]=S*C+E*P+T*B+k*j,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],r=e[4],i=e[8],s=e[12],o=e[1],a=e[5],c=e[9],l=e[13],u=e[2],h=e[6],d=e[10],m=e[14],g=e[3],v=e[7],y=e[11],_=e[15];return g*(+s*c*h-i*l*h-s*a*d+r*l*d+i*a*m-r*c*m)+v*(+t*c*m-t*l*d+s*o*d-i*o*m+i*l*u-s*c*u)+y*(+t*l*h-t*a*m-s*o*h+r*o*m+s*a*u-r*l*u)+_*(-i*a*u-t*c*h+t*a*d+i*o*h-r*o*d+r*c*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,r){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=r),this}invert(){const e=this.elements,t=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],u=e[8],h=e[9],d=e[10],m=e[11],g=e[12],v=e[13],y=e[14],_=e[15],S=h*y*l-v*d*l+v*c*m-a*y*m-h*c*_+a*d*_,E=g*d*l-u*y*l-g*c*m+o*y*m+u*c*_-o*d*_,T=u*v*l-g*h*l+g*a*m-o*v*m-u*a*_+o*h*_,k=g*h*c-u*v*c-g*a*d+o*v*d+u*a*y-o*h*y,R=t*S+r*E+i*T+s*k;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/R;return e[0]=S*M,e[1]=(v*d*s-h*y*s-v*i*m+r*y*m+h*i*_-r*d*_)*M,e[2]=(a*y*s-v*c*s+v*i*l-r*y*l-a*i*_+r*c*_)*M,e[3]=(h*c*s-a*d*s-h*i*l+r*d*l+a*i*m-r*c*m)*M,e[4]=E*M,e[5]=(u*y*s-g*d*s+g*i*m-t*y*m-u*i*_+t*d*_)*M,e[6]=(g*c*s-o*y*s-g*i*l+t*y*l+o*i*_-t*c*_)*M,e[7]=(o*d*s-u*c*s+u*i*l-t*d*l-o*i*m+t*c*m)*M,e[8]=T*M,e[9]=(g*h*s-u*v*s-g*r*m+t*v*m+u*r*_-t*h*_)*M,e[10]=(o*v*s-g*a*s+g*r*l-t*v*l-o*r*_+t*a*_)*M,e[11]=(u*a*s-o*h*s-u*r*l+t*h*l+o*r*m-t*a*m)*M,e[12]=k*M,e[13]=(u*v*i-g*h*i+g*r*d-t*v*d-u*r*y+t*h*y)*M,e[14]=(g*a*i-o*v*i-g*r*c+t*v*c+o*r*y-t*a*y)*M,e[15]=(o*h*i-u*a*i+u*r*c-t*h*c-o*r*d+t*a*d)*M,this}scale(e){const t=this.elements,r=e.x,i=e.y,s=e.z;return t[0]*=r,t[4]*=i,t[8]*=s,t[1]*=r,t[5]*=i,t[9]*=s,t[2]*=r,t[6]*=i,t[10]*=s,t[3]*=r,t[7]*=i,t[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],r=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,r,i))}makeTranslation(e,t,r){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,r,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),r=Math.sin(e);return this.set(1,0,0,0,0,t,-r,0,0,r,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,0,r,0,0,1,0,0,-r,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),r=Math.sin(e);return this.set(t,-r,0,0,r,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const r=Math.cos(t),i=Math.sin(t),s=1-r,o=e.x,a=e.y,c=e.z,l=s*o,u=s*a;return this.set(l*o+r,l*a-i*c,l*c+i*a,0,l*a+i*c,u*a+r,u*c-i*o,0,l*c-i*a,u*c+i*o,s*c*c+r,0,0,0,0,1),this}makeScale(e,t,r){return this.set(e,0,0,0,0,t,0,0,0,0,r,0,0,0,0,1),this}makeShear(e,t,r,i,s,o){return this.set(1,r,s,0,e,1,o,0,t,i,1,0,0,0,0,1),this}compose(e,t,r){const i=this.elements,s=t._x,o=t._y,a=t._z,c=t._w,l=s+s,u=o+o,h=a+a,d=s*l,m=s*u,g=s*h,v=o*u,y=o*h,_=a*h,S=c*l,E=c*u,T=c*h,k=r.x,R=r.y,M=r.z;return i[0]=(1-(v+_))*k,i[1]=(m+T)*k,i[2]=(g-E)*k,i[3]=0,i[4]=(m-T)*R,i[5]=(1-(d+_))*R,i[6]=(y+S)*R,i[7]=0,i[8]=(g+E)*M,i[9]=(y-S)*M,i[10]=(1-(d+v))*M,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,r){const i=this.elements;let s=Yh.set(i[0],i[1],i[2]).length();const o=Yh.set(i[4],i[5],i[6]).length(),a=Yh.set(i[8],i[9],i[10]).length();this.determinant()<0&&(s=-s),e.x=i[12],e.y=i[13],e.z=i[14],wo.copy(this);const l=1/s,u=1/o,h=1/a;return wo.elements[0]*=l,wo.elements[1]*=l,wo.elements[2]*=l,wo.elements[4]*=u,wo.elements[5]*=u,wo.elements[6]*=u,wo.elements[8]*=h,wo.elements[9]*=h,wo.elements[10]*=h,t.setFromRotationMatrix(wo),r.x=s,r.y=o,r.z=a,this}makePerspective(e,t,r,i,s,o,a=Rc){const c=this.elements,l=2*s/(t-e),u=2*s/(r-i),h=(t+e)/(t-e),d=(r+i)/(r-i);let m,g;if(a===Rc)m=-(o+s)/(o-s),g=-2*o*s/(o-s);else if(a===Y_)m=-o/(o-s),g=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=l,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=u,c[9]=d,c[13]=0,c[2]=0,c[6]=0,c[10]=m,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,r,i,s,o,a=Rc){const c=this.elements,l=1/(t-e),u=1/(r-i),h=1/(o-s),d=(t+e)*l,m=(r+i)*u;let g,v;if(a===Rc)g=(o+s)*h,v=-2*h;else if(a===Y_)g=s*h,v=-1*h;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=2*l,c[4]=0,c[8]=0,c[12]=-d,c[1]=0,c[5]=2*u,c[9]=0,c[13]=-m,c[2]=0,c[6]=0,c[10]=v,c[14]=-g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,r=e.elements;for(let i=0;i<16;i++)if(t[i]!==r[i])return!1;return!0}fromArray(e,t=0){for(let r=0;r<16;r++)this.elements[r]=e[r+t];return this}toArray(e=[],t=0){const r=this.elements;return e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2],e[t+3]=r[3],e[t+4]=r[4],e[t+5]=r[5],e[t+6]=r[6],e[t+7]=r[7],e[t+8]=r[8],e[t+9]=r[9],e[t+10]=r[10],e[t+11]=r[11],e[t+12]=r[12],e[t+13]=r[13],e[t+14]=r[14],e[t+15]=r[15],e}}const Yh=new xe,wo=new hr,Z8=new xe(0,0,0),J8=new xe(1,1,1),El=new xe,f0=new xe,Ns=new xe,NR=new hr,IR=new hm;class Vc{constructor(e=0,t=0,r=0,i=Vc.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,r,i=this._order){return this._x=e,this._y=t,this._z=r,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,r=!0){const i=e.elements,s=i[0],o=i[4],a=i[8],c=i[1],l=i[5],u=i[9],h=i[2],d=i[6],m=i[10];switch(t){case"XYZ":this._y=Math.asin(zi(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,m),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-zi(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,m),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(zi(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-h,m),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-zi(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(d,m),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(zi(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(a,m));break;case"XZY":this._z=Math.asin(-zi(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-u,m),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,r===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,r){return NR.makeRotationFromQuaternion(e),this.setFromRotationMatrix(NR,t,r)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return IR.setFromEuler(this),this.setFromQuaternion(IR,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Vc.DEFAULT_ORDER="XYZ";class Of{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let r=0;r0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map(a=>({boxInitialized:a.boxInitialized,boxMin:a.box.min.toArray(),boxMax:a.box.max.toArray(),sphereInitialized:a.sphereInitialized,sphereRadius:a.sphere.radius,sphereCenter:a.sphere.center.toArray()})),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()}));function s(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,u=c.length;l0){i.children=[];for(let a=0;a0){i.animations=[];for(let a=0;a0&&(r.geometries=a),c.length>0&&(r.materials=c),l.length>0&&(r.textures=l),u.length>0&&(r.images=u),h.length>0&&(r.shapes=h),d.length>0&&(r.skeletons=d),m.length>0&&(r.animations=m),g.length>0&&(r.nodes=g)}return r.object=i,r;function o(a){const c=[];for(const l in a){const u=a[l];delete u.metadata,c.push(u)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let r=0;r0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,t,r,i,s){Ao.subVectors(i,t),dc.subVectors(r,t),FS.subVectors(e,t);const o=Ao.dot(Ao),a=Ao.dot(dc),c=Ao.dot(FS),l=dc.dot(dc),u=dc.dot(FS),h=o*l-a*a;if(h===0)return s.set(0,0,0),null;const d=1/h,m=(l*c-a*u)*d,g=(o*u-a*c)*d;return s.set(1-m-g,g,m)}static containsPoint(e,t,r,i){return this.getBarycoord(e,t,r,i,pc)===null?!1:pc.x>=0&&pc.y>=0&&pc.x+pc.y<=1}static getInterpolation(e,t,r,i,s,o,a,c){return this.getBarycoord(e,t,r,i,pc)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,pc.x),c.addScaledVector(o,pc.y),c.addScaledVector(a,pc.z),c)}static getInterpolatedAttribute(e,t,r,i,s,o){return HS.setScalar(0),GS.setScalar(0),WS.setScalar(0),HS.fromBufferAttribute(e,t),GS.fromBufferAttribute(e,r),WS.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(HS,s.x),o.addScaledVector(GS,s.y),o.addScaledVector(WS,s.z),o}static isFrontFacing(e,t,r,i){return Ao.subVectors(r,t),dc.subVectors(e,t),Ao.cross(dc).dot(i)<0}set(e,t,r){return this.a.copy(e),this.b.copy(t),this.c.copy(r),this}setFromPointsAndIndices(e,t,r,i){return this.a.copy(e[t]),this.b.copy(e[r]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,r,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ao.subVectors(this.c,this.b),dc.subVectors(this.a,this.b),Ao.cross(dc).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return ko.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return ko.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,r,i,s){return ko.getInterpolation(e,this.a,this.b,this.c,t,r,i,s)}containsPoint(e){return ko.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return ko.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const r=this.a,i=this.b,s=this.c;let o,a;Qh.subVectors(i,r),ef.subVectors(s,r),BS.subVectors(e,r);const c=Qh.dot(BS),l=ef.dot(BS);if(c<=0&&l<=0)return t.copy(r);zS.subVectors(e,i);const u=Qh.dot(zS),h=ef.dot(zS);if(u>=0&&h<=u)return t.copy(i);const d=c*h-u*l;if(d<=0&&c>=0&&u<=0)return o=c/(c-u),t.copy(r).addScaledVector(Qh,o);VS.subVectors(e,s);const m=Qh.dot(VS),g=ef.dot(VS);if(g>=0&&m<=g)return t.copy(s);const v=m*l-c*g;if(v<=0&&l>=0&&g<=0)return a=l/(l-g),t.copy(r).addScaledVector(ef,a);const y=u*g-m*h;if(y<=0&&h-u>=0&&m-g>=0)return FR.subVectors(s,i),a=(h-u)/(h-u+(m-g)),t.copy(i).addScaledVector(FR,a);const _=1/(y+v+d);return o=v*_,a=d*_,t.copy(r).addScaledVector(Qh,o).addScaledVector(ef,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const eL={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},bl={h:0,s:0,l:0},p0={h:0,s:0,l:0};function jS(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class hn{constructor(e,t,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,r)}set(e,t,r){if(t===void 0&&r===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=vr){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,dn.toWorkingColorSpace(this,t),this}setRGB(e,t,r,i=dn.workingColorSpace){return this.r=e,this.g=t,this.b=r,dn.toWorkingColorSpace(this,i),this}setHSL(e,t,r,i=dn.workingColorSpace){if(e=WT(e,1),t=zi(t,0,1),r=zi(r,0,1),t===0)this.r=this.g=this.b=r;else{const s=r<=.5?r*(1+t):r+t-r*t,o=2*r-s;this.r=jS(o,s,e+1/3),this.g=jS(o,s,e),this.b=jS(o,s,e-1/3)}return dn.toWorkingColorSpace(this,i),this}setStyle(e,t=vr){function r(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=vr){const r=eL[e.toLowerCase()];return r!==void 0?this.setHex(r,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Lc(e.r),this.g=Lc(e.g),this.b=Lc(e.b),this}copyLinearToSRGB(e){return this.r=If(e.r),this.g=If(e.g),this.b=If(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=vr){return dn.fromWorkingColorSpace(Ei.copy(this),e),Math.round(zi(Ei.r*255,0,255))*65536+Math.round(zi(Ei.g*255,0,255))*256+Math.round(zi(Ei.b*255,0,255))}getHexString(e=vr){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=dn.workingColorSpace){dn.fromWorkingColorSpace(Ei.copy(this),t);const r=Ei.r,i=Ei.g,s=Ei.b,o=Math.max(r,i,s),a=Math.min(r,i,s);let c,l;const u=(a+o)/2;if(a===o)c=0,l=0;else{const h=o-a;switch(l=u<=.5?h/(o+a):h/(2-o-a),o){case r:c=(i-s)/h+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const r=e[t];if(r===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.copy(r):this[t]=r}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const r={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(r.dispersion=this.dispersion),this.iridescence!==void 0&&(r.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(r.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(r.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(r.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(r.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapRotation!==void 0&&(r.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==kf&&(r.blending=this.blending),this.side!==zc&&(r.side=this.side),this.vertexColors===!0&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=!0),this.blendSrc!==nE&&(r.blendSrc=this.blendSrc),this.blendDst!==rE&&(r.blendDst=this.blendDst),this.blendEquation!==Lu&&(r.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(r.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(r.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(r.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(r.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(r.blendAlpha=this.blendAlpha),this.depthFunc!==jf&&(r.depthFunc=this.depthFunc),this.depthTest===!1&&(r.depthTest=this.depthTest),this.depthWrite===!1&&(r.depthWrite=this.depthWrite),this.colorWrite===!1&&(r.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(r.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==xR&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==jh&&(r.stencilFail=this.stencilFail),this.stencilZFail!==jh&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==jh&&(r.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(r.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaHash===!0&&(r.alphaHash=!0),this.alphaToCoverage===!0&&(r.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=!0),this.forceSinglePass===!0&&(r.forceSinglePass=!0),this.wireframe===!0&&(r.wireframe=!0),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=!0),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),this.fog===!1&&(r.fog=!1),Object.keys(this.userData).length>0&&(r.userData=this.userData);function i(s){const o=[];for(const a in s){const c=s[a];delete c.metadata,o.push(c)}return o}if(t){const s=i(e.textures),o=i(e.images);s.length>0&&(r.textures=s),o.length>0&&(r.images=o)}return r}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let r=null;if(t!==null){const i=t.length;r=new Array(i);for(let s=0;s!==i;++s)r[s]=t[s].clone()}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class $T extends Kc{static get type(){return"MeshBasicMaterial"}constructor(e){super(),this.isMeshBasicMaterial=!0,this.color=new hn(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Vc,this.combine=DO,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Ar=new xe,m0=new Et;class er{constructor(e,t,r=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=r,this.usage=SR,this.updateRanges=[],this.gpuType=Aa,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,r){e*=this.itemSize,r*=t.itemSize;for(let i=0,s=this.itemSize;it.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new fm);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new xe(-1/0,-1/0,-1/0),new xe(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let r=0,i=t.length;r0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const r=this.attributes;for(const c in r){const l=r[c];e.data.attributes[c]=l.toJSON(e.data)}const i={};let s=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],u=[];for(let h=0,d=l.length;h0&&(i[c]=u,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const r=e.index;r!==null&&this.setIndex(r.clone(t));const i=e.attributes;for(const l in i){const u=i[l];this.setAttribute(l,u.clone(t))}const s=e.morphAttributes;for(const l in s){const u=[],h=s[l];for(let d=0,m=h.length;d0){const i=t[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s(e.far-e.near)**2))&&(BR.copy(s).invert(),yu.copy(e.ray).applyMatrix4(BR),!(r.boundingBox!==null&&yu.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,t,yu)))}_computeIntersections(e,t,r){let i;const s=this.geometry,o=this.material,a=s.index,c=s.attributes.position,l=s.attributes.uv,u=s.attributes.uv1,h=s.attributes.normal,d=s.groups,m=s.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,v=d.length;gt.far?null:{distance:l,point:S0.clone(),object:n}}function E0(n,e,t,r,i,s,o,a,c,l){n.getVertexPosition(a,_0),n.getVertexPosition(c,v0),n.getVertexPosition(l,y0);const u=s6(n,e,t,r,_0,v0,y0,VR);if(u){const h=new xe;ko.getBarycoord(VR,_0,v0,y0,h),i&&(u.uv=ko.getInterpolatedAttribute(i,a,c,l,h,new Et)),s&&(u.uv1=ko.getInterpolatedAttribute(s,a,c,l,h,new Et)),o&&(u.normal=ko.getInterpolatedAttribute(o,a,c,l,h,new xe),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));const d={a,b:c,c:l,normal:new xe,materialIndex:0};ko.getNormal(_0,v0,y0,d.normal),u.face=d,u.barycoord=h}return u}class dm extends jo{constructor(e=1,t=1,r=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:r,widthSegments:i,heightSegments:s,depthSegments:o};const a=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const c=[],l=[],u=[],h=[];let d=0,m=0;g("z","y","x",-1,-1,r,t,e,o,s,0),g("z","y","x",1,-1,r,t,-e,o,s,1),g("x","z","y",1,1,e,r,t,i,o,2),g("x","z","y",1,-1,e,r,-t,i,o,3),g("x","y","z",1,-1,e,t,r,i,s,4),g("x","y","z",-1,-1,e,t,-r,i,s,5),this.setIndex(c),this.setAttribute("position",new ju(l,3)),this.setAttribute("normal",new ju(u,3)),this.setAttribute("uv",new ju(h,2));function g(v,y,_,S,E,T,k,R,M,O,C){const I=T/M,U=k/O,L=T/2,P=k/2,w=R/2,H=M+1,V=O+1;let B=0,z=0;const W=new xe;for(let K=0;K0?1:-1,u.push(W.x,W.y,W.z),h.push(Y/M),h.push(1-K/O),B+=1}}for(let K=0;K0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const r={};for(const i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(t.extensions=r),t}}class Qv extends ms{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new hr,this.projectionMatrix=new hr,this.projectionMatrixInverse=new hr,this.coordinateSystem=Rc}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Tl=new xe,HR=new Et,GR=new Et;class Ls extends Qv{constructor(e=50,t=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Dp*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Ap*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Dp*2*Math.atan(Math.tan(Ap*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,r){Tl.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Tl.x,Tl.y).multiplyScalar(-e/Tl.z),Tl.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),r.set(Tl.x,Tl.y).multiplyScalar(-e/Tl.z)}getViewSize(e,t){return this.getViewBounds(e,HR,GR),t.subVectors(GR,HR)}setViewOffset(e,t,r,i,s,o){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Ap*.5*this.fov)/this.zoom,r=2*t,i=this.aspect*r,s=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,l=o.fullHeight;s+=o.offsetX*i/c,t-=o.offsetY*r/l,i*=o.width/c,r*=o.height/l}const a=this.filmOffset;a!==0&&(s+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,t,t-r,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const nf=-90,rf=1;class u6 extends ms{constructor(e,t,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Ls(nf,rf,e,t);i.layers=this.layers,this.add(i);const s=new Ls(nf,rf,e,t);s.layers=this.layers,this.add(s);const o=new Ls(nf,rf,e,t);o.layers=this.layers,this.add(o);const a=new Ls(nf,rf,e,t);a.layers=this.layers,this.add(a);const c=new Ls(nf,rf,e,t);c.layers=this.layers,this.add(c);const l=new Ls(nf,rf,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[r,i,s,o,a,c]=t;for(const l of t)this.remove(l);if(e===Rc)r.up.set(0,1,0),r.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===Y_)r.up.set(0,-1,0),r.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,a,c,l,u]=this.children,h=e.getRenderTarget(),d=e.getActiveCubeFace(),m=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;const v=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(t,s),e.setRenderTarget(r,1,i),e.render(t,o),e.setRenderTarget(r,2,i),e.render(t,a),e.setRenderTarget(r,3,i),e.render(t,c),e.setRenderTarget(r,4,i),e.render(t,l),r.texture.generateMipmaps=v,e.setRenderTarget(r,5,i),e.render(t,u),e.setRenderTarget(h,d,m),e.xr.enabled=g,r.texture.needsPMREMUpdate=!0}}class iL extends ur{constructor(e,t,r,i,s,o,a,c,l,u){e=e!==void 0?e:[],t=t!==void 0?t:$f,super(e,t,r,i,s,o,a,c,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class h6 extends Gs{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];this.texture=new iL(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:fs}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},i=new dm(5,5,5),s=new qi({name:"CubemapFromEquirect",uniforms:Xf(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:ci,blending:Po});s.uniforms.tEquirect.value=t;const o=new Io(i,s),a=t.minFilter;return t.minFilter===zu&&(t.minFilter=fs),new u6(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t,r,i){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,r,i);e.setRenderTarget(s)}}const XS=new xe,f6=new xe,d6=new Ft;class Co{constructor(e=new xe(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,r,i){return this.normal.set(e,t,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,r){const i=XS.subVectors(r,t).cross(f6.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const r=e.delta(XS),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/i;return s<0||s>1?null:t.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const t=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return t<0&&r>0||r<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const r=t||d6.getNormalMatrix(e),i=this.coplanarPoint(XS).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-i.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const xu=new Jv,b0=new xe;class sL{constructor(e=new Co,t=new Co,r=new Co,i=new Co,s=new Co,o=new Co){this.planes=[e,t,r,i,s,o]}set(e,t,r,i,s,o){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(r),a[3].copy(i),a[4].copy(s),a[5].copy(o),this}copy(e){const t=this.planes;for(let r=0;r<6;r++)t[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,t=Rc){const r=this.planes,i=e.elements,s=i[0],o=i[1],a=i[2],c=i[3],l=i[4],u=i[5],h=i[6],d=i[7],m=i[8],g=i[9],v=i[10],y=i[11],_=i[12],S=i[13],E=i[14],T=i[15];if(r[0].setComponents(c-s,d-l,y-m,T-_).normalize(),r[1].setComponents(c+s,d+l,y+m,T+_).normalize(),r[2].setComponents(c+o,d+u,y+g,T+S).normalize(),r[3].setComponents(c-o,d-u,y-g,T-S).normalize(),r[4].setComponents(c-a,d-h,y-v,T-E).normalize(),t===Rc)r[5].setComponents(c+a,d+h,y+v,T+E).normalize();else if(t===Y_)r[5].setComponents(a,h,v,E).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),xu.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),xu.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(xu)}intersectsSprite(e){return xu.center.set(0,0,0),xu.radius=.7071067811865476,xu.applyMatrix4(e.matrixWorld),this.intersectsSphere(xu)}intersectsSphere(e){const t=this.planes,r=e.center,i=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(r)0?e.max.x:e.min.x,b0.y=i.normal.y>0?e.max.y:e.min.y,b0.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(b0)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let r=0;r<6;r++)if(t[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function oL(){let n=null,e=!1,t=null,r=null;function i(s,o){t(s,o),r=n.requestAnimationFrame(i)}return{start:function(){e!==!0&&t!==null&&(r=n.requestAnimationFrame(i),e=!0)},stop:function(){n.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){n=s}}}function p6(n){const e=new WeakMap;function t(a,c){const l=a.array,u=a.usage,h=l.byteLength,d=n.createBuffer();n.bindBuffer(c,d),n.bufferData(c,l,u),a.onUploadCallback();let m;if(l instanceof Float32Array)m=n.FLOAT;else if(l instanceof Uint16Array)a.isFloat16BufferAttribute?m=n.HALF_FLOAT:m=n.UNSIGNED_SHORT;else if(l instanceof Int16Array)m=n.SHORT;else if(l instanceof Uint32Array)m=n.UNSIGNED_INT;else if(l instanceof Int32Array)m=n.INT;else if(l instanceof Int8Array)m=n.BYTE;else if(l instanceof Uint8Array)m=n.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)m=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:d,type:m,bytesPerElement:l.BYTES_PER_ELEMENT,version:a.version,size:h}}function r(a,c,l){const u=c.array,h=c.updateRanges;if(n.bindBuffer(l,a),h.length===0)n.bufferSubData(l,0,u);else{h.sort((m,g)=>m.start-g.start);let d=0;for(let m=1;m 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,N6=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,I6=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,O6=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,L6=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,P6=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,D6=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`,U6=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`,F6=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,B6=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,z6=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,V6=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,H6=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,G6=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,W6=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,j6="gl_FragColor = linearToOutputTexel( gl_FragColor );",$6=`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,q6=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,X6=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`,K6=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,Y6=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,Z6=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,J6=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,Q6=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,eV=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,tV=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,nV=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,rV=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,iV=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,sV=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,oV=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,aV=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,cV=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,lV=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,uV=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,hV=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,fV=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,dV=`struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,pV=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,mV=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,gV=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,_V=`#if defined( USE_LOGDEPTHBUF ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,vV=`#if defined( USE_LOGDEPTHBUF ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,yV=`#ifdef USE_LOGDEPTHBUF + varying float vFragDepth; + varying float vIsPerspective; +#endif`,xV=`#ifdef USE_LOGDEPTHBUF + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,SV=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,EV=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,bV=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,TV=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,wV=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,AV=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,MV=`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,CV=`#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,RV=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,kV=`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,NV=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,IV=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,OV=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,LV=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,PV=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,DV=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,UV=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,FV=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,BV=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,zV=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,VV=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,HV=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,GV=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`,WV=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,jV=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,$V=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,qV=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,XV=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,KV=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,YV=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`,ZV=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,JV=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,QV=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,eH=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,tH=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,nH=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,rH=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,iH=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,sH=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,oH=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,aH=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,cH=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,lH=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + + #else + + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,uH=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,hH=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,fH=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,dH=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`;const pH=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,mH=`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,gH=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,_H=`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,vH=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,yH=`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,xH=`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,SH=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,EH=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,bH=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,TH=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,wH=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,AH=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,MH=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,CH=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,RH=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,kH=`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,NH=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,IH=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,OH=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,LH=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,PH=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,DH=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,UH=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,FH=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,BH=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,zH=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,VH=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,HH=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,GH=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,WH=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,jH=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,$H=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,qH=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,Vt={alphahash_fragment:m6,alphahash_pars_fragment:g6,alphamap_fragment:_6,alphamap_pars_fragment:v6,alphatest_fragment:y6,alphatest_pars_fragment:x6,aomap_fragment:S6,aomap_pars_fragment:E6,batching_pars_vertex:b6,batching_vertex:T6,begin_vertex:w6,beginnormal_vertex:A6,bsdfs:M6,iridescence_fragment:C6,bumpmap_pars_fragment:R6,clipping_planes_fragment:k6,clipping_planes_pars_fragment:N6,clipping_planes_pars_vertex:I6,clipping_planes_vertex:O6,color_fragment:L6,color_pars_fragment:P6,color_pars_vertex:D6,color_vertex:U6,common:F6,cube_uv_reflection_fragment:B6,defaultnormal_vertex:z6,displacementmap_pars_vertex:V6,displacementmap_vertex:H6,emissivemap_fragment:G6,emissivemap_pars_fragment:W6,colorspace_fragment:j6,colorspace_pars_fragment:$6,envmap_fragment:q6,envmap_common_pars_fragment:X6,envmap_pars_fragment:K6,envmap_pars_vertex:Y6,envmap_physical_pars_fragment:aV,envmap_vertex:Z6,fog_vertex:J6,fog_pars_vertex:Q6,fog_fragment:eV,fog_pars_fragment:tV,gradientmap_pars_fragment:nV,lightmap_pars_fragment:rV,lights_lambert_fragment:iV,lights_lambert_pars_fragment:sV,lights_pars_begin:oV,lights_toon_fragment:cV,lights_toon_pars_fragment:lV,lights_phong_fragment:uV,lights_phong_pars_fragment:hV,lights_physical_fragment:fV,lights_physical_pars_fragment:dV,lights_fragment_begin:pV,lights_fragment_maps:mV,lights_fragment_end:gV,logdepthbuf_fragment:_V,logdepthbuf_pars_fragment:vV,logdepthbuf_pars_vertex:yV,logdepthbuf_vertex:xV,map_fragment:SV,map_pars_fragment:EV,map_particle_fragment:bV,map_particle_pars_fragment:TV,metalnessmap_fragment:wV,metalnessmap_pars_fragment:AV,morphinstance_vertex:MV,morphcolor_vertex:CV,morphnormal_vertex:RV,morphtarget_pars_vertex:kV,morphtarget_vertex:NV,normal_fragment_begin:IV,normal_fragment_maps:OV,normal_pars_fragment:LV,normal_pars_vertex:PV,normal_vertex:DV,normalmap_pars_fragment:UV,clearcoat_normal_fragment_begin:FV,clearcoat_normal_fragment_maps:BV,clearcoat_pars_fragment:zV,iridescence_pars_fragment:VV,opaque_fragment:HV,packing:GV,premultiplied_alpha_fragment:WV,project_vertex:jV,dithering_fragment:$V,dithering_pars_fragment:qV,roughnessmap_fragment:XV,roughnessmap_pars_fragment:KV,shadowmap_pars_fragment:YV,shadowmap_pars_vertex:ZV,shadowmap_vertex:JV,shadowmask_pars_fragment:QV,skinbase_vertex:eH,skinning_pars_vertex:tH,skinning_vertex:nH,skinnormal_vertex:rH,specularmap_fragment:iH,specularmap_pars_fragment:sH,tonemapping_fragment:oH,tonemapping_pars_fragment:aH,transmission_fragment:cH,transmission_pars_fragment:lH,uv_pars_fragment:uH,uv_pars_vertex:hH,uv_vertex:fH,worldpos_vertex:dH,background_vert:pH,background_frag:mH,backgroundCube_vert:gH,backgroundCube_frag:_H,cube_vert:vH,cube_frag:yH,depth_vert:xH,depth_frag:SH,distanceRGBA_vert:EH,distanceRGBA_frag:bH,equirect_vert:TH,equirect_frag:wH,linedashed_vert:AH,linedashed_frag:MH,meshbasic_vert:CH,meshbasic_frag:RH,meshlambert_vert:kH,meshlambert_frag:NH,meshmatcap_vert:IH,meshmatcap_frag:OH,meshnormal_vert:LH,meshnormal_frag:PH,meshphong_vert:DH,meshphong_frag:UH,meshphysical_vert:FH,meshphysical_frag:BH,meshtoon_vert:zH,meshtoon_frag:VH,points_vert:HH,points_frag:GH,shadow_vert:WH,shadow_frag:jH,sprite_vert:$H,sprite_frag:qH},Xe={common:{diffuse:{value:new hn(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ft},alphaMap:{value:null},alphaMapTransform:{value:new Ft},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ft}},envmap:{envMap:{value:null},envMapRotation:{value:new Ft},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ft}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ft}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ft},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ft},normalScale:{value:new Et(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ft},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ft}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ft}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ft}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new hn(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new hn(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ft},alphaTest:{value:0},uvTransform:{value:new Ft}},sprite:{diffuse:{value:new hn(16777215)},opacity:{value:1},center:{value:new Et(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ft},alphaMap:{value:null},alphaMapTransform:{value:new Ft},alphaTest:{value:0}}},ya={basic:{uniforms:Di([Xe.common,Xe.specularmap,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.fog]),vertexShader:Vt.meshbasic_vert,fragmentShader:Vt.meshbasic_frag},lambert:{uniforms:Di([Xe.common,Xe.specularmap,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.fog,Xe.lights,{emissive:{value:new hn(0)}}]),vertexShader:Vt.meshlambert_vert,fragmentShader:Vt.meshlambert_frag},phong:{uniforms:Di([Xe.common,Xe.specularmap,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.fog,Xe.lights,{emissive:{value:new hn(0)},specular:{value:new hn(1118481)},shininess:{value:30}}]),vertexShader:Vt.meshphong_vert,fragmentShader:Vt.meshphong_frag},standard:{uniforms:Di([Xe.common,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.roughnessmap,Xe.metalnessmap,Xe.fog,Xe.lights,{emissive:{value:new hn(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Vt.meshphysical_vert,fragmentShader:Vt.meshphysical_frag},toon:{uniforms:Di([Xe.common,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.gradientmap,Xe.fog,Xe.lights,{emissive:{value:new hn(0)}}]),vertexShader:Vt.meshtoon_vert,fragmentShader:Vt.meshtoon_frag},matcap:{uniforms:Di([Xe.common,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.fog,{matcap:{value:null}}]),vertexShader:Vt.meshmatcap_vert,fragmentShader:Vt.meshmatcap_frag},points:{uniforms:Di([Xe.points,Xe.fog]),vertexShader:Vt.points_vert,fragmentShader:Vt.points_frag},dashed:{uniforms:Di([Xe.common,Xe.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Vt.linedashed_vert,fragmentShader:Vt.linedashed_frag},depth:{uniforms:Di([Xe.common,Xe.displacementmap]),vertexShader:Vt.depth_vert,fragmentShader:Vt.depth_frag},normal:{uniforms:Di([Xe.common,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,{opacity:{value:1}}]),vertexShader:Vt.meshnormal_vert,fragmentShader:Vt.meshnormal_frag},sprite:{uniforms:Di([Xe.sprite,Xe.fog]),vertexShader:Vt.sprite_vert,fragmentShader:Vt.sprite_frag},background:{uniforms:{uvTransform:{value:new Ft},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Vt.background_vert,fragmentShader:Vt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ft}},vertexShader:Vt.backgroundCube_vert,fragmentShader:Vt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Vt.cube_vert,fragmentShader:Vt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Vt.equirect_vert,fragmentShader:Vt.equirect_frag},distanceRGBA:{uniforms:Di([Xe.common,Xe.displacementmap,{referencePosition:{value:new xe},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Vt.distanceRGBA_vert,fragmentShader:Vt.distanceRGBA_frag},shadow:{uniforms:Di([Xe.lights,Xe.fog,{color:{value:new hn(0)},opacity:{value:1}}]),vertexShader:Vt.shadow_vert,fragmentShader:Vt.shadow_frag}};ya.physical={uniforms:Di([ya.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ft},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ft},clearcoatNormalScale:{value:new Et(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ft},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ft},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ft},sheen:{value:0},sheenColor:{value:new hn(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ft},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ft},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ft},transmissionSamplerSize:{value:new Et},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ft},attenuationDistance:{value:0},attenuationColor:{value:new hn(0)},specularColor:{value:new hn(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ft},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ft},anisotropyVector:{value:new Et},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ft}}]),vertexShader:Vt.meshphysical_vert,fragmentShader:Vt.meshphysical_frag};const T0={r:0,b:0,g:0},Su=new Vc,XH=new hr;function KH(n,e,t,r,i,s,o){const a=new hn(0);let c=s===!0?0:1,l,u,h=null,d=0,m=null;function g(S){let E=S.isScene===!0?S.background:null;return E&&E.isTexture&&(E=(S.backgroundBlurriness>0?t:e).get(E)),E}function v(S){let E=!1;const T=g(S);T===null?_(a,c):T&&T.isColor&&(_(T,1),E=!0);const k=n.xr.getEnvironmentBlendMode();k==="additive"?r.buffers.color.setClear(0,0,0,1,o):k==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(n.autoClear||E)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function y(S,E){const T=g(E);T&&(T.isCubeTexture||T.mapping===Kv)?(u===void 0&&(u=new Io(new dm(1,1,1),new qi({name:"BackgroundCubeMaterial",uniforms:Xf(ya.backgroundCube.uniforms),vertexShader:ya.backgroundCube.vertexShader,fragmentShader:ya.backgroundCube.fragmentShader,side:ci,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(k,R,M){this.matrixWorld.copyPosition(M.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(u)),Su.copy(E.backgroundRotation),Su.x*=-1,Su.y*=-1,Su.z*=-1,T.isCubeTexture&&T.isRenderTargetTexture===!1&&(Su.y*=-1,Su.z*=-1),u.material.uniforms.envMap.value=T,u.material.uniforms.flipEnvMap.value=T.isCubeTexture&&T.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=E.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(XH.makeRotationFromEuler(Su)),u.material.toneMapped=dn.getTransfer(T.colorSpace)!==Cn,(h!==T||d!==T.version||m!==n.toneMapping)&&(u.material.needsUpdate=!0,h=T,d=T.version,m=n.toneMapping),u.layers.enableAll(),S.unshift(u,u.geometry,u.material,0,0,null)):T&&T.isTexture&&(l===void 0&&(l=new Io(new pm(2,2),new qi({name:"BackgroundMaterial",uniforms:Xf(ya.background.uniforms),vertexShader:ya.background.vertexShader,fragmentShader:ya.background.fragmentShader,side:zc,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=T,l.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,l.material.toneMapped=dn.getTransfer(T.colorSpace)!==Cn,T.matrixAutoUpdate===!0&&T.updateMatrix(),l.material.uniforms.uvTransform.value.copy(T.matrix),(h!==T||d!==T.version||m!==n.toneMapping)&&(l.material.needsUpdate=!0,h=T,d=T.version,m=n.toneMapping),l.layers.enableAll(),S.unshift(l,l.geometry,l.material,0,0,null))}function _(S,E){S.getRGB(T0,rL(n)),r.buffers.color.setClear(T0.r,T0.g,T0.b,E,o)}return{getClearColor:function(){return a},setClearColor:function(S,E=1){a.set(S),c=E,_(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(S){c=S,_(a,c)},render:v,addToRenderList:y}}function YH(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),r={},i=d(null);let s=i,o=!1;function a(I,U,L,P,w){let H=!1;const V=h(P,L,U);s!==V&&(s=V,l(s.object)),H=m(I,P,L,w),H&&g(I,P,L,w),w!==null&&e.update(w,n.ELEMENT_ARRAY_BUFFER),(H||o)&&(o=!1,T(I,U,L,P),w!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(w).buffer))}function c(){return n.createVertexArray()}function l(I){return n.bindVertexArray(I)}function u(I){return n.deleteVertexArray(I)}function h(I,U,L){const P=L.wireframe===!0;let w=r[I.id];w===void 0&&(w={},r[I.id]=w);let H=w[U.id];H===void 0&&(H={},w[U.id]=H);let V=H[P];return V===void 0&&(V=d(c()),H[P]=V),V}function d(I){const U=[],L=[],P=[];for(let w=0;w=0){const K=w[z];let j=H[z];if(j===void 0&&(z==="instanceMatrix"&&I.instanceMatrix&&(j=I.instanceMatrix),z==="instanceColor"&&I.instanceColor&&(j=I.instanceColor)),K===void 0||K.attribute!==j||j&&K.data!==j.data)return!0;V++}return s.attributesNum!==V||s.index!==P}function g(I,U,L,P){const w={},H=U.attributes;let V=0;const B=L.getAttributes();for(const z in B)if(B[z].location>=0){let K=H[z];K===void 0&&(z==="instanceMatrix"&&I.instanceMatrix&&(K=I.instanceMatrix),z==="instanceColor"&&I.instanceColor&&(K=I.instanceColor));const j={};j.attribute=K,K&&K.data&&(j.data=K.data),w[z]=j,V++}s.attributes=w,s.attributesNum=V,s.index=P}function v(){const I=s.newAttributes;for(let U=0,L=I.length;U=0){let W=w[B];if(W===void 0&&(B==="instanceMatrix"&&I.instanceMatrix&&(W=I.instanceMatrix),B==="instanceColor"&&I.instanceColor&&(W=I.instanceColor)),W!==void 0){const K=W.normalized,j=W.itemSize,Y=e.get(W);if(Y===void 0)continue;const ge=Y.buffer,Q=Y.type,re=Y.bytesPerElement,be=Q===n.INT||Q===n.UNSIGNED_INT||W.gpuType===BT;if(W.isInterleavedBufferAttribute){const Ae=W.data,Ee=Ae.stride,Le=W.offset;if(Ae.isInstancedInterleavedBuffer){for(let He=0;He0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";M="mediump"}return M==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const u=c(l);u!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",u,"instead."),l=u);const h=t.logarithmicDepthBuffer===!0,d=t.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),m=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),g=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=n.getParameter(n.MAX_TEXTURE_SIZE),y=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),_=n.getParameter(n.MAX_VERTEX_ATTRIBS),S=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),E=n.getParameter(n.MAX_VARYING_VECTORS),T=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),k=g>0,R=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:h,reverseDepthBuffer:d,maxTextures:m,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:y,maxAttributes:_,maxVertexUniforms:S,maxVaryings:E,maxFragmentUniforms:T,vertexTextures:k,maxSamples:R}}function QH(n){const e=this;let t=null,r=0,i=!1,s=!1;const o=new Co,a=new Ft,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(h,d){const m=h.length!==0||d||r!==0||i;return i=d,r=h.length,m},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,d){t=u(h,d,0)},this.setState=function(h,d,m){const g=h.clippingPlanes,v=h.clipIntersection,y=h.clipShadows,_=n.get(h);if(!i||g===null||g.length===0||s&&!y)s?u(null):l();else{const S=s?0:r,E=S*4;let T=_.clippingState||null;c.value=T,T=u(g,d,E,m);for(let k=0;k!==E;++k)T[k]=t[k];_.clippingState=T,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=S}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function u(h,d,m,g){const v=h!==null?h.length:0;let y=null;if(v!==0){if(y=c.value,g!==!0||y===null){const _=m+v*4,S=d.matrixWorldInverse;a.getNormalMatrix(S),(y===null||y.length<_)&&(y=new Float32Array(_));for(let E=0,T=m;E!==v;++E,T+=4)o.copy(h[E]).applyMatrix4(S,a),o.normal.toArray(y,T),y[T+3]=o.constant}c.value=y,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,y}}function eG(n){let e=new WeakMap;function t(o,a){return a===hE?o.mapping=$f:a===fE&&(o.mapping=qf),o}function r(o){if(o&&o.isTexture){const a=o.mapping;if(a===hE||a===fE)if(e.has(o)){const c=e.get(o).texture;return t(c,o.mapping)}else{const c=o.image;if(c&&c.height>0){const l=new h6(c.height);return l.fromEquirectangularTexture(n,o),e.set(o,l),o.addEventListener("dispose",i),t(l.texture,o.mapping)}else return null}}return o}function i(o){const a=o.target;a.removeEventListener("dispose",i);const c=e.get(a);c!==void 0&&(e.delete(a),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}class ey extends Qv{constructor(e=-1,t=1,r=1,i=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=r,this.bottom=i,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,r,i,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let s=r-e,o=r+e,a=i+t,c=i-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=l*this.view.offsetX,o=s+l*this.view.width,a-=u*this.view.offsetY,c=a-u*this.view.height}this.projectionMatrix.makeOrthographic(s,o,a,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const Sf=4,WR=[.125,.215,.35,.446,.526,.582],Pu=20,KS=new ey,jR=new hn;let YS=null,ZS=0,JS=0,QS=!1;const ku=(1+Math.sqrt(5))/2,sf=1/ku,$R=[new xe(-ku,sf,0),new xe(ku,sf,0),new xe(-sf,0,ku),new xe(sf,0,ku),new xe(0,ku,-sf),new xe(0,ku,sf),new xe(-1,1,-1),new xe(1,1,-1),new xe(-1,1,1),new xe(1,1,1)];class qR{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,r=.1,i=100){YS=this._renderer.getRenderTarget(),ZS=this._renderer.getActiveCubeFace(),JS=this._renderer.getActiveMipmapLevel(),QS=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,r,i,s),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=YR(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=KR(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?E:0,E,E),u.setRenderTarget(i),v&&u.render(g,a),u.render(e,a)}g.geometry.dispose(),g.material.dispose(),u.toneMapping=d,u.autoClear=h,e.background=y}_textureToCubeUV(e,t){const r=this._renderer,i=e.mapping===$f||e.mapping===qf;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=YR()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=KR());const s=i?this._cubemapMaterial:this._equirectMaterial,o=new Io(this._lodPlanes[0],s),a=s.uniforms;a.envMap.value=e;const c=this._cubeSize;w0(t,0,0,3*c,2*c),r.setRenderTarget(t),r.render(o,KS)}_applyPMREM(e){const t=this._renderer,r=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let s=1;sPu&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${y} samples when the maximum is set to ${Pu}`);const _=[];let S=0;for(let M=0;ME-Sf?i-E+Sf:0),R=4*(this._cubeSize-T);w0(t,k,R,3*T,2*T),c.setRenderTarget(t),c.render(h,KS)}}function tG(n){const e=[],t=[],r=[];let i=n;const s=n-Sf+1+WR.length;for(let o=0;on-Sf?c=WR[o-n+Sf-1]:o===0&&(c=0),r.push(c);const l=1/(a-2),u=-l,h=1+l,d=[u,u,h,u,h,h,u,u,h,h,u,h],m=6,g=6,v=3,y=2,_=1,S=new Float32Array(v*g*m),E=new Float32Array(y*g*m),T=new Float32Array(_*g*m);for(let R=0;R2?0:-1,C=[M,O,0,M+2/3,O,0,M+2/3,O+1,0,M,O,0,M+2/3,O+1,0,M,O+1,0];S.set(C,v*g*R),E.set(d,y*g*R);const I=[R,R,R,R,R,R];T.set(I,_*g*R)}const k=new jo;k.setAttribute("position",new er(S,v)),k.setAttribute("uv",new er(E,y)),k.setAttribute("faceIndex",new er(T,_)),e.push(k),i>Sf&&i--}return{lodPlanes:e,sizeLods:t,sigmas:r}}function XR(n,e,t){const r=new Gs(n,e,t);return r.texture.mapping=Kv,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function w0(n,e,t,r,i){n.viewport.set(e,t,r,i),n.scissor.set(e,t,r,i)}function nG(n,e,t){const r=new Float32Array(Pu),i=new xe(0,1,0);return new qi({name:"SphericalGaussianBlur",defines:{n:Pu,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:qT(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:Po,depthTest:!1,depthWrite:!1})}function KR(){return new qi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:qT(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:Po,depthTest:!1,depthWrite:!1})}function YR(){return new qi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:qT(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:Po,depthTest:!1,depthWrite:!1})}function qT(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function rG(n){let e=new WeakMap,t=null;function r(a){if(a&&a.isTexture){const c=a.mapping,l=c===hE||c===fE,u=c===$f||c===qf;if(l||u){let h=e.get(a);const d=h!==void 0?h.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==d)return t===null&&(t=new qR(n)),h=l?t.fromEquirectangular(a,h):t.fromCubemap(a,h),h.texture.pmremVersion=a.pmremVersion,e.set(a,h),h.texture;if(h!==void 0)return h.texture;{const m=a.image;return l&&m&&m.height>0||u&&m&&i(m)?(t===null&&(t=new qR(n)),h=l?t.fromEquirectangular(a):t.fromCubemap(a),h.texture.pmremVersion=a.pmremVersion,e.set(a,h),a.addEventListener("dispose",s),h.texture):null}}}return a}function i(a){let c=0;const l=6;for(let u=0;ue.maxTextureSize&&(R=Math.ceil(k/e.maxTextureSize),k=e.maxTextureSize);const M=new Float32Array(k*R*4*h),O=new QO(M,k,R,h);O.type=Aa,O.needsUpdate=!0;const C=T*4;for(let U=0;U0)return n;const i=e*t;let s=JR[i];if(s===void 0&&(s=new Float32Array(i),JR[i]=s),e!==0){r.toArray(s,0);for(let o=1,a=0;o!==e;++o)a+=t,n[o].toArray(s,a)}return s}function jr(n,e){if(n.length!==e.length)return!1;for(let t=0,r=n.length;t":" "} ${a}: ${t[o]}`)}return r.join(` +`)}const s2=new Ft;function rW(n){dn._getMatrix(s2,dn.workingColorSpace,n);const e=`mat3( ${s2.elements.map(t=>t.toFixed(4))} )`;switch(dn.getTransfer(n)){case Zv:return[e,"LinearTransferOETF"];case Cn:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function o2(n,e,t){const r=n.getShaderParameter(e,n.COMPILE_STATUS),i=n.getShaderInfoLog(e).trim();if(r&&i==="")return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const o=parseInt(s[1]);return t.toUpperCase()+` + +`+i+` + +`+nW(n.getShaderSource(e),o)}else return i}function iW(n,e){const t=rW(e);return[`vec4 ${n}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` +`)}function sW(n,e){let t;switch(e){case c8:t="Linear";break;case l8:t="Reinhard";break;case u8:t="Cineon";break;case UO:t="ACESFilmic";break;case f8:t="AgX";break;case d8:t="Neutral";break;case h8:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const A0=new xe;function oW(){dn.getLuminanceCoefficients(A0);const n=A0.x.toFixed(4),e=A0.y.toFixed(4),t=A0.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` +`)}function aW(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(pp).join(` +`)}function cW(n){const e=[];for(const t in n){const r=n[t];r!==!1&&e.push("#define "+t+" "+r)}return e.join(` +`)}function lW(n,e){const t={},r=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function VE(n){return n.replace(uW,fW)}const hW=new Map;function fW(n,e){let t=Vt[e];if(t===void 0){const r=hW.get(e);if(r!==void 0)t=Vt[r],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,r);else throw new Error("Can not resolve #include <"+e+">")}return VE(t)}const dW=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function l2(n){return n.replace(dW,pW)}function pW(n,e,t,r){let i="";for(let s=parseInt(e);s0&&(y+=` +`),_=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g].filter(pp).join(` +`),_.length>0&&(_+=` +`)):(y=[u2(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(pp).join(` +`),_=[u2(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+u:"",t.envMap?"#define "+h:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Ra?"#define TONE_MAPPING":"",t.toneMapping!==Ra?Vt.tonemapping_pars_fragment:"",t.toneMapping!==Ra?sW("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Vt.colorspace_pars_fragment,iW("linearToOutputTexel",t.outputColorSpace),oW(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(pp).join(` +`)),o=VE(o),o=a2(o,t),o=c2(o,t),a=VE(a),a=a2(a,t),a=c2(a,t),o=l2(o),a=l2(a),t.isRawShaderMaterial!==!0&&(S=`#version 300 es +`,y=[m,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+y,_=["#define varying in",t.glslVersion===ER?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===ER?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+_);const E=S+y+o,T=S+_+a,k=i2(i,i.VERTEX_SHADER,E),R=i2(i,i.FRAGMENT_SHADER,T);i.attachShader(v,k),i.attachShader(v,R),t.index0AttributeName!==void 0?i.bindAttribLocation(v,0,t.index0AttributeName):t.morphTargets===!0&&i.bindAttribLocation(v,0,"position"),i.linkProgram(v);function M(U){if(n.debug.checkShaderErrors){const L=i.getProgramInfoLog(v).trim(),P=i.getShaderInfoLog(k).trim(),w=i.getShaderInfoLog(R).trim();let H=!0,V=!0;if(i.getProgramParameter(v,i.LINK_STATUS)===!1)if(H=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(i,v,k,R);else{const B=o2(i,k,"vertex"),z=o2(i,R,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(v,i.VALIDATE_STATUS)+` + +Material Name: `+U.name+` +Material Type: `+U.type+` + +Program Info Log: `+L+` +`+B+` +`+z)}else L!==""?console.warn("THREE.WebGLProgram: Program Info Log:",L):(P===""||w==="")&&(V=!1);V&&(U.diagnostics={runnable:H,programLog:L,vertexShader:{log:P,prefix:y},fragmentShader:{log:w,prefix:_}})}i.deleteShader(k),i.deleteShader(R),O=new m_(i,v),C=lW(i,v)}let O;this.getUniforms=function(){return O===void 0&&M(this),O};let C;this.getAttributes=function(){return C===void 0&&M(this),C};let I=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return I===!1&&(I=i.getProgramParameter(v,eW)),I},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=tW++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=k,this.fragmentShader=R,this}let SW=0;class EW{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(t),s=this._getShaderStage(r),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const r of t)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let r=t.get(e);return r===void 0&&(r=new Set,t.set(e,r)),r}_getShaderStage(e){const t=this.shaderCache;let r=t.get(e);return r===void 0&&(r=new bW(e),t.set(e,r)),r}}class bW{constructor(e){this.id=SW++,this.code=e,this.usedTimes=0}}function TW(n,e,t,r,i,s,o){const a=new Of,c=new EW,l=new Set,u=[],h=i.logarithmicDepthBuffer,d=i.vertexTextures;let m=i.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(C){return l.add(C),C===0?"uv":`uv${C}`}function y(C,I,U,L,P){const w=L.fog,H=P.geometry,V=C.isMeshStandardMaterial?L.environment:null,B=(C.isMeshStandardMaterial?t:e).get(C.envMap||V),z=B&&B.mapping===Kv?B.image.height:null,W=g[C.type];C.precision!==null&&(m=i.getMaxPrecision(C.precision),m!==C.precision&&console.warn("THREE.WebGLProgram.getParameters:",C.precision,"not supported, using",m,"instead."));const K=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,j=K!==void 0?K.length:0;let Y=0;H.morphAttributes.position!==void 0&&(Y=1),H.morphAttributes.normal!==void 0&&(Y=2),H.morphAttributes.color!==void 0&&(Y=3);let ge,Q,re,be;if(W){const pn=ya[W];ge=pn.vertexShader,Q=pn.fragmentShader}else ge=C.vertexShader,Q=C.fragmentShader,c.update(C),re=c.getVertexShaderID(C),be=c.getFragmentShaderID(C);const Ae=n.getRenderTarget(),Ee=n.state.buffers.depth.getReversed(),Le=P.isInstancedMesh===!0,He=P.isBatchedMesh===!0,qe=!!C.map,it=!!C.matcap,De=!!B,A=!!C.aoMap,ie=!!C.lightMap,te=!!C.bumpMap,X=!!C.normalMap,$=!!C.displacementMap,ne=!!C.emissiveMap,ae=!!C.metalnessMap,G=!!C.roughnessMap,D=C.anisotropy>0,ee=C.clearcoat>0,he=C.dispersion>0,ce=C.iridescence>0,_e=C.sheen>0,ze=C.transmission>0,Oe=D&&!!C.anisotropyMap,Ge=ee&&!!C.clearcoatMap,Dt=ee&&!!C.clearcoatNormalMap,Pe=ee&&!!C.clearcoatRoughnessMap,nt=ce&&!!C.iridescenceMap,et=ce&&!!C.iridescenceThicknessMap,xt=_e&&!!C.sheenColorMap,rt=_e&&!!C.sheenRoughnessMap,Rt=!!C.specularMap,kt=!!C.specularColorMap,bn=!!C.specularIntensityMap,le=ze&&!!C.transmissionMap,je=ze&&!!C.thicknessMap,Ce=!!C.gradientMap,Ne=!!C.alphaMap,$e=C.alphaTest>0,Je=!!C.alphaHash,Nt=!!C.extensions;let $n=Ra;C.toneMapped&&(Ae===null||Ae.isXRRenderTarget===!0)&&($n=n.toneMapping);const Pr={shaderID:W,shaderType:C.type,shaderName:C.name,vertexShader:ge,fragmentShader:Q,defines:C.defines,customVertexShaderID:re,customFragmentShaderID:be,isRawShaderMaterial:C.isRawShaderMaterial===!0,glslVersion:C.glslVersion,precision:m,batching:He,batchingColor:He&&P._colorsTexture!==null,instancing:Le,instancingColor:Le&&P.instanceColor!==null,instancingMorph:Le&&P.morphTexture!==null,supportsVertexTextures:d,outputColorSpace:Ae===null?n.outputColorSpace:Ae.isXRRenderTarget===!0?Ae.texture.colorSpace:Ql,alphaToCoverage:!!C.alphaToCoverage,map:qe,matcap:it,envMap:De,envMapMode:De&&B.mapping,envMapCubeUVHeight:z,aoMap:A,lightMap:ie,bumpMap:te,normalMap:X,displacementMap:d&&$,emissiveMap:ne,normalMapObjectSpace:X&&C.normalMapType===g8,normalMapTangentSpace:X&&C.normalMapType===KO,metalnessMap:ae,roughnessMap:G,anisotropy:D,anisotropyMap:Oe,clearcoat:ee,clearcoatMap:Ge,clearcoatNormalMap:Dt,clearcoatRoughnessMap:Pe,dispersion:he,iridescence:ce,iridescenceMap:nt,iridescenceThicknessMap:et,sheen:_e,sheenColorMap:xt,sheenRoughnessMap:rt,specularMap:Rt,specularColorMap:kt,specularIntensityMap:bn,transmission:ze,transmissionMap:le,thicknessMap:je,gradientMap:Ce,opaque:C.transparent===!1&&C.blending===kf&&C.alphaToCoverage===!1,alphaMap:Ne,alphaTest:$e,alphaHash:Je,combine:C.combine,mapUv:qe&&v(C.map.channel),aoMapUv:A&&v(C.aoMap.channel),lightMapUv:ie&&v(C.lightMap.channel),bumpMapUv:te&&v(C.bumpMap.channel),normalMapUv:X&&v(C.normalMap.channel),displacementMapUv:$&&v(C.displacementMap.channel),emissiveMapUv:ne&&v(C.emissiveMap.channel),metalnessMapUv:ae&&v(C.metalnessMap.channel),roughnessMapUv:G&&v(C.roughnessMap.channel),anisotropyMapUv:Oe&&v(C.anisotropyMap.channel),clearcoatMapUv:Ge&&v(C.clearcoatMap.channel),clearcoatNormalMapUv:Dt&&v(C.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Pe&&v(C.clearcoatRoughnessMap.channel),iridescenceMapUv:nt&&v(C.iridescenceMap.channel),iridescenceThicknessMapUv:et&&v(C.iridescenceThicknessMap.channel),sheenColorMapUv:xt&&v(C.sheenColorMap.channel),sheenRoughnessMapUv:rt&&v(C.sheenRoughnessMap.channel),specularMapUv:Rt&&v(C.specularMap.channel),specularColorMapUv:kt&&v(C.specularColorMap.channel),specularIntensityMapUv:bn&&v(C.specularIntensityMap.channel),transmissionMapUv:le&&v(C.transmissionMap.channel),thicknessMapUv:je&&v(C.thicknessMap.channel),alphaMapUv:Ne&&v(C.alphaMap.channel),vertexTangents:!!H.attributes.tangent&&(X||D),vertexColors:C.vertexColors,vertexAlphas:C.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,pointsUvs:P.isPoints===!0&&!!H.attributes.uv&&(qe||Ne),fog:!!w,useFog:C.fog===!0,fogExp2:!!w&&w.isFogExp2,flatShading:C.flatShading===!0,sizeAttenuation:C.sizeAttenuation===!0,logarithmicDepthBuffer:h,reverseDepthBuffer:Ee,skinning:P.isSkinnedMesh===!0,morphTargets:H.morphAttributes.position!==void 0,morphNormals:H.morphAttributes.normal!==void 0,morphColors:H.morphAttributes.color!==void 0,morphTargetsCount:j,morphTextureStride:Y,numDirLights:I.directional.length,numPointLights:I.point.length,numSpotLights:I.spot.length,numSpotLightMaps:I.spotLightMap.length,numRectAreaLights:I.rectArea.length,numHemiLights:I.hemi.length,numDirLightShadows:I.directionalShadowMap.length,numPointLightShadows:I.pointShadowMap.length,numSpotLightShadows:I.spotShadowMap.length,numSpotLightShadowsWithMaps:I.numSpotLightShadowsWithMaps,numLightProbes:I.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:C.dithering,shadowMapEnabled:n.shadowMap.enabled&&U.length>0,shadowMapType:n.shadowMap.type,toneMapping:$n,decodeVideoTexture:qe&&C.map.isVideoTexture===!0&&dn.getTransfer(C.map.colorSpace)===Cn,decodeVideoTextureEmissive:ne&&C.emissiveMap.isVideoTexture===!0&&dn.getTransfer(C.emissiveMap.colorSpace)===Cn,premultipliedAlpha:C.premultipliedAlpha,doubleSided:C.side===Us,flipSided:C.side===ci,useDepthPacking:C.depthPacking>=0,depthPacking:C.depthPacking||0,index0AttributeName:C.index0AttributeName,extensionClipCullDistance:Nt&&C.extensions.clipCullDistance===!0&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Nt&&C.extensions.multiDraw===!0||He)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:C.customProgramCacheKey()};return Pr.vertexUv1s=l.has(1),Pr.vertexUv2s=l.has(2),Pr.vertexUv3s=l.has(3),l.clear(),Pr}function _(C){const I=[];if(C.shaderID?I.push(C.shaderID):(I.push(C.customVertexShaderID),I.push(C.customFragmentShaderID)),C.defines!==void 0)for(const U in C.defines)I.push(U),I.push(C.defines[U]);return C.isRawShaderMaterial===!1&&(S(I,C),E(I,C),I.push(n.outputColorSpace)),I.push(C.customProgramCacheKey),I.join()}function S(C,I){C.push(I.precision),C.push(I.outputColorSpace),C.push(I.envMapMode),C.push(I.envMapCubeUVHeight),C.push(I.mapUv),C.push(I.alphaMapUv),C.push(I.lightMapUv),C.push(I.aoMapUv),C.push(I.bumpMapUv),C.push(I.normalMapUv),C.push(I.displacementMapUv),C.push(I.emissiveMapUv),C.push(I.metalnessMapUv),C.push(I.roughnessMapUv),C.push(I.anisotropyMapUv),C.push(I.clearcoatMapUv),C.push(I.clearcoatNormalMapUv),C.push(I.clearcoatRoughnessMapUv),C.push(I.iridescenceMapUv),C.push(I.iridescenceThicknessMapUv),C.push(I.sheenColorMapUv),C.push(I.sheenRoughnessMapUv),C.push(I.specularMapUv),C.push(I.specularColorMapUv),C.push(I.specularIntensityMapUv),C.push(I.transmissionMapUv),C.push(I.thicknessMapUv),C.push(I.combine),C.push(I.fogExp2),C.push(I.sizeAttenuation),C.push(I.morphTargetsCount),C.push(I.morphAttributeCount),C.push(I.numDirLights),C.push(I.numPointLights),C.push(I.numSpotLights),C.push(I.numSpotLightMaps),C.push(I.numHemiLights),C.push(I.numRectAreaLights),C.push(I.numDirLightShadows),C.push(I.numPointLightShadows),C.push(I.numSpotLightShadows),C.push(I.numSpotLightShadowsWithMaps),C.push(I.numLightProbes),C.push(I.shadowMapType),C.push(I.toneMapping),C.push(I.numClippingPlanes),C.push(I.numClipIntersection),C.push(I.depthPacking)}function E(C,I){a.disableAll(),I.supportsVertexTextures&&a.enable(0),I.instancing&&a.enable(1),I.instancingColor&&a.enable(2),I.instancingMorph&&a.enable(3),I.matcap&&a.enable(4),I.envMap&&a.enable(5),I.normalMapObjectSpace&&a.enable(6),I.normalMapTangentSpace&&a.enable(7),I.clearcoat&&a.enable(8),I.iridescence&&a.enable(9),I.alphaTest&&a.enable(10),I.vertexColors&&a.enable(11),I.vertexAlphas&&a.enable(12),I.vertexUv1s&&a.enable(13),I.vertexUv2s&&a.enable(14),I.vertexUv3s&&a.enable(15),I.vertexTangents&&a.enable(16),I.anisotropy&&a.enable(17),I.alphaHash&&a.enable(18),I.batching&&a.enable(19),I.dispersion&&a.enable(20),I.batchingColor&&a.enable(21),C.push(a.mask),a.disableAll(),I.fog&&a.enable(0),I.useFog&&a.enable(1),I.flatShading&&a.enable(2),I.logarithmicDepthBuffer&&a.enable(3),I.reverseDepthBuffer&&a.enable(4),I.skinning&&a.enable(5),I.morphTargets&&a.enable(6),I.morphNormals&&a.enable(7),I.morphColors&&a.enable(8),I.premultipliedAlpha&&a.enable(9),I.shadowMapEnabled&&a.enable(10),I.doubleSided&&a.enable(11),I.flipSided&&a.enable(12),I.useDepthPacking&&a.enable(13),I.dithering&&a.enable(14),I.transmission&&a.enable(15),I.sheen&&a.enable(16),I.opaque&&a.enable(17),I.pointsUvs&&a.enable(18),I.decodeVideoTexture&&a.enable(19),I.decodeVideoTextureEmissive&&a.enable(20),I.alphaToCoverage&&a.enable(21),C.push(a.mask)}function T(C){const I=g[C.type];let U;if(I){const L=ya[I];U=a6.clone(L.uniforms)}else U=C.uniforms;return U}function k(C,I){let U;for(let L=0,P=u.length;L0?r.push(_):m.transparent===!0?i.push(_):t.push(_)}function c(h,d,m,g,v,y){const _=o(h,d,m,g,v,y);m.transmission>0?r.unshift(_):m.transparent===!0?i.unshift(_):t.unshift(_)}function l(h,d){t.length>1&&t.sort(h||AW),r.length>1&&r.sort(d||h2),i.length>1&&i.sort(d||h2)}function u(){for(let h=e,d=n.length;h=s.length?(o=new f2,s.push(o)):o=s[i],o}function t(){n=new WeakMap}return{get:e,dispose:t}}function CW(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new xe,color:new hn};break;case"SpotLight":t={position:new xe,direction:new xe,color:new hn,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new xe,color:new hn,distance:0,decay:0};break;case"HemisphereLight":t={direction:new xe,skyColor:new hn,groundColor:new hn};break;case"RectAreaLight":t={color:new hn,position:new xe,halfWidth:new xe,halfHeight:new xe};break}return n[e.id]=t,t}}}function RW(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Et};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Et};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Et,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let kW=0;function NW(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function IW(n){const e=new CW,t=RW(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)r.probe.push(new xe);const i=new xe,s=new hr,o=new hr;function a(l){let u=0,h=0,d=0;for(let C=0;C<9;C++)r.probe[C].set(0,0,0);let m=0,g=0,v=0,y=0,_=0,S=0,E=0,T=0,k=0,R=0,M=0;l.sort(NW);for(let C=0,I=l.length;C0&&(n.has("OES_texture_float_linear")===!0?(r.rectAreaLTC1=Xe.LTC_FLOAT_1,r.rectAreaLTC2=Xe.LTC_FLOAT_2):(r.rectAreaLTC1=Xe.LTC_HALF_1,r.rectAreaLTC2=Xe.LTC_HALF_2)),r.ambient[0]=u,r.ambient[1]=h,r.ambient[2]=d;const O=r.hash;(O.directionalLength!==m||O.pointLength!==g||O.spotLength!==v||O.rectAreaLength!==y||O.hemiLength!==_||O.numDirectionalShadows!==S||O.numPointShadows!==E||O.numSpotShadows!==T||O.numSpotMaps!==k||O.numLightProbes!==M)&&(r.directional.length=m,r.spot.length=v,r.rectArea.length=y,r.point.length=g,r.hemi.length=_,r.directionalShadow.length=S,r.directionalShadowMap.length=S,r.pointShadow.length=E,r.pointShadowMap.length=E,r.spotShadow.length=T,r.spotShadowMap.length=T,r.directionalShadowMatrix.length=S,r.pointShadowMatrix.length=E,r.spotLightMatrix.length=T+k-R,r.spotLightMap.length=k,r.numSpotLightShadowsWithMaps=R,r.numLightProbes=M,O.directionalLength=m,O.pointLength=g,O.spotLength=v,O.rectAreaLength=y,O.hemiLength=_,O.numDirectionalShadows=S,O.numPointShadows=E,O.numSpotShadows=T,O.numSpotMaps=k,O.numLightProbes=M,r.version=kW++)}function c(l,u){let h=0,d=0,m=0,g=0,v=0;const y=u.matrixWorldInverse;for(let _=0,S=l.length;_=o.length?(a=new d2(n),o.push(a)):a=o[s],a}function r(){e=new WeakMap}return{get:t,dispose:r}}class LW extends Kc{static get type(){return"MeshDepthMaterial"}constructor(e){super(),this.isMeshDepthMaterial=!0,this.depthPacking=dh,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class PW extends Kc{static get type(){return"MeshDistanceMaterial"}constructor(e){super(),this.isMeshDistanceMaterial=!0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const DW=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,UW=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`;function FW(n,e,t){let r=new sL;const i=new Et,s=new Et,o=new xr,a=new LW({depthPacking:m8}),c=new PW,l={},u=t.maxTextureSize,h={[zc]:ci,[ci]:zc,[Us]:Us},d=new qi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Et},radius:{value:4}},vertexShader:DW,fragmentShader:UW}),m=d.clone();m.defines.HORIZONTAL_PASS=1;const g=new jo;g.setAttribute("position",new er(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Io(g,d),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=FT;let _=this.type;this.render=function(R,M,O){if(y.enabled===!1||y.autoUpdate===!1&&y.needsUpdate===!1||R.length===0)return;const C=n.getRenderTarget(),I=n.getActiveCubeFace(),U=n.getActiveMipmapLevel(),L=n.state;L.setBlending(Po),L.buffers.color.setClear(1,1,1,1),L.buffers.depth.setTest(!0),L.setScissorTest(!1);const P=_!==ga&&this.type===ga,w=_===ga&&this.type!==ga;for(let H=0,V=R.length;Hu||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/W.x),i.x=s.x*W.x,z.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/W.y),i.y=s.y*W.y,z.mapSize.y=s.y)),z.map===null||P===!0||w===!0){const j=this.type!==ga?{minFilter:Er,magFilter:Er}:{};z.map!==null&&z.map.dispose(),z.map=new Gs(i.x,i.y,j),z.map.texture.name=B.name+".shadowMap",z.camera.updateProjectionMatrix()}n.setRenderTarget(z.map),n.clear();const K=z.getViewportCount();for(let j=0;j0||M.map&&M.alphaTest>0){const L=I.uuid,P=M.uuid;let w=l[L];w===void 0&&(w={},l[L]=w);let H=w[P];H===void 0&&(H=I.clone(),w[P]=H,M.addEventListener("dispose",k)),I=H}if(I.visible=M.visible,I.wireframe=M.wireframe,C===ga?I.side=M.shadowSide!==null?M.shadowSide:M.side:I.side=M.shadowSide!==null?M.shadowSide:h[M.side],I.alphaMap=M.alphaMap,I.alphaTest=M.alphaTest,I.map=M.map,I.clipShadows=M.clipShadows,I.clippingPlanes=M.clippingPlanes,I.clipIntersection=M.clipIntersection,I.displacementMap=M.displacementMap,I.displacementScale=M.displacementScale,I.displacementBias=M.displacementBias,I.wireframeLinewidth=M.wireframeLinewidth,I.linewidth=M.linewidth,O.isPointLight===!0&&I.isMeshDistanceMaterial===!0){const L=n.properties.get(I);L.light=O}return I}function T(R,M,O,C,I){if(R.visible===!1)return;if(R.layers.test(M.layers)&&(R.isMesh||R.isLine||R.isPoints)&&(R.castShadow||R.receiveShadow&&I===ga)&&(!R.frustumCulled||r.intersectsObject(R))){R.modelViewMatrix.multiplyMatrices(O.matrixWorldInverse,R.matrixWorld);const P=e.update(R),w=R.material;if(Array.isArray(w)){const H=P.groups;for(let V=0,B=H.length;V=1):z.indexOf("OpenGL ES")!==-1&&(B=parseFloat(/^OpenGL ES (\d)/.exec(z)[1]),V=B>=2);let W=null,K={};const j=n.getParameter(n.SCISSOR_BOX),Y=n.getParameter(n.VIEWPORT),ge=new xr().fromArray(j),Q=new xr().fromArray(Y);function re(le,je,Ce,Ne){const $e=new Uint8Array(4),Je=n.createTexture();n.bindTexture(le,Je),n.texParameteri(le,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(le,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let Nt=0;Nt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Et,u=new WeakMap;let h;const d=new WeakMap;let m=!1;try{m=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(G,D){return m?new OffscreenCanvas(G,D):Up("canvas")}function v(G,D,ee){let he=1;const ce=ae(G);if((ce.width>ee||ce.height>ee)&&(he=ee/Math.max(ce.width,ce.height)),he<1)if(typeof HTMLImageElement<"u"&&G instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&G instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&G instanceof ImageBitmap||typeof VideoFrame<"u"&&G instanceof VideoFrame){const _e=Math.floor(he*ce.width),ze=Math.floor(he*ce.height);h===void 0&&(h=g(_e,ze));const Oe=D?g(_e,ze):h;return Oe.width=_e,Oe.height=ze,Oe.getContext("2d").drawImage(G,0,0,_e,ze),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+ce.width+"x"+ce.height+") to ("+_e+"x"+ze+")."),Oe}else return"data"in G&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+ce.width+"x"+ce.height+")."),G;return G}function y(G){return G.generateMipmaps}function _(G){n.generateMipmap(G)}function S(G){return G.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:G.isWebGL3DRenderTarget?n.TEXTURE_3D:G.isWebGLArrayRenderTarget||G.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function E(G,D,ee,he,ce=!1){if(G!==null){if(n[G]!==void 0)return n[G];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+G+"'")}let _e=D;if(D===n.RED&&(ee===n.FLOAT&&(_e=n.R32F),ee===n.HALF_FLOAT&&(_e=n.R16F),ee===n.UNSIGNED_BYTE&&(_e=n.R8)),D===n.RED_INTEGER&&(ee===n.UNSIGNED_BYTE&&(_e=n.R8UI),ee===n.UNSIGNED_SHORT&&(_e=n.R16UI),ee===n.UNSIGNED_INT&&(_e=n.R32UI),ee===n.BYTE&&(_e=n.R8I),ee===n.SHORT&&(_e=n.R16I),ee===n.INT&&(_e=n.R32I)),D===n.RG&&(ee===n.FLOAT&&(_e=n.RG32F),ee===n.HALF_FLOAT&&(_e=n.RG16F),ee===n.UNSIGNED_BYTE&&(_e=n.RG8)),D===n.RG_INTEGER&&(ee===n.UNSIGNED_BYTE&&(_e=n.RG8UI),ee===n.UNSIGNED_SHORT&&(_e=n.RG16UI),ee===n.UNSIGNED_INT&&(_e=n.RG32UI),ee===n.BYTE&&(_e=n.RG8I),ee===n.SHORT&&(_e=n.RG16I),ee===n.INT&&(_e=n.RG32I)),D===n.RGB_INTEGER&&(ee===n.UNSIGNED_BYTE&&(_e=n.RGB8UI),ee===n.UNSIGNED_SHORT&&(_e=n.RGB16UI),ee===n.UNSIGNED_INT&&(_e=n.RGB32UI),ee===n.BYTE&&(_e=n.RGB8I),ee===n.SHORT&&(_e=n.RGB16I),ee===n.INT&&(_e=n.RGB32I)),D===n.RGBA_INTEGER&&(ee===n.UNSIGNED_BYTE&&(_e=n.RGBA8UI),ee===n.UNSIGNED_SHORT&&(_e=n.RGBA16UI),ee===n.UNSIGNED_INT&&(_e=n.RGBA32UI),ee===n.BYTE&&(_e=n.RGBA8I),ee===n.SHORT&&(_e=n.RGBA16I),ee===n.INT&&(_e=n.RGBA32I)),D===n.RGB&&ee===n.UNSIGNED_INT_5_9_9_9_REV&&(_e=n.RGB9_E5),D===n.RGBA){const ze=ce?Zv:dn.getTransfer(he);ee===n.FLOAT&&(_e=n.RGBA32F),ee===n.HALF_FLOAT&&(_e=n.RGBA16F),ee===n.UNSIGNED_BYTE&&(_e=ze===Cn?n.SRGB8_ALPHA8:n.RGBA8),ee===n.UNSIGNED_SHORT_4_4_4_4&&(_e=n.RGBA4),ee===n.UNSIGNED_SHORT_5_5_5_1&&(_e=n.RGB5_A1)}return(_e===n.R16F||_e===n.R32F||_e===n.RG16F||_e===n.RG32F||_e===n.RGBA16F||_e===n.RGBA32F)&&e.get("EXT_color_buffer_float"),_e}function T(G,D){let ee;return G?D===null||D===zl||D===Zu?ee=n.DEPTH24_STENCIL8:D===Aa?ee=n.DEPTH32F_STENCIL8:D===Pp&&(ee=n.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):D===null||D===zl||D===Zu?ee=n.DEPTH_COMPONENT24:D===Aa?ee=n.DEPTH_COMPONENT32F:D===Pp&&(ee=n.DEPTH_COMPONENT16),ee}function k(G,D){return y(G)===!0||G.isFramebufferTexture&&G.minFilter!==Er&&G.minFilter!==fs?Math.log2(Math.max(D.width,D.height))+1:G.mipmaps!==void 0&&G.mipmaps.length>0?G.mipmaps.length:G.isCompressedTexture&&Array.isArray(G.image)?D.mipmaps.length:1}function R(G){const D=G.target;D.removeEventListener("dispose",R),O(D),D.isVideoTexture&&u.delete(D)}function M(G){const D=G.target;D.removeEventListener("dispose",M),I(D)}function O(G){const D=r.get(G);if(D.__webglInit===void 0)return;const ee=G.source,he=d.get(ee);if(he){const ce=he[D.__cacheKey];ce.usedTimes--,ce.usedTimes===0&&C(G),Object.keys(he).length===0&&d.delete(ee)}r.remove(G)}function C(G){const D=r.get(G);n.deleteTexture(D.__webglTexture);const ee=G.source,he=d.get(ee);delete he[D.__cacheKey],o.memory.textures--}function I(G){const D=r.get(G);if(G.depthTexture&&(G.depthTexture.dispose(),r.remove(G.depthTexture)),G.isWebGLCubeRenderTarget)for(let he=0;he<6;he++){if(Array.isArray(D.__webglFramebuffer[he]))for(let ce=0;ce=i.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+G+" texture units while this GPU supports only "+i.maxTextures),U+=1,G}function w(G){const D=[];return D.push(G.wrapS),D.push(G.wrapT),D.push(G.wrapR||0),D.push(G.magFilter),D.push(G.minFilter),D.push(G.anisotropy),D.push(G.internalFormat),D.push(G.format),D.push(G.type),D.push(G.generateMipmaps),D.push(G.premultiplyAlpha),D.push(G.flipY),D.push(G.unpackAlignment),D.push(G.colorSpace),D.join()}function H(G,D){const ee=r.get(G);if(G.isVideoTexture&&$(G),G.isRenderTargetTexture===!1&&G.version>0&&ee.__version!==G.version){const he=G.image;if(he===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(he.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Q(ee,G,D);return}}t.bindTexture(n.TEXTURE_2D,ee.__webglTexture,n.TEXTURE0+D)}function V(G,D){const ee=r.get(G);if(G.version>0&&ee.__version!==G.version){Q(ee,G,D);return}t.bindTexture(n.TEXTURE_2D_ARRAY,ee.__webglTexture,n.TEXTURE0+D)}function B(G,D){const ee=r.get(G);if(G.version>0&&ee.__version!==G.version){Q(ee,G,D);return}t.bindTexture(n.TEXTURE_3D,ee.__webglTexture,n.TEXTURE0+D)}function z(G,D){const ee=r.get(G);if(G.version>0&&ee.__version!==G.version){re(ee,G,D);return}t.bindTexture(n.TEXTURE_CUBE_MAP,ee.__webglTexture,n.TEXTURE0+D)}const W={[dE]:n.REPEAT,[Bu]:n.CLAMP_TO_EDGE,[pE]:n.MIRRORED_REPEAT},K={[Er]:n.NEAREST,[p8]:n.NEAREST_MIPMAP_NEAREST,[o0]:n.NEAREST_MIPMAP_LINEAR,[fs]:n.LINEAR,[CS]:n.LINEAR_MIPMAP_NEAREST,[zu]:n.LINEAR_MIPMAP_LINEAR},j={[_8]:n.NEVER,[b8]:n.ALWAYS,[v8]:n.LESS,[YO]:n.LEQUAL,[y8]:n.EQUAL,[E8]:n.GEQUAL,[x8]:n.GREATER,[S8]:n.NOTEQUAL};function Y(G,D){if(D.type===Aa&&e.has("OES_texture_float_linear")===!1&&(D.magFilter===fs||D.magFilter===CS||D.magFilter===o0||D.magFilter===zu||D.minFilter===fs||D.minFilter===CS||D.minFilter===o0||D.minFilter===zu)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(G,n.TEXTURE_WRAP_S,W[D.wrapS]),n.texParameteri(G,n.TEXTURE_WRAP_T,W[D.wrapT]),(G===n.TEXTURE_3D||G===n.TEXTURE_2D_ARRAY)&&n.texParameteri(G,n.TEXTURE_WRAP_R,W[D.wrapR]),n.texParameteri(G,n.TEXTURE_MAG_FILTER,K[D.magFilter]),n.texParameteri(G,n.TEXTURE_MIN_FILTER,K[D.minFilter]),D.compareFunction&&(n.texParameteri(G,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(G,n.TEXTURE_COMPARE_FUNC,j[D.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(D.magFilter===Er||D.minFilter!==o0&&D.minFilter!==zu||D.type===Aa&&e.has("OES_texture_float_linear")===!1)return;if(D.anisotropy>1||r.get(D).__currentAnisotropy){const ee=e.get("EXT_texture_filter_anisotropic");n.texParameterf(G,ee.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(D.anisotropy,i.getMaxAnisotropy())),r.get(D).__currentAnisotropy=D.anisotropy}}}function ge(G,D){let ee=!1;G.__webglInit===void 0&&(G.__webglInit=!0,D.addEventListener("dispose",R));const he=D.source;let ce=d.get(he);ce===void 0&&(ce={},d.set(he,ce));const _e=w(D);if(_e!==G.__cacheKey){ce[_e]===void 0&&(ce[_e]={texture:n.createTexture(),usedTimes:0},o.memory.textures++,ee=!0),ce[_e].usedTimes++;const ze=ce[G.__cacheKey];ze!==void 0&&(ce[G.__cacheKey].usedTimes--,ze.usedTimes===0&&C(D)),G.__cacheKey=_e,G.__webglTexture=ce[_e].texture}return ee}function Q(G,D,ee){let he=n.TEXTURE_2D;(D.isDataArrayTexture||D.isCompressedArrayTexture)&&(he=n.TEXTURE_2D_ARRAY),D.isData3DTexture&&(he=n.TEXTURE_3D);const ce=ge(G,D),_e=D.source;t.bindTexture(he,G.__webglTexture,n.TEXTURE0+ee);const ze=r.get(_e);if(_e.version!==ze.__version||ce===!0){t.activeTexture(n.TEXTURE0+ee);const Oe=dn.getPrimaries(dn.workingColorSpace),Ge=D.colorSpace===ba?null:dn.getPrimaries(D.colorSpace),Dt=D.colorSpace===ba||Oe===Ge?n.NONE:n.BROWSER_DEFAULT_WEBGL;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,D.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,D.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,Dt);let Pe=v(D.image,!1,i.maxTextureSize);Pe=ne(D,Pe);const nt=s.convert(D.format,D.colorSpace),et=s.convert(D.type);let xt=E(D.internalFormat,nt,et,D.colorSpace,D.isVideoTexture);Y(he,D);let rt;const Rt=D.mipmaps,kt=D.isVideoTexture!==!0,bn=ze.__version===void 0||ce===!0,le=_e.dataReady,je=k(D,Pe);if(D.isDepthTexture)xt=T(D.format===Ju,D.type),bn&&(kt?t.texStorage2D(n.TEXTURE_2D,1,xt,Pe.width,Pe.height):t.texImage2D(n.TEXTURE_2D,0,xt,Pe.width,Pe.height,0,nt,et,null));else if(D.isDataTexture)if(Rt.length>0){kt&&bn&&t.texStorage2D(n.TEXTURE_2D,je,xt,Rt[0].width,Rt[0].height);for(let Ce=0,Ne=Rt.length;Ce0){const $e=p2(rt.width,rt.height,D.format,D.type);for(const Je of D.layerUpdates){const Nt=rt.data.subarray(Je*$e/rt.data.BYTES_PER_ELEMENT,(Je+1)*$e/rt.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ce,0,0,Je,rt.width,rt.height,1,nt,Nt)}D.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ce,0,0,0,rt.width,rt.height,Pe.depth,nt,rt.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,Ce,xt,rt.width,rt.height,Pe.depth,0,rt.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else kt?le&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,Ce,0,0,0,rt.width,rt.height,Pe.depth,nt,et,rt.data):t.texImage3D(n.TEXTURE_2D_ARRAY,Ce,xt,rt.width,rt.height,Pe.depth,0,nt,et,rt.data)}else{kt&&bn&&t.texStorage2D(n.TEXTURE_2D,je,xt,Rt[0].width,Rt[0].height);for(let Ce=0,Ne=Rt.length;Ce0){const Ce=p2(Pe.width,Pe.height,D.format,D.type);for(const Ne of D.layerUpdates){const $e=Pe.data.subarray(Ne*Ce/Pe.data.BYTES_PER_ELEMENT,(Ne+1)*Ce/Pe.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,Ne,Pe.width,Pe.height,1,nt,et,$e)}D.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,Pe.width,Pe.height,Pe.depth,nt,et,Pe.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,xt,Pe.width,Pe.height,Pe.depth,0,nt,et,Pe.data);else if(D.isData3DTexture)kt?(bn&&t.texStorage3D(n.TEXTURE_3D,je,xt,Pe.width,Pe.height,Pe.depth),le&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,Pe.width,Pe.height,Pe.depth,nt,et,Pe.data)):t.texImage3D(n.TEXTURE_3D,0,xt,Pe.width,Pe.height,Pe.depth,0,nt,et,Pe.data);else if(D.isFramebufferTexture){if(bn)if(kt)t.texStorage2D(n.TEXTURE_2D,je,xt,Pe.width,Pe.height);else{let Ce=Pe.width,Ne=Pe.height;for(let $e=0;$e>=1,Ne>>=1}}else if(Rt.length>0){if(kt&&bn){const Ce=ae(Rt[0]);t.texStorage2D(n.TEXTURE_2D,je,xt,Ce.width,Ce.height)}for(let Ce=0,Ne=Rt.length;Ce0&&je++;const Ne=ae(nt[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,je,Rt,Ne.width,Ne.height)}for(let Ne=0;Ne<6;Ne++)if(Pe){kt?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ne,0,0,0,nt[Ne].width,nt[Ne].height,xt,rt,nt[Ne].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Ne,0,Rt,nt[Ne].width,nt[Ne].height,0,xt,rt,nt[Ne].data);for(let $e=0;$e>_e),et=Math.max(1,D.height>>_e);ce===n.TEXTURE_3D||ce===n.TEXTURE_2D_ARRAY?t.texImage3D(ce,_e,Ge,nt,et,D.depth,0,ze,Oe,null):t.texImage2D(ce,_e,Ge,nt,et,0,ze,Oe,null)}t.bindFramebuffer(n.FRAMEBUFFER,G),X(D)?a.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,he,ce,Pe.__webglTexture,0,te(D)):(ce===n.TEXTURE_2D||ce>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&ce<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,he,ce,Pe.__webglTexture,_e),t.bindFramebuffer(n.FRAMEBUFFER,null)}function Ae(G,D,ee){if(n.bindRenderbuffer(n.RENDERBUFFER,G),D.depthBuffer){const he=D.depthTexture,ce=he&&he.isDepthTexture?he.type:null,_e=T(D.stencilBuffer,ce),ze=D.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Oe=te(D);X(D)?a.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Oe,_e,D.width,D.height):ee?n.renderbufferStorageMultisample(n.RENDERBUFFER,Oe,_e,D.width,D.height):n.renderbufferStorage(n.RENDERBUFFER,_e,D.width,D.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,ze,n.RENDERBUFFER,G)}else{const he=D.textures;for(let ce=0;ce{delete D.__boundDepthTexture,delete D.__depthDisposeCallback,he.removeEventListener("dispose",ce)};he.addEventListener("dispose",ce),D.__depthDisposeCallback=ce}D.__boundDepthTexture=he}if(G.depthTexture&&!D.__autoAllocateDepthBuffer){if(ee)throw new Error("target.depthTexture not supported in Cube render targets");Ee(D.__webglFramebuffer,G)}else if(ee){D.__webglDepthbuffer=[];for(let he=0;he<6;he++)if(t.bindFramebuffer(n.FRAMEBUFFER,D.__webglFramebuffer[he]),D.__webglDepthbuffer[he]===void 0)D.__webglDepthbuffer[he]=n.createRenderbuffer(),Ae(D.__webglDepthbuffer[he],G,!1);else{const ce=G.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,_e=D.__webglDepthbuffer[he];n.bindRenderbuffer(n.RENDERBUFFER,_e),n.framebufferRenderbuffer(n.FRAMEBUFFER,ce,n.RENDERBUFFER,_e)}}else if(t.bindFramebuffer(n.FRAMEBUFFER,D.__webglFramebuffer),D.__webglDepthbuffer===void 0)D.__webglDepthbuffer=n.createRenderbuffer(),Ae(D.__webglDepthbuffer,G,!1);else{const he=G.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ce=D.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ce),n.framebufferRenderbuffer(n.FRAMEBUFFER,he,n.RENDERBUFFER,ce)}t.bindFramebuffer(n.FRAMEBUFFER,null)}function He(G,D,ee){const he=r.get(G);D!==void 0&&be(he.__webglFramebuffer,G,G.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),ee!==void 0&&Le(G)}function qe(G){const D=G.texture,ee=r.get(G),he=r.get(D);G.addEventListener("dispose",M);const ce=G.textures,_e=G.isWebGLCubeRenderTarget===!0,ze=ce.length>1;if(ze||(he.__webglTexture===void 0&&(he.__webglTexture=n.createTexture()),he.__version=D.version,o.memory.textures++),_e){ee.__webglFramebuffer=[];for(let Oe=0;Oe<6;Oe++)if(D.mipmaps&&D.mipmaps.length>0){ee.__webglFramebuffer[Oe]=[];for(let Ge=0;Ge0){ee.__webglFramebuffer=[];for(let Oe=0;Oe0&&X(G)===!1){ee.__webglMultisampledFramebuffer=n.createFramebuffer(),ee.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,ee.__webglMultisampledFramebuffer);for(let Oe=0;Oe0)for(let Ge=0;Ge0)for(let Ge=0;Ge0){if(X(G)===!1){const D=G.textures,ee=G.width,he=G.height;let ce=n.COLOR_BUFFER_BIT;const _e=G.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ze=r.get(G),Oe=D.length>1;if(Oe)for(let Ge=0;Ge0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&D.__useRenderToTexture!==!1}function $(G){const D=o.render.frame;u.get(G)!==D&&(u.set(G,D),G.update())}function ne(G,D){const ee=G.colorSpace,he=G.format,ce=G.type;return G.isCompressedTexture===!0||G.isVideoTexture===!0||ee!==Ql&&ee!==ba&&(dn.getTransfer(ee)===Cn?(he!==ao||ce!==Mi)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",ee)),D}function ae(G){return typeof HTMLImageElement<"u"&&G instanceof HTMLImageElement?(l.width=G.naturalWidth||G.width,l.height=G.naturalHeight||G.height):typeof VideoFrame<"u"&&G instanceof VideoFrame?(l.width=G.displayWidth,l.height=G.displayHeight):(l.width=G.width,l.height=G.height),l}this.allocateTextureUnit=P,this.resetTextureUnits=L,this.setTexture2D=H,this.setTexture2DArray=V,this.setTexture3D=B,this.setTextureCube=z,this.rebindTextures=He,this.setupRenderTarget=qe,this.updateRenderTargetMipmap=it,this.updateMultisampleRenderTarget=ie,this.setupDepthRenderbuffer=Le,this.setupFrameBufferTexture=be,this.useMultisampledRTT=X}function GW(n,e){function t(r,i=ba){let s;const o=dn.getTransfer(i);if(r===Mi)return n.UNSIGNED_BYTE;if(r===zT)return n.UNSIGNED_SHORT_4_4_4_4;if(r===VT)return n.UNSIGNED_SHORT_5_5_5_1;if(r===VO)return n.UNSIGNED_INT_5_9_9_9_REV;if(r===BO)return n.BYTE;if(r===zO)return n.SHORT;if(r===Pp)return n.UNSIGNED_SHORT;if(r===BT)return n.INT;if(r===zl)return n.UNSIGNED_INT;if(r===Aa)return n.FLOAT;if(r===vd)return n.HALF_FLOAT;if(r===HO)return n.ALPHA;if(r===GO)return n.RGB;if(r===ao)return n.RGBA;if(r===WO)return n.LUMINANCE;if(r===jO)return n.LUMINANCE_ALPHA;if(r===Nf)return n.DEPTH_COMPONENT;if(r===Ju)return n.DEPTH_STENCIL;if(r===$O)return n.RED;if(r===HT)return n.RED_INTEGER;if(r===qO)return n.RG;if(r===GT)return n.RG_INTEGER;if(r===Yv)return n.RGBA_INTEGER;if(r===u_||r===h_||r===f_||r===d_)if(o===Cn)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(r===u_)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(r===h_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(r===f_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(r===d_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(r===u_)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(r===h_)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(r===f_)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(r===d_)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(r===mE||r===gE||r===_E||r===vE)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(r===mE)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(r===gE)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(r===_E)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(r===vE)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(r===yE||r===xE||r===SE)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(r===yE||r===xE)return o===Cn?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(r===SE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(r===EE||r===bE||r===TE||r===wE||r===AE||r===ME||r===CE||r===RE||r===kE||r===NE||r===IE||r===OE||r===LE||r===PE)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(r===EE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(r===bE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(r===TE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(r===wE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(r===AE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(r===ME)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(r===CE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(r===RE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(r===kE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(r===NE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(r===IE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(r===OE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(r===LE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(r===PE)return o===Cn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(r===p_||r===DE||r===UE)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(r===p_)return o===Cn?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(r===DE)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(r===UE)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(r===XO||r===FE||r===BE||r===zE)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(r===p_)return s.COMPRESSED_RED_RGTC1_EXT;if(r===FE)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(r===BE)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(r===zE)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return r===Zu?n.UNSIGNED_INT_24_8:n[r]!==void 0?n[r]:null}return{convert:t}}class WW extends Ls{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class mp extends ms{constructor(){super(),this.isGroup=!0,this.type="Group"}}const jW={type:"move"};class t1{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new mp,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new mp,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new xe,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new xe),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new mp,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new xe,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new xe),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const r of e.hand.values())this._getHandJoint(t,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,r){let i=null,s=null,o=null;const a=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){o=!0;for(const v of e.hand.values()){const y=t.getJointPose(v,r),_=this._getHandJoint(l,v);y!==null&&(_.matrix.fromArray(y.transform.matrix),_.matrix.decompose(_.position,_.rotation,_.scale),_.matrixWorldNeedsUpdate=!0,_.jointRadius=y.radius),_.visible=y!==null}const u=l.joints["index-finger-tip"],h=l.joints["thumb-tip"],d=u.position.distanceTo(h.position),m=.02,g=.005;l.inputState.pinching&&d>m+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&d<=m-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,r),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));a!==null&&(i=t.getPose(e.targetRaySpace,r),i===null&&s!==null&&(i=s),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(jW)))}return a!==null&&(a.visible=i!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const r=new mp;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[t.jointName]=r,e.add(r)}return e.joints[t.jointName]}}const $W=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,qW=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`;class XW{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,r){if(this.texture===null){const i=new ur,s=e.properties.get(i);s.__webglTexture=t.texture,(t.depthNear!=r.depthNear||t.depthFar!=r.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,r=new qi({vertexShader:$W,fragmentShader:qW,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Io(new pm(20,20),r)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class KW extends Xc{constructor(e,t){super();const r=this;let i=null,s=1,o=null,a="local-floor",c=1,l=null,u=null,h=null,d=null,m=null,g=null;const v=new XW,y=t.getContextAttributes();let _=null,S=null;const E=[],T=[],k=new Et;let R=null;const M=new Ls;M.viewport=new xr;const O=new Ls;O.viewport=new xr;const C=[M,O],I=new WW;let U=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Q){let re=E[Q];return re===void 0&&(re=new t1,E[Q]=re),re.getTargetRaySpace()},this.getControllerGrip=function(Q){let re=E[Q];return re===void 0&&(re=new t1,E[Q]=re),re.getGripSpace()},this.getHand=function(Q){let re=E[Q];return re===void 0&&(re=new t1,E[Q]=re),re.getHandSpace()};function P(Q){const re=T.indexOf(Q.inputSource);if(re===-1)return;const be=E[re];be!==void 0&&(be.update(Q.inputSource,Q.frame,l||o),be.dispatchEvent({type:Q.type,data:Q.inputSource}))}function w(){i.removeEventListener("select",P),i.removeEventListener("selectstart",P),i.removeEventListener("selectend",P),i.removeEventListener("squeeze",P),i.removeEventListener("squeezestart",P),i.removeEventListener("squeezeend",P),i.removeEventListener("end",w),i.removeEventListener("inputsourceschange",H);for(let Q=0;Q=0&&(T[Ae]=null,E[Ae].disconnect(be))}for(let re=0;re=T.length){T.push(be),Ae=Le;break}else if(T[Le]===null){T[Le]=be,Ae=Le;break}if(Ae===-1)break}const Ee=E[Ae];Ee&&Ee.connect(be)}}const V=new xe,B=new xe;function z(Q,re,be){V.setFromMatrixPosition(re.matrixWorld),B.setFromMatrixPosition(be.matrixWorld);const Ae=V.distanceTo(B),Ee=re.projectionMatrix.elements,Le=be.projectionMatrix.elements,He=Ee[14]/(Ee[10]-1),qe=Ee[14]/(Ee[10]+1),it=(Ee[9]+1)/Ee[5],De=(Ee[9]-1)/Ee[5],A=(Ee[8]-1)/Ee[0],ie=(Le[8]+1)/Le[0],te=He*A,X=He*ie,$=Ae/(-A+ie),ne=$*-A;if(re.matrixWorld.decompose(Q.position,Q.quaternion,Q.scale),Q.translateX(ne),Q.translateZ($),Q.matrixWorld.compose(Q.position,Q.quaternion,Q.scale),Q.matrixWorldInverse.copy(Q.matrixWorld).invert(),Ee[10]===-1)Q.projectionMatrix.copy(re.projectionMatrix),Q.projectionMatrixInverse.copy(re.projectionMatrixInverse);else{const ae=He+$,G=qe+$,D=te-ne,ee=X+(Ae-ne),he=it*qe/G*ae,ce=De*qe/G*ae;Q.projectionMatrix.makePerspective(D,ee,he,ce,ae,G),Q.projectionMatrixInverse.copy(Q.projectionMatrix).invert()}}function W(Q,re){re===null?Q.matrixWorld.copy(Q.matrix):Q.matrixWorld.multiplyMatrices(re.matrixWorld,Q.matrix),Q.matrixWorldInverse.copy(Q.matrixWorld).invert()}this.updateCamera=function(Q){if(i===null)return;let re=Q.near,be=Q.far;v.texture!==null&&(v.depthNear>0&&(re=v.depthNear),v.depthFar>0&&(be=v.depthFar)),I.near=O.near=M.near=re,I.far=O.far=M.far=be,(U!==I.near||L!==I.far)&&(i.updateRenderState({depthNear:I.near,depthFar:I.far}),U=I.near,L=I.far),M.layers.mask=Q.layers.mask|2,O.layers.mask=Q.layers.mask|4,I.layers.mask=M.layers.mask|O.layers.mask;const Ae=Q.parent,Ee=I.cameras;W(I,Ae);for(let Le=0;Le0&&(y.alphaTest.value=_.alphaTest);const S=e.get(_),E=S.envMap,T=S.envMapRotation;E&&(y.envMap.value=E,Eu.copy(T),Eu.x*=-1,Eu.y*=-1,Eu.z*=-1,E.isCubeTexture&&E.isRenderTargetTexture===!1&&(Eu.y*=-1,Eu.z*=-1),y.envMapRotation.value.setFromMatrix4(YW.makeRotationFromEuler(Eu)),y.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,y.reflectivity.value=_.reflectivity,y.ior.value=_.ior,y.refractionRatio.value=_.refractionRatio),_.lightMap&&(y.lightMap.value=_.lightMap,y.lightMapIntensity.value=_.lightMapIntensity,t(_.lightMap,y.lightMapTransform)),_.aoMap&&(y.aoMap.value=_.aoMap,y.aoMapIntensity.value=_.aoMapIntensity,t(_.aoMap,y.aoMapTransform))}function o(y,_){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,_.map&&(y.map.value=_.map,t(_.map,y.mapTransform))}function a(y,_){y.dashSize.value=_.dashSize,y.totalSize.value=_.dashSize+_.gapSize,y.scale.value=_.scale}function c(y,_,S,E){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,y.size.value=_.size*S,y.scale.value=E*.5,_.map&&(y.map.value=_.map,t(_.map,y.uvTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,t(_.alphaMap,y.alphaMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest)}function l(y,_){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,y.rotation.value=_.rotation,_.map&&(y.map.value=_.map,t(_.map,y.mapTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,t(_.alphaMap,y.alphaMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest)}function u(y,_){y.specular.value.copy(_.specular),y.shininess.value=Math.max(_.shininess,1e-4)}function h(y,_){_.gradientMap&&(y.gradientMap.value=_.gradientMap)}function d(y,_){y.metalness.value=_.metalness,_.metalnessMap&&(y.metalnessMap.value=_.metalnessMap,t(_.metalnessMap,y.metalnessMapTransform)),y.roughness.value=_.roughness,_.roughnessMap&&(y.roughnessMap.value=_.roughnessMap,t(_.roughnessMap,y.roughnessMapTransform)),_.envMap&&(y.envMapIntensity.value=_.envMapIntensity)}function m(y,_,S){y.ior.value=_.ior,_.sheen>0&&(y.sheenColor.value.copy(_.sheenColor).multiplyScalar(_.sheen),y.sheenRoughness.value=_.sheenRoughness,_.sheenColorMap&&(y.sheenColorMap.value=_.sheenColorMap,t(_.sheenColorMap,y.sheenColorMapTransform)),_.sheenRoughnessMap&&(y.sheenRoughnessMap.value=_.sheenRoughnessMap,t(_.sheenRoughnessMap,y.sheenRoughnessMapTransform))),_.clearcoat>0&&(y.clearcoat.value=_.clearcoat,y.clearcoatRoughness.value=_.clearcoatRoughness,_.clearcoatMap&&(y.clearcoatMap.value=_.clearcoatMap,t(_.clearcoatMap,y.clearcoatMapTransform)),_.clearcoatRoughnessMap&&(y.clearcoatRoughnessMap.value=_.clearcoatRoughnessMap,t(_.clearcoatRoughnessMap,y.clearcoatRoughnessMapTransform)),_.clearcoatNormalMap&&(y.clearcoatNormalMap.value=_.clearcoatNormalMap,t(_.clearcoatNormalMap,y.clearcoatNormalMapTransform),y.clearcoatNormalScale.value.copy(_.clearcoatNormalScale),_.side===ci&&y.clearcoatNormalScale.value.negate())),_.dispersion>0&&(y.dispersion.value=_.dispersion),_.iridescence>0&&(y.iridescence.value=_.iridescence,y.iridescenceIOR.value=_.iridescenceIOR,y.iridescenceThicknessMinimum.value=_.iridescenceThicknessRange[0],y.iridescenceThicknessMaximum.value=_.iridescenceThicknessRange[1],_.iridescenceMap&&(y.iridescenceMap.value=_.iridescenceMap,t(_.iridescenceMap,y.iridescenceMapTransform)),_.iridescenceThicknessMap&&(y.iridescenceThicknessMap.value=_.iridescenceThicknessMap,t(_.iridescenceThicknessMap,y.iridescenceThicknessMapTransform))),_.transmission>0&&(y.transmission.value=_.transmission,y.transmissionSamplerMap.value=S.texture,y.transmissionSamplerSize.value.set(S.width,S.height),_.transmissionMap&&(y.transmissionMap.value=_.transmissionMap,t(_.transmissionMap,y.transmissionMapTransform)),y.thickness.value=_.thickness,_.thicknessMap&&(y.thicknessMap.value=_.thicknessMap,t(_.thicknessMap,y.thicknessMapTransform)),y.attenuationDistance.value=_.attenuationDistance,y.attenuationColor.value.copy(_.attenuationColor)),_.anisotropy>0&&(y.anisotropyVector.value.set(_.anisotropy*Math.cos(_.anisotropyRotation),_.anisotropy*Math.sin(_.anisotropyRotation)),_.anisotropyMap&&(y.anisotropyMap.value=_.anisotropyMap,t(_.anisotropyMap,y.anisotropyMapTransform))),y.specularIntensity.value=_.specularIntensity,y.specularColor.value.copy(_.specularColor),_.specularColorMap&&(y.specularColorMap.value=_.specularColorMap,t(_.specularColorMap,y.specularColorMapTransform)),_.specularIntensityMap&&(y.specularIntensityMap.value=_.specularIntensityMap,t(_.specularIntensityMap,y.specularIntensityMapTransform))}function g(y,_){_.matcap&&(y.matcap.value=_.matcap)}function v(y,_){const S=e.get(_).light;y.referencePosition.value.setFromMatrixPosition(S.matrixWorld),y.nearDistance.value=S.shadow.camera.near,y.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function JW(n,e,t,r){let i={},s={},o=[];const a=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function c(S,E){const T=E.program;r.uniformBlockBinding(S,T)}function l(S,E){let T=i[S.id];T===void 0&&(g(S),T=u(S),i[S.id]=T,S.addEventListener("dispose",y));const k=E.program;r.updateUBOMapping(S,k);const R=e.render.frame;s[S.id]!==R&&(d(S),s[S.id]=R)}function u(S){const E=h();S.__bindingPointIndex=E;const T=n.createBuffer(),k=S.__size,R=S.usage;return n.bindBuffer(n.UNIFORM_BUFFER,T),n.bufferData(n.UNIFORM_BUFFER,k,R),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,E,T),T}function h(){for(let S=0;S0&&(T+=k-R),S.__size=T,S.__cache={},this}function v(S){const E={boundary:0,storage:0};return typeof S=="number"||typeof S=="boolean"?(E.boundary=4,E.storage=4):S.isVector2?(E.boundary=8,E.storage=8):S.isVector3||S.isColor?(E.boundary=16,E.storage=12):S.isVector4?(E.boundary=16,E.storage=16):S.isMatrix3?(E.boundary=48,E.storage=48):S.isMatrix4?(E.boundary=64,E.storage=64):S.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",S),E}function y(S){const E=S.target;E.removeEventListener("dispose",y);const T=o.indexOf(E.__bindingPointIndex);o.splice(T,1),n.deleteBuffer(i[E.id]),delete i[E.id],delete s[E.id]}function _(){for(const S in i)n.deleteBuffer(i[S]);o=[],i={},s={}}return{bind:c,update:l,dispose:_}}class QW{constructor(e={}){const{canvas:t=V8(),context:r=null,depth:i=!0,stencil:s=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:h=!1,reverseDepthBuffer:d=!1}=e;this.isWebGLRenderer=!0;let m;if(r!==null){if(typeof WebGLRenderingContext<"u"&&r instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");m=r.getContextAttributes().alpha}else m=o;const g=new Uint32Array(4),v=new Int32Array(4);let y=null,_=null;const S=[],E=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=vr,this.toneMapping=Ra,this.toneMappingExposure=1;const T=this;let k=!1,R=0,M=0,O=null,C=-1,I=null;const U=new xr,L=new xr;let P=null;const w=new hn(0);let H=0,V=t.width,B=t.height,z=1,W=null,K=null;const j=new xr(0,0,V,B),Y=new xr(0,0,V,B);let ge=!1;const Q=new sL;let re=!1,be=!1;const Ae=new hr,Ee=new hr,Le=new xe,He=new xr,qe={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let it=!1;function De(){return O===null?z:1}let A=r;function ie(q,fe){return t.getContext(q,fe)}try{const q={alpha:!0,depth:i,stencil:s,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:u,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Xv}`),t.addEventListener("webglcontextlost",Ne,!1),t.addEventListener("webglcontextrestored",$e,!1),t.addEventListener("webglcontextcreationerror",Je,!1),A===null){const fe="webgl2";if(A=ie(fe,q),A===null)throw ie(fe)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(q){throw console.error("THREE.WebGLRenderer: "+q.message),q}let te,X,$,ne,ae,G,D,ee,he,ce,_e,ze,Oe,Ge,Dt,Pe,nt,et,xt,rt,Rt,kt,bn,le;function je(){te=new iG(A),te.init(),kt=new GW(A,te),X=new JH(A,te,e,kt),$=new zW(A,te),X.reverseDepthBuffer&&d&&$.buffers.depth.setReversed(!0),ne=new aG(A),ae=new wW,G=new HW(A,te,$,ae,X,kt,ne),D=new eG(T),ee=new rG(T),he=new p6(A),bn=new YH(A,he),ce=new sG(A,he,ne,bn),_e=new lG(A,ce,he,ne),xt=new cG(A,X,G),Pe=new QH(ae),ze=new TW(T,D,ee,te,X,bn,Pe),Oe=new ZW(T,ae),Ge=new MW,Dt=new OW(te),et=new KH(T,D,ee,$,_e,m,c),nt=new FW(T,_e,X),le=new JW(A,ne,X,$),rt=new ZH(A,te,ne),Rt=new oG(A,te,ne),ne.programs=ze.programs,T.capabilities=X,T.extensions=te,T.properties=ae,T.renderLists=Ge,T.shadowMap=nt,T.state=$,T.info=ne}je();const Ce=new KW(T,A);this.xr=Ce,this.getContext=function(){return A},this.getContextAttributes=function(){return A.getContextAttributes()},this.forceContextLoss=function(){const q=te.get("WEBGL_lose_context");q&&q.loseContext()},this.forceContextRestore=function(){const q=te.get("WEBGL_lose_context");q&&q.restoreContext()},this.getPixelRatio=function(){return z},this.setPixelRatio=function(q){q!==void 0&&(z=q,this.setSize(V,B,!1))},this.getSize=function(q){return q.set(V,B)},this.setSize=function(q,fe,Te=!0){if(Ce.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}V=q,B=fe,t.width=Math.floor(q*z),t.height=Math.floor(fe*z),Te===!0&&(t.style.width=q+"px",t.style.height=fe+"px"),this.setViewport(0,0,q,fe)},this.getDrawingBufferSize=function(q){return q.set(V*z,B*z).floor()},this.setDrawingBufferSize=function(q,fe,Te){V=q,B=fe,z=Te,t.width=Math.floor(q*Te),t.height=Math.floor(fe*Te),this.setViewport(0,0,q,fe)},this.getCurrentViewport=function(q){return q.copy(U)},this.getViewport=function(q){return q.copy(j)},this.setViewport=function(q,fe,Te,we){q.isVector4?j.set(q.x,q.y,q.z,q.w):j.set(q,fe,Te,we),$.viewport(U.copy(j).multiplyScalar(z).round())},this.getScissor=function(q){return q.copy(Y)},this.setScissor=function(q,fe,Te,we){q.isVector4?Y.set(q.x,q.y,q.z,q.w):Y.set(q,fe,Te,we),$.scissor(L.copy(Y).multiplyScalar(z).round())},this.getScissorTest=function(){return ge},this.setScissorTest=function(q){$.setScissorTest(ge=q)},this.setOpaqueSort=function(q){W=q},this.setTransparentSort=function(q){K=q},this.getClearColor=function(q){return q.copy(et.getClearColor())},this.setClearColor=function(){et.setClearColor.apply(et,arguments)},this.getClearAlpha=function(){return et.getClearAlpha()},this.setClearAlpha=function(){et.setClearAlpha.apply(et,arguments)},this.clear=function(q=!0,fe=!0,Te=!0){let we=0;if(q){let me=!1;if(O!==null){const Be=O.texture.format;me=Be===Yv||Be===GT||Be===HT}if(me){const Be=O.texture.type,Ye=Be===Mi||Be===zl||Be===Pp||Be===Zu||Be===zT||Be===VT,lt=et.getClearColor(),ht=et.getClearAlpha(),Mt=lt.r,It=lt.g,ft=lt.b;Ye?(g[0]=Mt,g[1]=It,g[2]=ft,g[3]=ht,A.clearBufferuiv(A.COLOR,0,g)):(v[0]=Mt,v[1]=It,v[2]=ft,v[3]=ht,A.clearBufferiv(A.COLOR,0,v))}else we|=A.COLOR_BUFFER_BIT}fe&&(we|=A.DEPTH_BUFFER_BIT),Te&&(we|=A.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),A.clear(we)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Ne,!1),t.removeEventListener("webglcontextrestored",$e,!1),t.removeEventListener("webglcontextcreationerror",Je,!1),Ge.dispose(),Dt.dispose(),ae.dispose(),D.dispose(),ee.dispose(),_e.dispose(),bn.dispose(),le.dispose(),ze.dispose(),Ce.dispose(),Ce.removeEventListener("sessionstart",sg),Ce.removeEventListener("sessionend",og),ta.stop()};function Ne(q){q.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),k=!0}function $e(){console.log("THREE.WebGLRenderer: Context Restored."),k=!1;const q=ne.autoReset,fe=nt.enabled,Te=nt.autoUpdate,we=nt.needsUpdate,me=nt.type;je(),ne.autoReset=q,nt.enabled=fe,nt.autoUpdate=Te,nt.needsUpdate=we,nt.type=me}function Je(q){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",q.statusMessage)}function Nt(q){const fe=q.target;fe.removeEventListener("dispose",Nt),$n(fe)}function $n(q){Pr(q),ae.remove(q)}function Pr(q){const fe=ae.get(q).programs;fe!==void 0&&(fe.forEach(function(Te){ze.releaseProgram(Te)}),q.isShaderMaterial&&ze.releaseShaderCache(q))}this.renderBufferDirect=function(q,fe,Te,we,me,Be){fe===null&&(fe=qe);const Ye=me.isMesh&&me.matrixWorld.determinant()<0,lt=Sx(q,fe,Te,we,me);$.setMaterial(we,Ye);let ht=Te.index,Mt=1;if(we.wireframe===!0){if(ht=ce.getWireframeAttribute(Te),ht===void 0)return;Mt=2}const It=Te.drawRange,ft=Te.attributes.position;let Ht=It.start*Mt,rn=(It.start+It.count)*Mt;Be!==null&&(Ht=Math.max(Ht,Be.start*Mt),rn=Math.min(rn,(Be.start+Be.count)*Mt)),ht!==null?(Ht=Math.max(Ht,0),rn=Math.min(rn,ht.count)):ft!=null&&(Ht=Math.max(Ht,0),rn=Math.min(rn,ft.count));const bt=rn-Ht;if(bt<0||bt===1/0)return;bn.setup(me,we,lt,Te,ht);let Ut,Gt=rt;if(ht!==null&&(Ut=he.get(ht),Gt=Rt,Gt.setIndex(Ut)),me.isMesh)we.wireframe===!0?($.setLineWidth(we.wireframeLinewidth*De()),Gt.setMode(A.LINES)):Gt.setMode(A.TRIANGLES);else if(me.isLine){let Qe=we.linewidth;Qe===void 0&&(Qe=1),$.setLineWidth(Qe*De()),me.isLineSegments?Gt.setMode(A.LINES):me.isLineLoop?Gt.setMode(A.LINE_LOOP):Gt.setMode(A.LINE_STRIP)}else me.isPoints?Gt.setMode(A.POINTS):me.isSprite&&Gt.setMode(A.TRIANGLES);if(me.isBatchedMesh)if(me._multiDrawInstances!==null)Gt.renderMultiDrawInstances(me._multiDrawStarts,me._multiDrawCounts,me._multiDrawCount,me._multiDrawInstances);else if(te.get("WEBGL_multi_draw"))Gt.renderMultiDraw(me._multiDrawStarts,me._multiDrawCounts,me._multiDrawCount);else{const Qe=me._multiDrawStarts,qn=me._multiDrawCounts,Yt=me._multiDrawCount,Kr=ht?he.get(ht).bytesPerElement:1,dr=ae.get(we).currentProgram.getUniforms();for(let Yr=0;Yr{function Be(){if(we.forEach(function(Ye){ae.get(Ye).currentProgram.isReady()&&we.delete(Ye)}),we.size===0){me(q);return}setTimeout(Be,10)}te.get("KHR_parallel_shader_compile")!==null?Be():setTimeout(Be,10)})};let ts=null;function So(q){ts&&ts(q)}function sg(){ta.stop()}function og(){ta.start()}const ta=new oL;ta.setAnimationLoop(So),typeof self<"u"&&ta.setContext(self),this.setAnimationLoop=function(q){ts=q,Ce.setAnimationLoop(q),q===null?ta.stop():ta.start()},Ce.addEventListener("sessionstart",sg),Ce.addEventListener("sessionend",og),this.render=function(q,fe){if(fe!==void 0&&fe.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(k===!0)return;if(q.matrixWorldAutoUpdate===!0&&q.updateMatrixWorld(),fe.parent===null&&fe.matrixWorldAutoUpdate===!0&&fe.updateMatrixWorld(),Ce.enabled===!0&&Ce.isPresenting===!0&&(Ce.cameraAutoUpdate===!0&&Ce.updateCamera(fe),fe=Ce.getCamera()),q.isScene===!0&&q.onBeforeRender(T,q,fe,O),_=Dt.get(q,E.length),_.init(fe),E.push(_),Ee.multiplyMatrices(fe.projectionMatrix,fe.matrixWorldInverse),Q.setFromProjectionMatrix(Ee),be=this.localClippingEnabled,re=Pe.init(this.clippingPlanes,be),y=Ge.get(q,S.length),y.init(),S.push(y),Ce.enabled===!0&&Ce.isPresenting===!0){const Be=T.xr.getDepthSensingMesh();Be!==null&&au(Be,fe,-1/0,T.sortObjects)}au(q,fe,0,T.sortObjects),y.finish(),T.sortObjects===!0&&y.sort(W,K),it=Ce.enabled===!1||Ce.isPresenting===!1||Ce.hasDepthSensing()===!1,it&&et.addToRenderList(y,q),this.info.render.frame++,re===!0&&Pe.beginShadows();const Te=_.state.shadowsArray;nt.render(Te,q,fe),re===!0&&Pe.endShadows(),this.info.autoReset===!0&&this.info.reset();const we=y.opaque,me=y.transmissive;if(_.setupLights(),fe.isArrayCamera){const Be=fe.cameras;if(me.length>0)for(let Ye=0,lt=Be.length;Ye0&&cl(we,me,q,fe),it&&et.render(q),ag(y,q,fe);O!==null&&(G.updateMultisampleRenderTarget(O),G.updateRenderTargetMipmap(O)),q.isScene===!0&&q.onAfterRender(T,q,fe),bn.resetDefaultState(),C=-1,I=null,E.pop(),E.length>0?(_=E[E.length-1],re===!0&&Pe.setGlobalState(T.clippingPlanes,_.state.camera)):_=null,S.pop(),S.length>0?y=S[S.length-1]:y=null};function au(q,fe,Te,we){if(q.visible===!1)return;if(q.layers.test(fe.layers)){if(q.isGroup)Te=q.renderOrder;else if(q.isLOD)q.autoUpdate===!0&&q.update(fe);else if(q.isLight)_.pushLight(q),q.castShadow&&_.pushShadow(q);else if(q.isSprite){if(!q.frustumCulled||Q.intersectsSprite(q)){we&&He.setFromMatrixPosition(q.matrixWorld).applyMatrix4(Ee);const Ye=_e.update(q),lt=q.material;lt.visible&&y.push(q,Ye,lt,Te,He.z,null)}}else if((q.isMesh||q.isLine||q.isPoints)&&(!q.frustumCulled||Q.intersectsObject(q))){const Ye=_e.update(q),lt=q.material;if(we&&(q.boundingSphere!==void 0?(q.boundingSphere===null&&q.computeBoundingSphere(),He.copy(q.boundingSphere.center)):(Ye.boundingSphere===null&&Ye.computeBoundingSphere(),He.copy(Ye.boundingSphere.center)),He.applyMatrix4(q.matrixWorld).applyMatrix4(Ee)),Array.isArray(lt)){const ht=Ye.groups;for(let Mt=0,It=ht.length;Mt0&&Nh(me,fe,Te),Be.length>0&&Nh(Be,fe,Te),Ye.length>0&&Nh(Ye,fe,Te),$.buffers.depth.setTest(!0),$.buffers.depth.setMask(!0),$.buffers.color.setMask(!0),$.setPolygonOffset(!1)}function cl(q,fe,Te,we){if((Te.isScene===!0?Te.overrideMaterial:null)!==null)return;_.state.transmissionRenderTarget[we.id]===void 0&&(_.state.transmissionRenderTarget[we.id]=new Gs(1,1,{generateMipmaps:!0,type:te.has("EXT_color_buffer_half_float")||te.has("EXT_color_buffer_float")?vd:Mi,minFilter:zu,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:dn.workingColorSpace}));const Be=_.state.transmissionRenderTarget[we.id],Ye=we.viewport||U;Be.setSize(Ye.z,Ye.w);const lt=T.getRenderTarget();T.setRenderTarget(Be),T.getClearColor(w),H=T.getClearAlpha(),H<1&&T.setClearColor(16777215,.5),T.clear(),it&&et.render(Te);const ht=T.toneMapping;T.toneMapping=Ra;const Mt=we.viewport;if(we.viewport!==void 0&&(we.viewport=void 0),_.setupLightsView(we),re===!0&&Pe.setGlobalState(T.clippingPlanes,we),Nh(q,Te,we),G.updateMultisampleRenderTarget(Be),G.updateRenderTargetMipmap(Be),te.has("WEBGL_multisampled_render_to_texture")===!1){let It=!1;for(let ft=0,Ht=fe.length;ft0),ft=!!Te.morphAttributes.position,Ht=!!Te.morphAttributes.normal,rn=!!Te.morphAttributes.color;let bt=Ra;we.toneMapped&&(O===null||O.isXRRenderTarget===!0)&&(bt=T.toneMapping);const Ut=Te.morphAttributes.position||Te.morphAttributes.normal||Te.morphAttributes.color,Gt=Ut!==void 0?Ut.length:0,Qe=ae.get(we),qn=_.state.lights;if(re===!0&&(be===!0||q!==I)){const Xn=q===I&&we.id===C;Pe.setState(we,q,Xn)}let Yt=!1;we.version===Qe.__version?(Qe.needsLights&&Qe.lightsStateVersion!==qn.state.version||Qe.outputColorSpace!==lt||me.isBatchedMesh&&Qe.batching===!1||!me.isBatchedMesh&&Qe.batching===!0||me.isBatchedMesh&&Qe.batchingColor===!0&&me.colorTexture===null||me.isBatchedMesh&&Qe.batchingColor===!1&&me.colorTexture!==null||me.isInstancedMesh&&Qe.instancing===!1||!me.isInstancedMesh&&Qe.instancing===!0||me.isSkinnedMesh&&Qe.skinning===!1||!me.isSkinnedMesh&&Qe.skinning===!0||me.isInstancedMesh&&Qe.instancingColor===!0&&me.instanceColor===null||me.isInstancedMesh&&Qe.instancingColor===!1&&me.instanceColor!==null||me.isInstancedMesh&&Qe.instancingMorph===!0&&me.morphTexture===null||me.isInstancedMesh&&Qe.instancingMorph===!1&&me.morphTexture!==null||Qe.envMap!==ht||we.fog===!0&&Qe.fog!==Be||Qe.numClippingPlanes!==void 0&&(Qe.numClippingPlanes!==Pe.numPlanes||Qe.numIntersection!==Pe.numIntersection)||Qe.vertexAlphas!==Mt||Qe.vertexTangents!==It||Qe.morphTargets!==ft||Qe.morphNormals!==Ht||Qe.morphColors!==rn||Qe.toneMapping!==bt||Qe.morphTargetsCount!==Gt)&&(Yt=!0):(Yt=!0,Qe.__version=we.version);let Kr=Qe.currentProgram;Yt===!0&&(Kr=Ih(we,fe,me));let dr=!1,Yr=!1,ll=!1;const Mn=Kr.getUniforms(),Ni=Qe.uniforms;if($.useProgram(Kr.program)&&(dr=!0,Yr=!0,ll=!0),we.id!==C&&(C=we.id,Yr=!0),dr||I!==q){$.buffers.depth.getReversed()?(Ae.copy(q.projectionMatrix),G8(Ae),W8(Ae),Mn.setValue(A,"projectionMatrix",Ae)):Mn.setValue(A,"projectionMatrix",q.projectionMatrix),Mn.setValue(A,"viewMatrix",q.matrixWorldInverse);const na=Mn.map.cameraPosition;na!==void 0&&na.setValue(A,Le.setFromMatrixPosition(q.matrixWorld)),X.logarithmicDepthBuffer&&Mn.setValue(A,"logDepthBufFC",2/(Math.log(q.far+1)/Math.LN2)),(we.isMeshPhongMaterial||we.isMeshToonMaterial||we.isMeshLambertMaterial||we.isMeshBasicMaterial||we.isMeshStandardMaterial||we.isShaderMaterial)&&Mn.setValue(A,"isOrthographic",q.isOrthographicCamera===!0),I!==q&&(I=q,Yr=!0,ll=!0)}if(me.isSkinnedMesh){Mn.setOptional(A,me,"bindMatrix"),Mn.setOptional(A,me,"bindMatrixInverse");const Xn=me.skeleton;Xn&&(Xn.boneTexture===null&&Xn.computeBoneTexture(),Mn.setValue(A,"boneTexture",Xn.boneTexture,G))}me.isBatchedMesh&&(Mn.setOptional(A,me,"batchingTexture"),Mn.setValue(A,"batchingTexture",me._matricesTexture,G),Mn.setOptional(A,me,"batchingIdTexture"),Mn.setValue(A,"batchingIdTexture",me._indirectTexture,G),Mn.setOptional(A,me,"batchingColorTexture"),me._colorsTexture!==null&&Mn.setValue(A,"batchingColorTexture",me._colorsTexture,G));const ul=Te.morphAttributes;if((ul.position!==void 0||ul.normal!==void 0||ul.color!==void 0)&&xt.update(me,Te,Kr),(Yr||Qe.receiveShadow!==me.receiveShadow)&&(Qe.receiveShadow=me.receiveShadow,Mn.setValue(A,"receiveShadow",me.receiveShadow)),we.isMeshGouraudMaterial&&we.envMap!==null&&(Ni.envMap.value=ht,Ni.flipEnvMap.value=ht.isCubeTexture&&ht.isRenderTargetTexture===!1?-1:1),we.isMeshStandardMaterial&&we.envMap===null&&fe.environment!==null&&(Ni.envMapIntensity.value=fe.environmentIntensity),Yr&&(Mn.setValue(A,"toneMappingExposure",T.toneMappingExposure),Qe.needsLights&&Ex(Ni,ll),Be&&we.fog===!0&&Oe.refreshFogUniforms(Ni,Be),Oe.refreshMaterialUniforms(Ni,we,z,B,_.state.transmissionRenderTarget[q.id]),m_.upload(A,lg(Qe),Ni,G)),we.isShaderMaterial&&we.uniformsNeedUpdate===!0&&(m_.upload(A,lg(Qe),Ni,G),we.uniformsNeedUpdate=!1),we.isSpriteMaterial&&Mn.setValue(A,"center",me.center),Mn.setValue(A,"modelViewMatrix",me.modelViewMatrix),Mn.setValue(A,"normalMatrix",me.normalMatrix),Mn.setValue(A,"modelMatrix",me.matrixWorld),we.isShaderMaterial||we.isRawShaderMaterial){const Xn=we.uniformsGroups;for(let na=0,ra=Xn.length;na0&&G.useMultisampledRTT(q)===!1?me=ae.get(q).__webglMultisampledFramebuffer:Array.isArray(It)?me=It[Te]:me=It,U.copy(q.viewport),L.copy(q.scissor),P=q.scissorTest}else U.copy(j).multiplyScalar(z).floor(),L.copy(Y).multiplyScalar(z).floor(),P=ge;if($.bindFramebuffer(A.FRAMEBUFFER,me)&&we&&$.drawBuffers(q,me),$.viewport(U),$.scissor(L),$.setScissorTest(P),Be){const ht=ae.get(q.texture);A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+fe,ht.__webglTexture,Te)}else if(Ye){const ht=ae.get(q.texture),Mt=fe||0;A.framebufferTextureLayer(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,ht.__webglTexture,Te||0,Mt)}C=-1},this.readRenderTargetPixels=function(q,fe,Te,we,me,Be,Ye){if(!(q&&q.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let lt=ae.get(q).__webglFramebuffer;if(q.isWebGLCubeRenderTarget&&Ye!==void 0&&(lt=lt[Ye]),lt){$.bindFramebuffer(A.FRAMEBUFFER,lt);try{const ht=q.texture,Mt=ht.format,It=ht.type;if(!X.textureFormatReadable(Mt)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!X.textureTypeReadable(It)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}fe>=0&&fe<=q.width-we&&Te>=0&&Te<=q.height-me&&A.readPixels(fe,Te,we,me,kt.convert(Mt),kt.convert(It),Be)}finally{const ht=O!==null?ae.get(O).__webglFramebuffer:null;$.bindFramebuffer(A.FRAMEBUFFER,ht)}}},this.readRenderTargetPixelsAsync=async function(q,fe,Te,we,me,Be,Ye){if(!(q&&q.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let lt=ae.get(q).__webglFramebuffer;if(q.isWebGLCubeRenderTarget&&Ye!==void 0&&(lt=lt[Ye]),lt){const ht=q.texture,Mt=ht.format,It=ht.type;if(!X.textureFormatReadable(Mt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!X.textureTypeReadable(It))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(fe>=0&&fe<=q.width-we&&Te>=0&&Te<=q.height-me){$.bindFramebuffer(A.FRAMEBUFFER,lt);const ft=A.createBuffer();A.bindBuffer(A.PIXEL_PACK_BUFFER,ft),A.bufferData(A.PIXEL_PACK_BUFFER,Be.byteLength,A.STREAM_READ),A.readPixels(fe,Te,we,me,kt.convert(Mt),kt.convert(It),0);const Ht=O!==null?ae.get(O).__webglFramebuffer:null;$.bindFramebuffer(A.FRAMEBUFFER,Ht);const rn=A.fenceSync(A.SYNC_GPU_COMMANDS_COMPLETE,0);return A.flush(),await H8(A,rn,4),A.bindBuffer(A.PIXEL_PACK_BUFFER,ft),A.getBufferSubData(A.PIXEL_PACK_BUFFER,0,Be),A.deleteBuffer(ft),A.deleteSync(rn),Be}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(q,fe=null,Te=0){q.isTexture!==!0&&(dp("WebGLRenderer: copyFramebufferToTexture function signature has changed."),fe=arguments[0]||null,q=arguments[1]);const we=Math.pow(2,-Te),me=Math.floor(q.image.width*we),Be=Math.floor(q.image.height*we),Ye=fe!==null?fe.x:0,lt=fe!==null?fe.y:0;G.setTexture2D(q,0),A.copyTexSubImage2D(A.TEXTURE_2D,Te,0,0,Ye,lt,me,Be),$.unbindTexture()},this.copyTextureToTexture=function(q,fe,Te=null,we=null,me=0){q.isTexture!==!0&&(dp("WebGLRenderer: copyTextureToTexture function signature has changed."),we=arguments[0]||null,q=arguments[1],fe=arguments[2],me=arguments[3]||0,Te=null);let Be,Ye,lt,ht,Mt,It,ft,Ht,rn;const bt=q.isCompressedTexture?q.mipmaps[me]:q.image;Te!==null?(Be=Te.max.x-Te.min.x,Ye=Te.max.y-Te.min.y,lt=Te.isBox3?Te.max.z-Te.min.z:1,ht=Te.min.x,Mt=Te.min.y,It=Te.isBox3?Te.min.z:0):(Be=bt.width,Ye=bt.height,lt=bt.depth||1,ht=0,Mt=0,It=0),we!==null?(ft=we.x,Ht=we.y,rn=we.z):(ft=0,Ht=0,rn=0);const Ut=kt.convert(fe.format),Gt=kt.convert(fe.type);let Qe;fe.isData3DTexture?(G.setTexture3D(fe,0),Qe=A.TEXTURE_3D):fe.isDataArrayTexture||fe.isCompressedArrayTexture?(G.setTexture2DArray(fe,0),Qe=A.TEXTURE_2D_ARRAY):(G.setTexture2D(fe,0),Qe=A.TEXTURE_2D),A.pixelStorei(A.UNPACK_FLIP_Y_WEBGL,fe.flipY),A.pixelStorei(A.UNPACK_PREMULTIPLY_ALPHA_WEBGL,fe.premultiplyAlpha),A.pixelStorei(A.UNPACK_ALIGNMENT,fe.unpackAlignment);const qn=A.getParameter(A.UNPACK_ROW_LENGTH),Yt=A.getParameter(A.UNPACK_IMAGE_HEIGHT),Kr=A.getParameter(A.UNPACK_SKIP_PIXELS),dr=A.getParameter(A.UNPACK_SKIP_ROWS),Yr=A.getParameter(A.UNPACK_SKIP_IMAGES);A.pixelStorei(A.UNPACK_ROW_LENGTH,bt.width),A.pixelStorei(A.UNPACK_IMAGE_HEIGHT,bt.height),A.pixelStorei(A.UNPACK_SKIP_PIXELS,ht),A.pixelStorei(A.UNPACK_SKIP_ROWS,Mt),A.pixelStorei(A.UNPACK_SKIP_IMAGES,It);const ll=q.isDataArrayTexture||q.isData3DTexture,Mn=fe.isDataArrayTexture||fe.isData3DTexture;if(q.isRenderTargetTexture||q.isDepthTexture){const Ni=ae.get(q),ul=ae.get(fe),Xn=ae.get(Ni.__renderTarget),na=ae.get(ul.__renderTarget);$.bindFramebuffer(A.READ_FRAMEBUFFER,Xn.__webglFramebuffer),$.bindFramebuffer(A.DRAW_FRAMEBUFFER,na.__webglFramebuffer);for(let ra=0;ra0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class hL extends ur{constructor(e=null,t=1,r=1,i,s,o,a,c,l=Er,u=Er,h,d){super(null,o,a,c,l,u,i,s,h,d),this.isDataTexture=!0,this.image={data:e,width:t,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class ej extends Kc{static get type(){return"PointsMaterial"}constructor(e){super(),this.isPointsMaterial=!0,this.color=new hn(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const m2=new hr,HE=new jT,M0=new Jv,C0=new xe;class tj extends ms{constructor(e=new jo,t=new ej){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const r=this.geometry,i=this.matrixWorld,s=e.params.Points.threshold,o=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),M0.copy(r.boundingSphere),M0.applyMatrix4(i),M0.radius+=s,e.ray.intersectsSphere(M0)===!1)return;m2.copy(i).invert(),HE.copy(e.ray).applyMatrix4(m2);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=r.index,h=r.attributes.position;if(l!==null){const d=Math.max(0,o.start),m=Math.min(l.count,o.start+o.count);for(let g=d,v=m;g0){const i=t[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;si.far)return;s.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}class nj extends ur{constructor(e,t,r,i,s,o,a,c,l){super(e,t,r,i,s,o,a,c,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class rj extends Kc{static get type(){return"MeshNormalMaterial"}constructor(e){super(),this.isMeshNormalMaterial=!0,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=KO,this.normalScale=new Et(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}const _2={enabled:!1,files:{},add:function(n,e){this.enabled!==!1&&(this.files[n]=e)},get:function(n){if(this.enabled!==!1)return this.files[n]},remove:function(n){delete this.files[n]},clear:function(){this.files={}}};class ij{constructor(e,t,r){const i=this;let s=!1,o=0,a=0,c;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=r,this.itemStart=function(u){a++,s===!1&&i.onStart!==void 0&&i.onStart(u,o,a),s=!0},this.itemEnd=function(u){o++,i.onProgress!==void 0&&i.onProgress(u,o,a),o===a&&(s=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(u){i.onError!==void 0&&i.onError(u)},this.resolveURL=function(u){return c?c(u):u},this.setURLModifier=function(u){return c=u,this},this.addHandler=function(u,h){return l.push(u,h),this},this.removeHandler=function(u){const h=l.indexOf(u);return h!==-1&&l.splice(h,2),this},this.getHandler=function(u){for(let h=0,d=l.length;h=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,S2).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Xv}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Xv);var fL={exports:{}},ph={};/** + * @license React + * react-reconciler-constants.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ph.ConcurrentRoot=1;ph.ContinuousEventPriority=4;ph.DefaultEventPriority=16;ph.DiscreteEventPriority=1;ph.IdleEventPriority=536870912;ph.LegacyRoot=0;fL.exports=ph;var Ef=fL.exports;function uj(n){let e;const t=new Set,r=(l,u)=>{const h=typeof l=="function"?l(e):l;if(h!==e){const d=e;e=u?h:Object.assign({},e,h),t.forEach(m=>m(e,d))}},i=()=>e,s=(l,u=i,h=Object.is)=>{console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware");let d=u(e);function m(){const g=u(e);if(!h(d,g)){const v=d;l(d=g,v)}}return t.add(m),()=>t.delete(m)},c={setState:r,getState:i,subscribe:(l,u,h)=>u||h?s(l,u,h):(t.add(l),()=>t.delete(l)),destroy:()=>t.clear()};return e=n(r,i,c),c}const hj=typeof window>"u"||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent),E2=hj?ke.useEffect:ke.useLayoutEffect;function fj(n){const e=typeof n=="function"?uj(n):n,t=(r=e.getState,i=Object.is)=>{const[,s]=ke.useReducer(y=>y+1,0),o=e.getState(),a=ke.useRef(o),c=ke.useRef(r),l=ke.useRef(i),u=ke.useRef(!1),h=ke.useRef();h.current===void 0&&(h.current=r(o));let d,m=!1;(a.current!==o||c.current!==r||l.current!==i||u.current)&&(d=r(o),m=!i(h.current,d)),E2(()=>{m&&(h.current=d),a.current=o,c.current=r,l.current=i,u.current=!1});const g=ke.useRef(o);E2(()=>{const y=()=>{try{const S=e.getState(),E=c.current(S);l.current(h.current,E)||(a.current=S,h.current=E,s())}catch{u.current=!0,s()}},_=e.subscribe(y);return e.getState()!==g.current&&y(),_},[]);const v=m?d:h.current;return ke.useDebugValue(v),v};return Object.assign(t,e),t[Symbol.iterator]=function(){console.warn("[useStore, api] = create() is deprecated and will be removed in v4");const r=[t,e];return{next(){const i=r.length<=0;return{value:r.shift(),done:i}}}},t}const dj=n=>typeof n=="object"&&typeof n.then=="function",Vu=[];function dL(n,e,t=(r,i)=>r===i){if(n===e)return!0;if(!n||!e)return!1;const r=n.length;if(e.length!==r)return!1;for(let i=0;i0&&(s.timeout&&clearTimeout(s.timeout),s.timeout=setTimeout(s.remove,r.lifespan)),s.response;if(!t)throw s.promise}const i={keys:e,equal:r.equal,remove:()=>{const s=Vu.indexOf(i);s!==-1&&Vu.splice(s,1)},promise:(dj(n)?n:n(...e)).then(s=>{i.response=s,r.lifespan&&r.lifespan>0&&(i.timeout=setTimeout(i.remove,r.lifespan))}).catch(s=>i.error=s)};if(Vu.push(i),!t)throw i.promise}const pj=(n,e,t)=>pL(n,e,!1,t),mj=(n,e,t)=>void pL(n,e,!0,t),gj=n=>{if(n===void 0||n.length===0)Vu.splice(0,Vu.length);else{const e=Vu.find(t=>dL(n,t.keys,t.equal));e&&e.remove()}};var mL={exports:{}},gL={exports:{}},_L={};/** + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(n){function e(z,W){var K=z.length;z.push(W);e:for(;0>>1,Y=z[j];if(0>>1;ji(re,K))bei(Ae,re)?(z[j]=Ae,z[be]=K,j=be):(z[j]=re,z[Q]=K,j=Q);else if(bei(Ae,K))z[j]=Ae,z[be]=K,j=be;else break e}}return W}function i(z,W){var K=z.sortIndex-W.sortIndex;return K!==0?K:z.id-W.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;n.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();n.unstable_now=function(){return o.now()-a}}var c=[],l=[],u=1,h=null,d=3,m=!1,g=!1,v=!1,y=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(z){for(var W=t(l);W!==null;){if(W.callback===null)r(l);else if(W.startTime<=z)r(l),W.sortIndex=W.expirationTime,e(c,W);else break;W=t(l)}}function T(z){if(v=!1,E(z),!g)if(t(c)!==null)g=!0,V(k);else{var W=t(l);W!==null&&B(T,W.startTime-z)}}function k(z,W){g=!1,v&&(v=!1,_(O),O=-1),m=!0;var K=d;try{for(E(W),h=t(c);h!==null&&(!(h.expirationTime>W)||z&&!U());){var j=h.callback;if(typeof j=="function"){h.callback=null,d=h.priorityLevel;var Y=j(h.expirationTime<=W);W=n.unstable_now(),typeof Y=="function"?h.callback=Y:h===t(c)&&r(c),E(W)}else r(c);h=t(c)}if(h!==null)var ge=!0;else{var Q=t(l);Q!==null&&B(T,Q.startTime-W),ge=!1}return ge}finally{h=null,d=K,m=!1}}var R=!1,M=null,O=-1,C=5,I=-1;function U(){return!(n.unstable_now()-Iz||125j?(z.sortIndex=K,e(l,z),t(c)===null&&z===t(l)&&(v?(_(O),O=-1):v=!0,B(T,K-j))):(z.sortIndex=Y,e(c,z),g||m||(g=!0,V(k))),z},n.unstable_shouldYield=U,n.unstable_wrapCallback=function(z){var W=d;return function(){var K=d;d=W;try{return z.apply(this,arguments)}finally{d=K}}}})(_L);gL.exports=_L;var WE=gL.exports;/** + * @license React + * react-reconciler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var _j=function(e){var t={},r=ke,i=WE,s=Object.assign;function o(f){for(var p="https://reactjs.org/docs/error-decoder.html?invariant="+f,x=1;xoe||N[J]!==F[oe]){var Re=` +`+N[J].replace(" at new "," at ");return f.displayName&&Re.includes("")&&(Re=Re.replace("",f.displayName)),Re}while(1<=J&&0<=oe);break}}}finally{ht=!1,Error.prepareStackTrace=x}return(f=f?f.displayName||f.name:"")?lt(f):""}var It=Object.prototype.hasOwnProperty,ft=[],Ht=-1;function rn(f){return{current:f}}function bt(f){0>Ht||(f.current=ft[Ht],ft[Ht]=null,Ht--)}function Ut(f,p){Ht++,ft[Ht]=f.current,f.current=p}var Gt={},Qe=rn(Gt),qn=rn(!1),Yt=Gt;function Kr(f,p){var x=f.type.contextTypes;if(!x)return Gt;var b=f.stateNode;if(b&&b.__reactInternalMemoizedUnmaskedChildContext===p)return b.__reactInternalMemoizedMaskedChildContext;var N={},F;for(F in x)N[F]=p[F];return b&&(f=f.stateNode,f.__reactInternalMemoizedUnmaskedChildContext=p,f.__reactInternalMemoizedMaskedChildContext=N),N}function dr(f){return f=f.childContextTypes,f!=null}function Yr(){bt(qn),bt(Qe)}function ll(f,p,x){if(Qe.current!==Gt)throw Error(o(168));Ut(Qe,p),Ut(qn,x)}function Mn(f,p,x){var b=f.stateNode;if(p=p.childContextTypes,typeof b.getChildContext!="function")return x;b=b.getChildContext();for(var N in b)if(!(N in p))throw Error(o(108,O(f)||"Unknown",N));return s({},x,b)}function Ni(f){return f=(f=f.stateNode)&&f.__reactInternalMemoizedMergedChildContext||Gt,Yt=Qe.current,Ut(Qe,f),Ut(qn,qn.current),!0}function ul(f,p,x){var b=f.stateNode;if(!b)throw Error(o(169));x?(f=Mn(f,p,Yt),b.__reactInternalMemoizedMergedChildContext=f,bt(qn),bt(Qe),Ut(Qe,f)):bt(qn),Ut(qn,x)}var Xn=Math.clz32?Math.clz32:fg,na=Math.log,ra=Math.LN2;function fg(f){return f>>>=0,f===0?32:31-(na(f)/ra|0)|0}var dg=64,pg=4194304;function Nd(f){switch(f&-f){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 f&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return f&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return f}}function mg(f,p){var x=f.pendingLanes;if(x===0)return 0;var b=0,N=f.suspendedLanes,F=f.pingedLanes,J=x&268435455;if(J!==0){var oe=J&~N;oe!==0?b=Nd(oe):(F&=J,F!==0&&(b=Nd(F)))}else J=x&~N,J!==0?b=Nd(J):F!==0&&(b=Nd(F));if(b===0)return 0;if(p!==0&&p!==b&&!(p&N)&&(N=b&-b,F=p&-p,N>=F||N===16&&(F&4194240)!==0))return p;if(b&4&&(b|=x&16),p=f.entangledLanes,p!==0)for(f=f.entanglements,p&=b;0x;x++)p.push(f);return p}function Id(f,p,x){f.pendingLanes|=p,p!==536870912&&(f.suspendedLanes=0,f.pingedLanes=0),f=f.eventTimes,p=31-Xn(p),f[p]=x}function A5(f,p){var x=f.pendingLanes&~p;f.pendingLanes=p,f.suspendedLanes=0,f.pingedLanes=0,f.expiredLanes&=p,f.mutableReadLanes&=p,f.entangledLanes&=p,p=f.entanglements;var b=f.eventTimes;for(f=f.expirationTimes;0>=J,N-=J,oc=1<<32-Xn(p)+N|x<gn?(Qr=Lt,Lt=null):Qr=Lt.sibling;var _n=St(Se,Lt,Me[gn],tt);if(_n===null){Lt===null&&(Lt=Qr);break}f&&Lt&&_n.alternate===null&&p(Se,Lt),de=F(_n,de,gn),zt===null?mt=_n:zt.sibling=_n,zt=_n,Lt=Qr}if(gn===Me.length)return x(Se,Lt),Kn&&lu(Se,gn),mt;if(Lt===null){for(;gngn?(Qr=Lt,Lt=null):Qr=Lt.sibling;var vl=St(Se,Lt,_n.value,tt);if(vl===null){Lt===null&&(Lt=Qr);break}f&&Lt&&vl.alternate===null&&p(Se,Lt),de=F(vl,de,gn),zt===null?mt=vl:zt.sibling=vl,zt=vl,Lt=Qr}if(_n.done)return x(Se,Lt),Kn&&lu(Se,gn),mt;if(Lt===null){for(;!_n.done;gn++,_n=Me.next())_n=Ot(Se,_n.value,tt),_n!==null&&(de=F(_n,de,gn),zt===null?mt=_n:zt.sibling=_n,zt=_n);return Kn&&lu(Se,gn),mt}for(Lt=b(Se,Lt);!_n.done;gn++,_n=Me.next())_n=On(Lt,Se,gn,_n.value,tt),_n!==null&&(f&&_n.alternate!==null&&Lt.delete(_n.key===null?gn:_n.key),de=F(_n,de,gn),zt===null?mt=_n:zt.sibling=_n,zt=_n);return f&&Lt.forEach(function(hz){return p(Se,hz)}),Kn&&lu(Se,gn),mt}function Js(Se,de,Me,tt){if(typeof Me=="object"&&Me!==null&&Me.type===u&&Me.key===null&&(Me=Me.props.children),typeof Me=="object"&&Me!==null){switch(Me.$$typeof){case c:e:{for(var mt=Me.key,zt=de;zt!==null;){if(zt.key===mt){if(mt=Me.type,mt===u){if(zt.tag===7){x(Se,zt.sibling),de=N(zt,Me.props.children),de.return=Se,Se=de;break e}}else if(zt.elementType===mt||typeof mt=="object"&&mt!==null&&mt.$$typeof===E&&ZM(mt)===zt.type){x(Se,zt.sibling),de=N(zt,Me.props),de.ref=Pd(Se,zt,Me),de.return=Se,Se=de;break e}x(Se,zt);break}else p(Se,zt);zt=zt.sibling}Me.type===u?(de=gu(Me.props.children,Se.mode,tt,Me.key),de.return=Se,Se=de):(tt=r0(Me.type,Me.key,Me.props,null,Se.mode,tt),tt.ref=Pd(Se,de,Me),tt.return=Se,Se=tt)}return J(Se);case l:e:{for(zt=Me.key;de!==null;){if(de.key===zt)if(de.tag===4&&de.stateNode.containerInfo===Me.containerInfo&&de.stateNode.implementation===Me.implementation){x(Se,de.sibling),de=N(de,Me.children||[]),de.return=Se,Se=de;break e}else{x(Se,de);break}else p(Se,de);de=de.sibling}de=wS(Me,Se.mode,tt),de.return=Se,Se=de}return J(Se);case E:return zt=Me._init,Js(Se,de,zt(Me._payload),tt)}if(H(Me))return _t(Se,de,Me,tt);if(R(Me))return xi(Se,de,Me,tt);Ag(Se,Me)}return typeof Me=="string"&&Me!==""||typeof Me=="number"?(Me=""+Me,de!==null&&de.tag===6?(x(Se,de.sibling),de=N(de,Me),de.return=Se,Se=de):(x(Se,de),de=TS(Me,Se.mode,tt),de.return=Se,Se=de),J(Se)):x(Se,de)}return Js}var Fh=JM(!0),QM=JM(!1),Dd={},Xs=rn(Dd),Ud=rn(Dd),Bh=rn(Dd);function ca(f){if(f===Dd)throw Error(o(174));return f}function Hx(f,p){Ut(Bh,p),Ut(Ud,f),Ut(Xs,Dd),f=B(p),bt(Xs),Ut(Xs,f)}function zh(){bt(Xs),bt(Ud),bt(Bh)}function eC(f){var p=ca(Bh.current),x=ca(Xs.current);p=z(x,f.type,p),x!==p&&(Ut(Ud,f),Ut(Xs,p))}function Gx(f){Ud.current===f&&(bt(Xs),bt(Ud))}var Zn=rn(0);function Mg(f){for(var p=f;p!==null;){if(p.tag===13){var x=p.memoizedState;if(x!==null&&(x=x.dehydrated,x===null||ta(x)||au(x)))return p}else if(p.tag===19&&p.memoizedProps.revealOrder!==void 0){if(p.flags&128)return p}else if(p.child!==null){p.child.return=p,p=p.child;continue}if(p===f)break;for(;p.sibling===null;){if(p.return===null||p.return===f)return null;p=p.return}p.sibling.return=p.return,p=p.sibling}return null}var Wx=[];function jx(){for(var f=0;fx?x:4,f(!0);var b=Ks.transition;Ks.transition={};try{f(!1),p()}finally{mn=x,Ks.transition=b}}function pC(){return la().memoizedState}function F5(f,p,x){var b=ml(f);x={lane:b,action:x,hasEagerState:!1,eagerState:null,next:null},mC(f)?gC(p,x):(_C(f,p,x),x=Oi(),f=Ys(f,b,x),f!==null&&vC(f,p,b))}function B5(f,p,x){var b=ml(f),N={lane:b,action:x,hasEagerState:!1,eagerState:null,next:null};if(mC(f))gC(p,N);else{_C(f,p,N);var F=f.alternate;if(f.lanes===0&&(F===null||F.lanes===0)&&(F=p.lastRenderedReducer,F!==null))try{var J=p.lastRenderedState,oe=F(J,x);if(N.hasEagerState=!0,N.eagerState=oe,sa(oe,J))return}catch{}finally{}x=Oi(),f=Ys(f,b,x),f!==null&&vC(f,p,b)}}function mC(f){var p=f.alternate;return f===nr||p!==null&&p===nr}function gC(f,p){Fd=Rg=!0;var x=f.pending;x===null?p.next=p:(p.next=x.next,x.next=p),f.pending=p}function _C(f,p,x){Tr!==null&&f.mode&1&&!(Wt&2)?(f=p.interleaved,f===null?(x.next=x,aa===null?aa=[p]:aa.push(p)):(x.next=f.next,f.next=x),p.interleaved=x):(f=p.pending,f===null?x.next=x:(x.next=f.next,f.next=x),p.pending=x)}function vC(f,p,x){if(x&4194240){var b=p.lanes;b&=f.pendingLanes,x|=b,p.lanes=x,wx(f,x)}}var Lg={readContext:js,useCallback:vi,useContext:vi,useEffect:vi,useImperativeHandle:vi,useInsertionEffect:vi,useLayoutEffect:vi,useMemo:vi,useReducer:vi,useRef:vi,useState:vi,useDebugValue:vi,useDeferredValue:vi,useTransition:vi,useMutableSource:vi,useSyncExternalStore:vi,useId:vi,unstable_isNewReconciler:!1},z5={readContext:js,useCallback:function(f,p){return cc().memoizedState=[f,p===void 0?null:p],f},useContext:js,useEffect:Yx,useImperativeHandle:function(f,p,x){return x=x!=null?x.concat([f]):null,Ig(4194308,4,uC.bind(null,p,f),x)},useLayoutEffect:function(f,p){return Ig(4194308,4,f,p)},useInsertionEffect:function(f,p){return Ig(4,2,f,p)},useMemo:function(f,p){var x=cc();return p=p===void 0?null:p,f=f(),x.memoizedState=[f,p],f},useReducer:function(f,p,x){var b=cc();return p=x!==void 0?x(p):p,b.memoizedState=b.baseState=p,f={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:f,lastRenderedState:p},b.queue=f,f=f.dispatch=F5.bind(null,nr,f),[b.memoizedState,f]},useRef:function(f){var p=cc();return f={current:f},p.memoizedState=f},useState:Kx,useDebugValue:Zx,useDeferredValue:function(f){var p=Kx(f),x=p[0],b=p[1];return Yx(function(){var N=Ks.transition;Ks.transition={};try{b(f)}finally{Ks.transition=N}},[f]),x},useTransition:function(){var f=Kx(!1),p=f[0];return f=U5.bind(null,f[1]),cc().memoizedState=f,[p,f]},useMutableSource:function(){},useSyncExternalStore:function(f,p,x){var b=nr,N=cc();if(Kn){if(x===void 0)throw Error(o(407));x=x()}else{if(x=p(),Tr===null)throw Error(o(349));Vh&30||rC(b,p,x)}N.memoizedState=x;var F={value:x,getSnapshot:p};return N.queue=F,Yx(sC.bind(null,b,F,f),[f]),b.flags|=2048,zd(9,iC.bind(null,b,F,x,p),void 0,null),x},useId:function(){var f=cc(),p=Tr.identifierPrefix;if(Kn){var x=ac,b=oc;x=(b&~(1<<32-Xn(b)-1)).toString(32)+x,p=":"+p+"R"+x,x=Bd++,0gS&&(p.flags|=128,b=!0,Wd(N,!1),p.lanes=4194304)}else{if(!b)if(f=Mg(F),f!==null){if(p.flags|=128,b=!0,f=f.updateQueue,f!==null&&(p.updateQueue=f,p.flags|=4),Wd(N,!0),N.tail===null&&N.tailMode==="hidden"&&!F.alternate&&!Kn)return yi(p),null}else 2*Zr()-N.renderingStartTime>gS&&x!==1073741824&&(p.flags|=128,b=!0,Wd(N,!1),p.lanes=4194304);N.isBackwards?(F.sibling=p.child,p.child=F):(f=N.last,f!==null?f.sibling=F:p.child=F,N.last=F)}return N.tail!==null?(p=N.tail,N.rendering=p,N.tail=p.sibling,N.renderingStartTime=Zr(),p.sibling=null,f=Zn.current,Ut(Zn,b?f&1|2:f&1),p):(yi(p),null);case 22:case 23:return SS(),b=p.memoizedState!==null,f!==null&&f.memoizedState!==null!==b&&(p.flags|=8192),b&&p.mode&1?ks&1073741824&&(yi(p),qe&&p.subtreeFlags&6&&(p.flags|=8192)):yi(p),null;case 24:return null;case 25:return null}throw Error(o(156,p.tag))}var j5=a.ReactCurrentOwner,Rs=!1;function Ii(f,p,x,b){p.child=f===null?QM(p,null,x,b):Fh(p,f.child,x,b)}function AC(f,p,x,b,N){x=x.render;var F=p.ref;return Lh(p,N),b=qx(f,p,x,b,F,N),x=Xx(),f!==null&&!Rs?(p.updateQueue=f.updateQueue,p.flags&=-2053,f.lanes&=~N,lc(f,p,N)):(Kn&&x&&Ux(p),p.flags|=1,Ii(f,p,b,N),p.child)}function MC(f,p,x,b,N){if(f===null){var F=x.type;return typeof F=="function"&&!bS(F)&&F.defaultProps===void 0&&x.compare===null&&x.defaultProps===void 0?(p.tag=15,p.type=F,CC(f,p,F,b,N)):(f=r0(x.type,null,b,p,p.mode,N),f.ref=p.ref,f.return=p,p.child=f)}if(F=f.child,!(f.lanes&N)){var J=F.memoizedProps;if(x=x.compare,x=x!==null?x:vg,x(J,b)&&f.ref===p.ref)return lc(f,p,N)}return p.flags|=1,f=_l(F,b),f.ref=p.ref,f.return=p,p.child=f}function CC(f,p,x,b,N){if(f!==null&&vg(f.memoizedProps,b)&&f.ref===p.ref)if(Rs=!1,(f.lanes&N)!==0)f.flags&131072&&(Rs=!0);else return p.lanes=f.lanes,lc(f,p,N);return eS(f,p,x,b,N)}function RC(f,p,x){var b=p.pendingProps,N=b.children,F=f!==null?f.memoizedState:null;if(b.mode==="hidden")if(!(p.mode&1))p.memoizedState={baseLanes:0,cachePool:null},Ut(Hh,ks),ks|=x;else if(x&1073741824)p.memoizedState={baseLanes:0,cachePool:null},b=F!==null?F.baseLanes:x,Ut(Hh,ks),ks|=b;else return f=F!==null?F.baseLanes|x:x,p.lanes=p.childLanes=1073741824,p.memoizedState={baseLanes:f,cachePool:null},p.updateQueue=null,Ut(Hh,ks),ks|=f,null;else F!==null?(b=F.baseLanes|x,p.memoizedState=null):b=x,Ut(Hh,ks),ks|=b;return Ii(f,p,N,x),p.child}function kC(f,p){var x=p.ref;(f===null&&x!==null||f!==null&&f.ref!==x)&&(p.flags|=512,p.flags|=2097152)}function eS(f,p,x,b,N){var F=dr(x)?Yt:Qe.current;return F=Kr(p,F),Lh(p,N),x=qx(f,p,x,b,F,N),b=Xx(),f!==null&&!Rs?(p.updateQueue=f.updateQueue,p.flags&=-2053,f.lanes&=~N,lc(f,p,N)):(Kn&&b&&Ux(p),p.flags|=1,Ii(f,p,x,N),p.child)}function NC(f,p,x,b,N){if(dr(x)){var F=!0;Ni(p)}else F=!1;if(Lh(p,N),p.stateNode===null)f!==null&&(f.alternate=null,p.alternate=null,p.flags|=2),jM(p,x,b),Dx(p,x,b,N),b=!0;else if(f===null){var J=p.stateNode,oe=p.memoizedProps;J.props=oe;var Re=J.context,Fe=x.contextType;typeof Fe=="object"&&Fe!==null?Fe=js(Fe):(Fe=dr(x)?Yt:Qe.current,Fe=Kr(p,Fe));var at=x.getDerivedStateFromProps,Ot=typeof at=="function"||typeof J.getSnapshotBeforeUpdate=="function";Ot||typeof J.UNSAFE_componentWillReceiveProps!="function"&&typeof J.componentWillReceiveProps!="function"||(oe!==b||Re!==Fe)&&$M(p,J,b,Fe),hl=!1;var St=p.memoizedState;J.state=St,Eg(p,b,J,N),Re=p.memoizedState,oe!==b||St!==Re||qn.current||hl?(typeof at=="function"&&(Px(p,x,at,b),Re=p.memoizedState),(oe=hl||WM(p,x,oe,b,St,Re,Fe))?(Ot||typeof J.UNSAFE_componentWillMount!="function"&&typeof J.componentWillMount!="function"||(typeof J.componentWillMount=="function"&&J.componentWillMount(),typeof J.UNSAFE_componentWillMount=="function"&&J.UNSAFE_componentWillMount()),typeof J.componentDidMount=="function"&&(p.flags|=4194308)):(typeof J.componentDidMount=="function"&&(p.flags|=4194308),p.memoizedProps=b,p.memoizedState=Re),J.props=b,J.state=Re,J.context=Fe,b=oe):(typeof J.componentDidMount=="function"&&(p.flags|=4194308),b=!1)}else{J=p.stateNode,zM(f,p),oe=p.memoizedProps,Fe=p.type===p.elementType?oe:Eo(p.type,oe),J.props=Fe,Ot=p.pendingProps,St=J.context,Re=x.contextType,typeof Re=="object"&&Re!==null?Re=js(Re):(Re=dr(x)?Yt:Qe.current,Re=Kr(p,Re));var On=x.getDerivedStateFromProps;(at=typeof On=="function"||typeof J.getSnapshotBeforeUpdate=="function")||typeof J.UNSAFE_componentWillReceiveProps!="function"&&typeof J.componentWillReceiveProps!="function"||(oe!==Ot||St!==Re)&&$M(p,J,b,Re),hl=!1,St=p.memoizedState,J.state=St,Eg(p,b,J,N);var _t=p.memoizedState;oe!==Ot||St!==_t||qn.current||hl?(typeof On=="function"&&(Px(p,x,On,b),_t=p.memoizedState),(Fe=hl||WM(p,x,Fe,b,St,_t,Re)||!1)?(at||typeof J.UNSAFE_componentWillUpdate!="function"&&typeof J.componentWillUpdate!="function"||(typeof J.componentWillUpdate=="function"&&J.componentWillUpdate(b,_t,Re),typeof J.UNSAFE_componentWillUpdate=="function"&&J.UNSAFE_componentWillUpdate(b,_t,Re)),typeof J.componentDidUpdate=="function"&&(p.flags|=4),typeof J.getSnapshotBeforeUpdate=="function"&&(p.flags|=1024)):(typeof J.componentDidUpdate!="function"||oe===f.memoizedProps&&St===f.memoizedState||(p.flags|=4),typeof J.getSnapshotBeforeUpdate!="function"||oe===f.memoizedProps&&St===f.memoizedState||(p.flags|=1024),p.memoizedProps=b,p.memoizedState=_t),J.props=b,J.state=_t,J.context=Re,b=Fe):(typeof J.componentDidUpdate!="function"||oe===f.memoizedProps&&St===f.memoizedState||(p.flags|=4),typeof J.getSnapshotBeforeUpdate!="function"||oe===f.memoizedProps&&St===f.memoizedState||(p.flags|=1024),b=!1)}return tS(f,p,x,b,F,N)}function tS(f,p,x,b,N,F){kC(f,p);var J=(p.flags&128)!==0;if(!b&&!J)return N&&ul(p,x,!1),lc(f,p,F);b=p.stateNode,j5.current=p;var oe=J&&typeof x.getDerivedStateFromError!="function"?null:b.render();return p.flags|=1,f!==null&&J?(p.child=Fh(p,f.child,null,F),p.child=Fh(p,null,oe,F)):Ii(f,p,oe,F),p.memoizedState=b.state,N&&ul(p,x,!0),p.child}function IC(f){var p=f.stateNode;p.pendingContext?ll(f,p.pendingContext,p.pendingContext!==p.context):p.context&&ll(f,p.context,!1),Hx(f,p.containerInfo)}function OC(f,p,x,b,N){return Uh(),Vx(N),p.flags|=256,Ii(f,p,x,b),p.child}var Ug={dehydrated:null,treeContext:null,retryLane:0};function Fg(f){return{baseLanes:f,cachePool:null}}function LC(f,p,x){var b=p.pendingProps,N=Zn.current,F=!1,J=(p.flags&128)!==0,oe;if((oe=J)||(oe=f!==null&&f.memoizedState===null?!1:(N&2)!==0),oe?(F=!0,p.flags&=-129):(f===null||f.memoizedState!==null)&&(N|=1),Ut(Zn,N&1),f===null)return zx(p),f=p.memoizedState,f!==null&&(f=f.dehydrated,f!==null)?(p.mode&1?au(f)?p.lanes=8:p.lanes=1073741824:p.lanes=1,null):(N=b.children,f=b.fallback,F?(b=p.mode,F=p.child,N={mode:"hidden",children:N},!(b&1)&&F!==null?(F.childLanes=0,F.pendingProps=N):F=i0(N,b,0,null),f=gu(f,b,x,null),F.return=p,f.return=p,F.sibling=f,p.child=F,p.child.memoizedState=Fg(x),p.memoizedState=Ug,f):nS(p,N));if(N=f.memoizedState,N!==null){if(oe=N.dehydrated,oe!==null){if(J)return p.flags&256?(p.flags&=-257,Bg(f,p,x,Error(o(422)))):p.memoizedState!==null?(p.child=f.child,p.flags|=128,null):(F=b.fallback,N=p.mode,b=i0({mode:"visible",children:b.children},N,0,null),F=gu(F,N,x,null),F.flags|=2,b.return=p,F.return=p,b.sibling=F,p.child=b,p.mode&1&&Fh(p,f.child,null,x),p.child.memoizedState=Fg(x),p.memoizedState=Ug,F);if(!(p.mode&1))p=Bg(f,p,x,null);else if(au(oe))p=Bg(f,p,x,Error(o(419)));else if(b=(x&f.childLanes)!==0,Rs||b){if(b=Tr,b!==null){switch(x&-x){case 4:F=2;break;case 16:F=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:F=32;break;case 536870912:F=268435456;break;default:F=0}b=F&(b.suspendedLanes|x)?0:F,b!==0&&b!==N.retryLane&&(N.retryLane=b,Ys(f,b,-1))}ES(),p=Bg(f,p,x,Error(o(421)))}else ta(oe)?(p.flags|=128,p.child=f.child,p=iz.bind(null,f),ag(oe,p),p=null):(x=N.treeContext,De&&(Cs=Ih(oe),Ms=p,Kn=!0,bo=null,Od=!1,x!==null&&($s[qs++]=oc,$s[qs++]=ac,$s[qs++]=cu,oc=x.id,ac=x.overflow,cu=p)),p=nS(p,p.pendingProps.children),p.flags|=4096);return p}return F?(b=DC(f,p,b.children,b.fallback,x),F=p.child,N=f.child.memoizedState,F.memoizedState=N===null?Fg(x):{baseLanes:N.baseLanes|x,cachePool:null},F.childLanes=f.childLanes&~x,p.memoizedState=Ug,b):(x=PC(f,p,b.children,x),p.memoizedState=null,x)}return F?(b=DC(f,p,b.children,b.fallback,x),F=p.child,N=f.child.memoizedState,F.memoizedState=N===null?Fg(x):{baseLanes:N.baseLanes|x,cachePool:null},F.childLanes=f.childLanes&~x,p.memoizedState=Ug,b):(x=PC(f,p,b.children,x),p.memoizedState=null,x)}function nS(f,p){return p=i0({mode:"visible",children:p},f.mode,0,null),p.return=f,f.child=p}function PC(f,p,x,b){var N=f.child;return f=N.sibling,x=_l(N,{mode:"visible",children:x}),!(p.mode&1)&&(x.lanes=b),x.return=p,x.sibling=null,f!==null&&(b=p.deletions,b===null?(p.deletions=[f],p.flags|=16):b.push(f)),p.child=x}function DC(f,p,x,b,N){var F=p.mode;f=f.child;var J=f.sibling,oe={mode:"hidden",children:x};return!(F&1)&&p.child!==f?(x=p.child,x.childLanes=0,x.pendingProps=oe,p.deletions=null):(x=_l(f,oe),x.subtreeFlags=f.subtreeFlags&14680064),J!==null?b=_l(J,b):(b=gu(b,F,N,null),b.flags|=2),b.return=p,x.return=p,x.sibling=b,p.child=x,b}function Bg(f,p,x,b){return b!==null&&Vx(b),Fh(p,f.child,null,x),f=nS(p,p.pendingProps.children),f.flags|=2,p.memoizedState=null,f}function UC(f,p,x){f.lanes|=p;var b=f.alternate;b!==null&&(b.lanes|=p),Ox(f.return,p,x)}function rS(f,p,x,b,N){var F=f.memoizedState;F===null?f.memoizedState={isBackwards:p,rendering:null,renderingStartTime:0,last:b,tail:x,tailMode:N}:(F.isBackwards=p,F.rendering=null,F.renderingStartTime=0,F.last=b,F.tail=x,F.tailMode=N)}function FC(f,p,x){var b=p.pendingProps,N=b.revealOrder,F=b.tail;if(Ii(f,p,b.children,x),b=Zn.current,b&2)b=b&1|2,p.flags|=128;else{if(f!==null&&f.flags&128)e:for(f=p.child;f!==null;){if(f.tag===13)f.memoizedState!==null&&UC(f,x,p);else if(f.tag===19)UC(f,x,p);else if(f.child!==null){f.child.return=f,f=f.child;continue}if(f===p)break e;for(;f.sibling===null;){if(f.return===null||f.return===p)break e;f=f.return}f.sibling.return=f.return,f=f.sibling}b&=1}if(Ut(Zn,b),!(p.mode&1))p.memoizedState=null;else switch(N){case"forwards":for(x=p.child,N=null;x!==null;)f=x.alternate,f!==null&&Mg(f)===null&&(N=x),x=x.sibling;x=N,x===null?(N=p.child,p.child=null):(N=x.sibling,x.sibling=null),rS(p,!1,N,x,F);break;case"backwards":for(x=null,N=p.child,p.child=null;N!==null;){if(f=N.alternate,f!==null&&Mg(f)===null){p.child=N;break}f=N.sibling,N.sibling=x,x=N,N=f}rS(p,!0,x,null,F);break;case"together":rS(p,!1,null,null,void 0);break;default:p.memoizedState=null}return p.child}function lc(f,p,x){if(f!==null&&(p.dependencies=f.dependencies),Gh|=p.lanes,!(x&p.childLanes))return null;if(f!==null&&p.child!==f.child)throw Error(o(153));if(p.child!==null){for(f=p.child,x=_l(f,f.pendingProps),p.child=x,x.return=p;f.sibling!==null;)f=f.sibling,x=x.sibling=_l(f,f.pendingProps),x.return=p;x.sibling=null}return p.child}function $5(f,p,x){switch(p.tag){case 3:IC(p),Uh();break;case 5:eC(p);break;case 1:dr(p.type)&&Ni(p);break;case 4:Hx(p,p.stateNode.containerInfo);break;case 10:BM(p,p.type._context,p.memoizedProps.value);break;case 13:var b=p.memoizedState;if(b!==null)return b.dehydrated!==null?(Ut(Zn,Zn.current&1),p.flags|=128,null):x&p.child.childLanes?LC(f,p,x):(Ut(Zn,Zn.current&1),f=lc(f,p,x),f!==null?f.sibling:null);Ut(Zn,Zn.current&1);break;case 19:if(b=(x&p.childLanes)!==0,f.flags&128){if(b)return FC(f,p,x);p.flags|=128}var N=p.memoizedState;if(N!==null&&(N.rendering=null,N.tail=null,N.lastEffect=null),Ut(Zn,Zn.current),b)break;return null;case 22:case 23:return p.lanes=0,RC(f,p,x)}return lc(f,p,x)}function q5(f,p){switch(Fx(p),p.tag){case 1:return dr(p.type)&&Yr(),f=p.flags,f&65536?(p.flags=f&-65537|128,p):null;case 3:return zh(),bt(qn),bt(Qe),jx(),f=p.flags,f&65536&&!(f&128)?(p.flags=f&-65537|128,p):null;case 5:return Gx(p),null;case 13:if(bt(Zn),f=p.memoizedState,f!==null&&f.dehydrated!==null){if(p.alternate===null)throw Error(o(340));Uh()}return f=p.flags,f&65536?(p.flags=f&-65537|128,p):null;case 19:return bt(Zn),null;case 4:return zh(),null;case 10:return Ix(p.type._context),null;case 22:case 23:return SS(),null;case 24:return null;default:return null}}var zg=!1,hu=!1,X5=typeof WeakSet=="function"?WeakSet:Set,Ze=null;function Vg(f,p){var x=f.ref;if(x!==null)if(typeof x=="function")try{x(null)}catch(b){is(f,p,b)}else x.current=null}function iS(f,p,x){try{x()}catch(b){is(f,p,b)}}var BC=!1;function K5(f,p){for(W(f.containerInfo),Ze=p;Ze!==null;)if(f=Ze,p=f.child,(f.subtreeFlags&1028)!==0&&p!==null)p.return=f,Ze=p;else for(;Ze!==null;){f=Ze;try{var x=f.alternate;if(f.flags&1024)switch(f.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var b=x.memoizedProps,N=x.memoizedState,F=f.stateNode,J=F.getSnapshotBeforeUpdate(f.elementType===f.type?b:Eo(f.type,b),N);F.__reactInternalSnapshotBeforeUpdate=J}break;case 3:qe&&Ne(f.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(o(163))}}catch(oe){is(f,f.return,oe)}if(p=f.sibling,p!==null){p.return=f.return,Ze=p;break}Ze=f.return}return x=BC,BC=!1,x}function fu(f,p,x){var b=p.updateQueue;if(b=b!==null?b.lastEffect:null,b!==null){var N=b=b.next;do{if((N.tag&f)===f){var F=N.destroy;N.destroy=void 0,F!==void 0&&iS(p,x,F)}N=N.next}while(N!==b)}}function jd(f,p){if(p=p.updateQueue,p=p!==null?p.lastEffect:null,p!==null){var x=p=p.next;do{if((x.tag&f)===f){var b=x.create;x.destroy=b()}x=x.next}while(x!==p)}}function sS(f){var p=f.ref;if(p!==null){var x=f.stateNode;switch(f.tag){case 5:f=V(x);break;default:f=x}typeof p=="function"?p(f):p.current=f}}function zC(f,p,x){if(ia&&typeof ia.onCommitFiberUnmount=="function")try{ia.onCommitFiberUnmount(gg,p)}catch{}switch(p.tag){case 0:case 11:case 14:case 15:if(f=p.updateQueue,f!==null&&(f=f.lastEffect,f!==null)){var b=f=f.next;do{var N=b,F=N.destroy;N=N.tag,F!==void 0&&(N&2||N&4)&&iS(p,x,F),b=b.next}while(b!==f)}break;case 1:if(Vg(p,x),f=p.stateNode,typeof f.componentWillUnmount=="function")try{f.props=p.memoizedProps,f.state=p.memoizedState,f.componentWillUnmount()}catch(J){is(p,x,J)}break;case 5:Vg(p,x);break;case 4:qe?$C(f,p,x):it&&it&&(p=p.stateNode.containerInfo,x=Je(p),Pr(p,x))}}function VC(f,p,x){for(var b=p;;)if(zC(f,b,x),b.child===null||qe&&b.tag===4){if(b===p)break;for(;b.sibling===null;){if(b.return===null||b.return===p)return;b=b.return}b.sibling.return=b.return,b=b.sibling}else b.child.return=b,b=b.child}function HC(f){var p=f.alternate;p!==null&&(f.alternate=null,HC(p)),f.child=null,f.deletions=null,f.sibling=null,f.tag===5&&(p=f.stateNode,p!==null&&X(p)),f.stateNode=null,f.return=null,f.dependencies=null,f.memoizedProps=null,f.memoizedState=null,f.pendingProps=null,f.stateNode=null,f.updateQueue=null}function GC(f){return f.tag===5||f.tag===3||f.tag===4}function WC(f){e:for(;;){for(;f.sibling===null;){if(f.return===null||GC(f.return))return null;f=f.return}for(f.sibling.return=f.return,f=f.sibling;f.tag!==5&&f.tag!==6&&f.tag!==18;){if(f.flags&2||f.child===null||f.tag===4)continue e;f.child.return=f,f=f.child}if(!(f.flags&2))return f.stateNode}}function jC(f){if(qe){e:{for(var p=f.return;p!==null;){if(GC(p))break e;p=p.return}throw Error(o(160))}var x=p;switch(x.tag){case 5:p=x.stateNode,x.flags&32&&(kt(p),x.flags&=-33),x=WC(f),aS(f,x,p);break;case 3:case 4:p=x.stateNode.containerInfo,x=WC(f),oS(f,x,p);break;default:throw Error(o(161))}}}function oS(f,p,x){var b=f.tag;if(b===5||b===6)f=f.stateNode,p?xt(x,f,p):Ge(x,f);else if(b!==4&&(f=f.child,f!==null))for(oS(f,p,x),f=f.sibling;f!==null;)oS(f,p,x),f=f.sibling}function aS(f,p,x){var b=f.tag;if(b===5||b===6)f=f.stateNode,p?et(x,f,p):Oe(x,f);else if(b!==4&&(f=f.child,f!==null))for(aS(f,p,x),f=f.sibling;f!==null;)aS(f,p,x),f=f.sibling}function $C(f,p,x){for(var b=p,N=!1,F,J;;){if(!N){N=b.return;e:for(;;){if(N===null)throw Error(o(160));switch(F=N.stateNode,N.tag){case 5:J=!1;break e;case 3:F=F.containerInfo,J=!0;break e;case 4:F=F.containerInfo,J=!0;break e}N=N.return}N=!0}if(b.tag===5||b.tag===6)VC(f,b,x),J?Rt(F,b.stateNode):rt(F,b.stateNode);else if(b.tag===18)J?Te(F,b.stateNode):fe(F,b.stateNode);else if(b.tag===4){if(b.child!==null){F=b.stateNode.containerInfo,J=!0,b.child.return=b,b=b.child;continue}}else if(zC(f,b,x),b.child!==null){b.child.return=b,b=b.child;continue}if(b===p)break;for(;b.sibling===null;){if(b.return===null||b.return===p)return;b=b.return,b.tag===4&&(N=!1)}b.sibling.return=b.return,b=b.sibling}}function cS(f,p){if(qe){switch(p.tag){case 0:case 11:case 14:case 15:fu(3,p,p.return),jd(3,p),fu(5,p,p.return);return;case 1:return;case 5:var x=p.stateNode;if(x!=null){var b=p.memoizedProps;f=f!==null?f.memoizedProps:b;var N=p.type,F=p.updateQueue;p.updateQueue=null,F!==null&&nt(x,F,N,f,b,p)}return;case 6:if(p.stateNode===null)throw Error(o(162));x=p.memoizedProps,Dt(p.stateNode,f!==null?f.memoizedProps:x,x);return;case 3:De&&f!==null&&f.memoizedState.isDehydrated&&hg(p.stateNode.containerInfo);return;case 12:return;case 13:Hg(p);return;case 19:Hg(p);return;case 17:return}throw Error(o(163))}switch(p.tag){case 0:case 11:case 14:case 15:fu(3,p,p.return),jd(3,p),fu(5,p,p.return);return;case 12:return;case 13:Hg(p);return;case 19:Hg(p);return;case 3:De&&f!==null&&f.memoizedState.isDehydrated&&hg(p.stateNode.containerInfo);break;case 22:case 23:return}e:if(it){switch(p.tag){case 1:case 5:case 6:break e;case 3:case 4:p=p.stateNode,Pr(p.containerInfo,p.pendingChildren);break e}throw Error(o(163))}}function Hg(f){var p=f.updateQueue;if(p!==null){f.updateQueue=null;var x=f.stateNode;x===null&&(x=f.stateNode=new X5),p.forEach(function(b){var N=sz.bind(null,f,b);x.has(b)||(x.add(b),b.then(N,N))})}}function Y5(f,p){for(Ze=p;Ze!==null;){p=Ze;var x=p.deletions;if(x!==null)for(var b=0;b";case Wg:return":has("+(hS(f)||"")+")";case jg:return'[role="'+f.value+'"]';case qg:return'"'+f.value+'"';case $g:return'[data-testname="'+f.value+'"]';default:throw Error(o(365))}}function ZC(f,p){var x=[];f=[f,0];for(var b=0;bN&&(N=J),b&=~F}if(b=N,b=Zr()-b,b=(120>b?120:480>b?480:1080>b?1080:1920>b?1920:3e3>b?3e3:4320>b?4320:1960*J5(b/1960))-b,10f?16:f,pl===null)var b=!1;else{if(f=pl,pl=null,Jg=0,Wt&6)throw Error(o(331));var N=Wt;for(Wt|=4,Ze=f.current;Ze!==null;){var F=Ze,J=F.child;if(Ze.flags&16){var oe=F.deletions;if(oe!==null){for(var Re=0;ReZr()-mS?du(f,0):pS|=x),rs(f,p)}function oR(f,p){p===0&&(f.mode&1?(p=pg,pg<<=1,!(pg&130023424)&&(pg=4194304)):p=1);var x=Oi();f=t0(f,p),f!==null&&(Id(f,p,x),rs(f,x))}function iz(f){var p=f.memoizedState,x=0;p!==null&&(x=p.retryLane),oR(f,x)}function sz(f,p){var x=0;switch(f.tag){case 13:var b=f.stateNode,N=f.memoizedState;N!==null&&(x=N.retryLane);break;case 19:b=f.stateNode;break;default:throw Error(o(314))}b!==null&&b.delete(p),oR(f,x)}var aR;aR=function(f,p,x){if(f!==null)if(f.memoizedProps!==p.pendingProps||qn.current)Rs=!0;else{if(!(f.lanes&x)&&!(p.flags&128))return Rs=!1,$5(f,p,x);Rs=!!(f.flags&131072)}else Rs=!1,Kn&&p.flags&1048576&&qM(p,wg,p.index);switch(p.lanes=0,p.tag){case 2:var b=p.type;f!==null&&(f.alternate=null,p.alternate=null,p.flags|=2),f=p.pendingProps;var N=Kr(p,Qe.current);Lh(p,x),N=qx(null,p,b,f,N,x);var F=Xx();return p.flags|=1,typeof N=="object"&&N!==null&&typeof N.render=="function"&&N.$$typeof===void 0?(p.tag=1,p.memoizedState=null,p.updateQueue=null,dr(b)?(F=!0,Ni(p)):F=!1,p.memoizedState=N.state!==null&&N.state!==void 0?N.state:null,Lx(p),N.updater=bg,p.stateNode=N,N._reactInternals=p,Dx(p,b,f,x),p=tS(null,p,b,!0,F,x)):(p.tag=0,Kn&&F&&Ux(p),Ii(null,p,N,x),p=p.child),p;case 16:b=p.elementType;e:{switch(f!==null&&(f.alternate=null,p.alternate=null,p.flags|=2),f=p.pendingProps,N=b._init,b=N(b._payload),p.type=b,N=p.tag=az(b),f=Eo(b,f),N){case 0:p=eS(null,p,b,f,x);break e;case 1:p=NC(null,p,b,f,x);break e;case 11:p=AC(null,p,b,f,x);break e;case 14:p=MC(null,p,b,Eo(b.type,f),x);break e}throw Error(o(306,b,""))}return p;case 0:return b=p.type,N=p.pendingProps,N=p.elementType===b?N:Eo(b,N),eS(f,p,b,N,x);case 1:return b=p.type,N=p.pendingProps,N=p.elementType===b?N:Eo(b,N),NC(f,p,b,N,x);case 3:e:{if(IC(p),f===null)throw Error(o(387));b=p.pendingProps,F=p.memoizedState,N=F.element,zM(f,p),Eg(p,b,null,x);var J=p.memoizedState;if(b=J.element,De&&F.isDehydrated)if(F={element:b,isDehydrated:!1,cache:J.cache,transitions:J.transitions},p.updateQueue.baseState=F,p.memoizedState=F,p.flags&256){N=Error(o(423)),p=OC(f,p,b,x,N);break e}else if(b!==N){N=Error(o(424)),p=OC(f,p,b,x,N);break e}else for(De&&(Cs=cg(p.stateNode.containerInfo),Ms=p,Kn=!0,bo=null,Od=!1),x=QM(p,null,b,x),p.child=x;x;)x.flags=x.flags&-3|4096,x=x.sibling;else{if(Uh(),b===N){p=lc(f,p,x);break e}Ii(f,p,b,x)}p=p.child}return p;case 5:return eC(p),f===null&&zx(p),b=p.type,N=p.pendingProps,F=f!==null?f.memoizedProps:null,J=N.children,re(b,N)?J=null:F!==null&&re(b,F)&&(p.flags|=32),kC(f,p),Ii(f,p,J,x),p.child;case 6:return f===null&&zx(p),null;case 13:return LC(f,p,x);case 4:return Hx(p,p.stateNode.containerInfo),b=p.pendingProps,f===null?p.child=Fh(p,null,b,x):Ii(f,p,b,x),p.child;case 11:return b=p.type,N=p.pendingProps,N=p.elementType===b?N:Eo(b,N),AC(f,p,b,N,x);case 7:return Ii(f,p,p.pendingProps,x),p.child;case 8:return Ii(f,p,p.pendingProps.children,x),p.child;case 12:return Ii(f,p,p.pendingProps.children,x),p.child;case 10:e:{if(b=p.type._context,N=p.pendingProps,F=p.memoizedProps,J=N.value,BM(p,b,J),F!==null)if(sa(F.value,J)){if(F.children===N.children&&!qn.current){p=lc(f,p,x);break e}}else for(F=p.child,F!==null&&(F.return=p);F!==null;){var oe=F.dependencies;if(oe!==null){J=F.child;for(var Re=oe.firstContext;Re!==null;){if(Re.context===b){if(F.tag===1){Re=sc(-1,x&-x),Re.tag=2;var Fe=F.updateQueue;if(Fe!==null){Fe=Fe.shared;var at=Fe.pending;at===null?Re.next=Re:(Re.next=at.next,at.next=Re),Fe.pending=Re}}F.lanes|=x,Re=F.alternate,Re!==null&&(Re.lanes|=x),Ox(F.return,x,p),oe.lanes|=x;break}Re=Re.next}}else if(F.tag===10)J=F.type===p.type?null:F.child;else if(F.tag===18){if(J=F.return,J===null)throw Error(o(341));J.lanes|=x,oe=J.alternate,oe!==null&&(oe.lanes|=x),Ox(J,x,p),J=F.sibling}else J=F.child;if(J!==null)J.return=F;else for(J=F;J!==null;){if(J===p){J=null;break}if(F=J.sibling,F!==null){F.return=J.return,J=F;break}J=J.return}F=J}Ii(f,p,N.children,x),p=p.child}return p;case 9:return N=p.type,b=p.pendingProps.children,Lh(p,x),N=js(N),b=b(N),p.flags|=1,Ii(f,p,b,x),p.child;case 14:return b=p.type,N=Eo(b,p.pendingProps),N=Eo(b.type,N),MC(f,p,b,N,x);case 15:return CC(f,p,p.type,p.pendingProps,x);case 17:return b=p.type,N=p.pendingProps,N=p.elementType===b?N:Eo(b,N),f!==null&&(f.alternate=null,p.alternate=null,p.flags|=2),p.tag=1,dr(b)?(f=!0,Ni(p)):f=!1,Lh(p,x),jM(p,b,N),Dx(p,b,N,x),tS(null,p,b,!0,f,x);case 19:return FC(f,p,x);case 22:return RC(f,p,x)}throw Error(o(156,p.tag))};function cR(f,p){return Ax(f,p)}function oz(f,p,x,b){this.tag=f,this.key=x,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=p,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=b,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Zs(f,p,x,b){return new oz(f,p,x,b)}function bS(f){return f=f.prototype,!(!f||!f.isReactComponent)}function az(f){if(typeof f=="function")return bS(f)?1:0;if(f!=null){if(f=f.$$typeof,f===v)return 11;if(f===S)return 14}return 2}function _l(f,p){var x=f.alternate;return x===null?(x=Zs(f.tag,p,f.key,f.mode),x.elementType=f.elementType,x.type=f.type,x.stateNode=f.stateNode,x.alternate=f,f.alternate=x):(x.pendingProps=p,x.type=f.type,x.flags=0,x.subtreeFlags=0,x.deletions=null),x.flags=f.flags&14680064,x.childLanes=f.childLanes,x.lanes=f.lanes,x.child=f.child,x.memoizedProps=f.memoizedProps,x.memoizedState=f.memoizedState,x.updateQueue=f.updateQueue,p=f.dependencies,x.dependencies=p===null?null:{lanes:p.lanes,firstContext:p.firstContext},x.sibling=f.sibling,x.index=f.index,x.ref=f.ref,x}function r0(f,p,x,b,N,F){var J=2;if(b=f,typeof f=="function")bS(f)&&(J=1);else if(typeof f=="string")J=5;else e:switch(f){case u:return gu(x.children,N,F,p);case h:J=8,N|=8;break;case d:return f=Zs(12,x,p,N|2),f.elementType=d,f.lanes=F,f;case y:return f=Zs(13,x,p,N),f.elementType=y,f.lanes=F,f;case _:return f=Zs(19,x,p,N),f.elementType=_,f.lanes=F,f;case T:return i0(x,N,F,p);default:if(typeof f=="object"&&f!==null)switch(f.$$typeof){case m:J=10;break e;case g:J=9;break e;case v:J=11;break e;case S:J=14;break e;case E:J=16,b=null;break e}throw Error(o(130,f==null?f:typeof f,""))}return p=Zs(J,x,p,N),p.elementType=f,p.type=b,p.lanes=F,p}function gu(f,p,x,b){return f=Zs(7,f,b,p),f.lanes=x,f}function i0(f,p,x,b){return f=Zs(22,f,b,p),f.elementType=T,f.lanes=x,f.stateNode={},f}function TS(f,p,x){return f=Zs(6,f,null,p),f.lanes=x,f}function wS(f,p,x){return p=Zs(4,f.children!==null?f.children:[],f.key,p),p.lanes=x,p.stateNode={containerInfo:f.containerInfo,pendingChildren:null,implementation:f.implementation},p}function cz(f,p,x,b,N){this.tag=p,this.containerInfo=f,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Le,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Tx(0),this.expirationTimes=Tx(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Tx(0),this.identifierPrefix=b,this.onRecoverableError=N,De&&(this.mutableSourceEagerHydrationData=null)}function lR(f,p,x,b,N,F,J,oe,Re){return f=new cz(f,p,x,oe,Re),p===1?(p=1,F===!0&&(p|=8)):p=0,F=Zs(3,null,null,p),f.current=F,F.stateNode=f,F.memoizedState={element:b,isDehydrated:x,cache:null,transitions:null},Lx(F),f}function uR(f){if(!f)return Gt;f=f._reactInternals;e:{if(C(f)!==f||f.tag!==1)throw Error(o(170));var p=f;do{switch(p.tag){case 3:p=p.stateNode.context;break e;case 1:if(dr(p.type)){p=p.stateNode.__reactInternalMemoizedMergedChildContext;break e}}p=p.return}while(p!==null);throw Error(o(171))}if(f.tag===1){var x=f.type;if(dr(x))return Mn(f,x,p)}return p}function hR(f){var p=f._reactInternals;if(p===void 0)throw typeof f.render=="function"?Error(o(188)):(f=Object.keys(f).join(","),Error(o(268,f)));return f=L(p),f===null?null:f.stateNode}function fR(f,p){if(f=f.memoizedState,f!==null&&f.dehydrated!==null){var x=f.retryLane;f.retryLane=x!==0&&x=Fe&&F>=Ot&&N<=at&&J<=St){f.splice(p,1);break}else if(b!==Fe||x.width!==Re.width||StJ){if(!(F!==Ot||x.height!==Re.height||atN)){Fe>b&&(Re.width+=Fe-b,Re.x=b),atF&&(Re.height+=Ot-F,Re.y=F),Stx&&(x=J)),J ")+` + +No matching component was found for: + `)+f.join(" > ")}return null},t.getPublicRootInstance=function(f){if(f=f.current,!f.child)return null;switch(f.child.tag){case 5:return V(f.child.stateNode);default:return f.child.stateNode}},t.injectIntoDevTools=function(f){if(f={bundleType:f.bundleType,version:f.version,rendererPackageName:f.rendererPackageName,rendererConfig:f.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:a.ReactCurrentDispatcher,findHostInstanceByFiber:lz,findFiberByHostInstance:f.findFiberByHostInstance||uz,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.0.0-fc46dba67-20220329"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")f=!1;else{var p=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(p.isDisabled||!p.supportsFiber)f=!0;else{try{gg=p.inject(f),ia=p}catch{}f=!!p.checkDCE}}return f},t.isAlreadyRendering=function(){return!1},t.observeVisibleRects=function(f,p,x,b){if(!ae)throw Error(o(363));f=fS(f,p);var N=ze(f,x,b).disconnect;return{disconnect:function(){N()}}},t.registerMutableSourceForHydration=function(f,p){var x=p._getVersion;x=x(p._source),f.mutableSourceEagerHydrationData==null?f.mutableSourceEagerHydrationData=[p,x]:f.mutableSourceEagerHydrationData.push(p,x)},t.runWithPriority=function(f,p){var x=mn;try{return mn=f,p()}finally{mn=x}},t.shouldError=function(){return null},t.shouldSuspend=function(){return!1},t.updateContainer=function(f,p,x,b){var N=p.current,F=Oi(),J=ml(N);return x=uR(x),p.context===null?p.context=x:p.pendingContext=x,p=sc(F,J),p.payload={element:f},b=b===void 0?null:b,b!==null&&(p.callback=b),fl(N,p),f=Ys(N,J,F),f!==null&&Sg(f,N,J),J},t};mL.exports=_j;var vj=mL.exports;const yj=$a(vj),ZT={},JT=n=>void Object.assign(ZT,n);function xj(n,e){function t(u,{args:h=[],attach:d,...m},g){let v=`${u[0].toUpperCase()}${u.slice(1)}`,y;if(u==="primitive"){if(m.object===void 0)throw new Error("R3F: Primitives without 'object' are invalid!");const _=m.object;y=mf(_,{type:u,root:g,attach:d,primitive:!0})}else{const _=ZT[v];if(!_)throw new Error(`R3F: ${v} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`);if(!Array.isArray(h))throw new Error("R3F: The args prop must be an array!");y=mf(new _(...h),{type:u,root:g,attach:d,memoizedProps:{args:h}})}return y.__r3f.attach===void 0&&(y instanceof jo?y.__r3f.attach="geometry":y instanceof Kc&&(y.__r3f.attach="material")),v!=="inject"&&i1(y,m),y}function r(u,h){let d=!1;if(h){var m,g;(m=h.__r3f)!=null&&m.attach?r1(u,h,h.__r3f.attach):h.isObject3D&&u.isObject3D&&(u.add(h),d=!0),d||(g=u.__r3f)==null||g.objects.push(h),h.__r3f||mf(h,{}),h.__r3f.parent=u,$E(h),gf(h)}}function i(u,h,d){let m=!1;if(h){var g,v;if((g=h.__r3f)!=null&&g.attach)r1(u,h,h.__r3f.attach);else if(h.isObject3D&&u.isObject3D){h.parent=u,h.dispatchEvent({type:"added"}),u.dispatchEvent({type:"childadded",child:h});const y=u.children.filter(S=>S!==h),_=y.indexOf(d);u.children=[...y.slice(0,_),h,...y.slice(_)],m=!0}m||(v=u.__r3f)==null||v.objects.push(h),h.__r3f||mf(h,{}),h.__r3f.parent=u,$E(h),gf(h)}}function s(u,h,d=!1){u&&[...u].forEach(m=>o(h,m,d))}function o(u,h,d){if(h){var m,g,v;if(h.__r3f&&(h.__r3f.parent=null),(m=u.__r3f)!=null&&m.objects&&(u.__r3f.objects=u.__r3f.objects.filter(T=>T!==h)),(g=h.__r3f)!=null&&g.attach)M2(u,h,h.__r3f.attach);else if(h.isObject3D&&u.isObject3D){var y;u.remove(h),(y=h.__r3f)!=null&&y.root&&Rj(g_(h),h)}const S=(v=h.__r3f)==null?void 0:v.primitive,E=!S&&(d===void 0?h.dispose!==null:d);if(!S){var _;s((_=h.__r3f)==null?void 0:_.objects,h,E),s(h.children,h,E)}if(delete h.__r3f,E&&h.dispose&&h.type!=="Scene"){const T=()=>{try{h.dispose()}catch{}};typeof IS_REACT_ACT_ENVIRONMENT>"u"?WE.unstable_scheduleCallback(WE.unstable_IdlePriority,T):T()}gf(u)}}function a(u,h,d,m){var g;const v=(g=u.__r3f)==null?void 0:g.parent;if(!v)return;const y=t(h,d,u.__r3f.root);if(u.children){for(const _ of u.children)_.__r3f&&r(y,_);u.children=u.children.filter(_=>!_.__r3f)}u.__r3f.objects.forEach(_=>r(y,_)),u.__r3f.objects=[],u.__r3f.autoRemovedBeforeAppend||o(v,u),y.parent&&(y.__r3f.autoRemovedBeforeAppend=!0),r(v,y),y.raycast&&y.__r3f.eventCount&&g_(y).getState().internal.interaction.push(y),[m,m.alternate].forEach(_=>{_!==null&&(_.stateNode=y,_.ref&&(typeof _.ref=="function"?_.ref(y):_.ref.current=y))})}const c=()=>{};return{reconciler:yj({createInstance:t,removeChild:o,appendChild:r,appendInitialChild:r,insertBefore:i,supportsMutation:!0,isPrimaryRenderer:!1,supportsPersistence:!1,supportsHydration:!1,noTimeout:-1,appendChildToContainer:(u,h)=>{if(!h)return;const d=u.getState().scene;d.__r3f&&(d.__r3f.root=u,r(d,h))},removeChildFromContainer:(u,h)=>{h&&o(u.getState().scene,h)},insertInContainerBefore:(u,h,d)=>{if(!h||!d)return;const m=u.getState().scene;m.__r3f&&i(m,h,d)},getRootHostContext:()=>null,getChildHostContext:u=>u,finalizeInitialChildren(u){var h;return!!((h=u==null?void 0:u.__r3f)!=null?h:{}).handlers},prepareUpdate(u,h,d,m){var g;if(((g=u==null?void 0:u.__r3f)!=null?g:{}).primitive&&m.object&&m.object!==u)return[!0];{const{args:y=[],children:_,...S}=m,{args:E=[],children:T,...k}=d;if(!Array.isArray(y))throw new Error("R3F: the args prop must be an array!");if(y.some((M,O)=>M!==E[O]))return[!0];const R=EL(u,S,k,!0);return R.changes.length?[!1,R]:null}},commitUpdate(u,[h,d],m,g,v,y){h?a(u,m,v,y):i1(u,d)},commitMount(u,h,d,m){var g;const v=(g=u.__r3f)!=null?g:{};u.raycast&&v.handlers&&v.eventCount&&g_(u).getState().internal.interaction.push(u)},getPublicInstance:u=>u,prepareForCommit:()=>null,preparePortalMount:u=>mf(u.getState().scene),resetAfterCommit:()=>{},shouldSetTextContent:()=>!1,clearContainer:()=>!1,hideInstance(u){var h;const{attach:d,parent:m}=(h=u.__r3f)!=null?h:{};d&&m&&M2(m,u,d),u.isObject3D&&(u.visible=!1),gf(u)},unhideInstance(u,h){var d;const{attach:m,parent:g}=(d=u.__r3f)!=null?d:{};m&&g&&r1(g,u,m),(u.isObject3D&&h.visible==null||h.visible)&&(u.visible=!0),gf(u)},createTextInstance:c,hideTextInstance:c,unhideTextInstance:c,getCurrentEventPriority:()=>e?e():Ef.DefaultEventPriority,beforeActiveInstanceBlur:()=>{},afterActiveInstanceBlur:()=>{},detachDeletedInstance:()=>{},now:typeof performance<"u"&&Un.fun(performance.now)?performance.now:Un.fun(Date.now)?Date.now:()=>0,scheduleTimeout:Un.fun(setTimeout)?setTimeout:void 0,cancelTimeout:Un.fun(clearTimeout)?clearTimeout:void 0}),applyProps:i1}}var b2,T2;const n1=n=>"colorSpace"in n||"outputColorSpace"in n,vL=()=>{var n;return(n=ZT.ColorManagement)!=null?n:null},yL=n=>n&&n.isOrthographicCamera,ny=typeof window<"u"&&((b2=window.document)!=null&&b2.createElement||((T2=window.navigator)==null?void 0:T2.product)==="ReactNative")?ke.useLayoutEffect:ke.useEffect;function Sj(n){const e=ke.useRef(n);return ny(()=>void(e.current=n),[n]),e}class Ej extends ke.Component{constructor(...e){super(...e),this.state={error:!1}}componentDidCatch(e){this.props.set(e)}render(){return this.state.error?null:this.props.children}}Ej.getDerivedStateFromError=()=>({error:!0});const xL="__default",w2=new Map,bj=n=>n&&!!n.memoized&&!!n.changes;function SL(n){var e;const t=typeof window<"u"?(e=window.devicePixelRatio)!=null?e:2:1;return Array.isArray(n)?Math.min(Math.max(n[0],t),n[1]):n}const tp=n=>{var e;return(e=n.__r3f)==null?void 0:e.root.getState()};function g_(n){let e=n.__r3f.root;for(;e.getState().previousRoot;)e=e.getState().previousRoot;return e}const Un={obj:n=>n===Object(n)&&!Un.arr(n)&&typeof n!="function",fun:n=>typeof n=="function",str:n=>typeof n=="string",num:n=>typeof n=="number",boo:n=>typeof n=="boolean",und:n=>n===void 0,arr:n=>Array.isArray(n),equ(n,e,{arrays:t="shallow",objects:r="reference",strict:i=!0}={}){if(typeof n!=typeof e||!!n!=!!e)return!1;if(Un.str(n)||Un.num(n)||Un.boo(n))return n===e;const s=Un.obj(n);if(s&&r==="reference")return n===e;const o=Un.arr(n);if(o&&t==="reference")return n===e;if((o||s)&&n===e)return!0;let a;for(a in n)if(!(a in e))return!1;if(s&&t==="shallow"&&r==="shallow"){for(a in i?e:n)if(!Un.equ(n[a],e[a],{strict:i,objects:"reference"}))return!1}else for(a in i?e:n)if(n[a]!==e[a])return!1;if(Un.und(a)){if(o&&n.length===0&&e.length===0||s&&Object.keys(n).length===0&&Object.keys(e).length===0)return!0;if(n!==e)return!1}return!0}};function Tj(n){const e={nodes:{},materials:{}};return n&&n.traverse(t=>{t.name&&(e.nodes[t.name]=t),t.material&&!e.materials[t.material.name]&&(e.materials[t.material.name]=t.material)}),e}function wj(n){n.dispose&&n.type!=="Scene"&&n.dispose();for(const e in n)e.dispose==null||e.dispose(),delete n[e]}function mf(n,e){const t=n;return t.__r3f={type:"",root:null,previousAttach:null,memoizedProps:{},eventCount:0,handlers:{},objects:[],parent:null,...e},n}function jE(n,e){let t=n;if(e.includes("-")){const r=e.split("-"),i=r.pop();return t=r.reduce((s,o)=>s[o],n),{target:t,key:i}}else return{target:t,key:e}}const A2=/-\d+$/;function r1(n,e,t){if(Un.str(t)){if(A2.test(t)){const s=t.replace(A2,""),{target:o,key:a}=jE(n,s);Array.isArray(o[a])||(o[a]=[])}const{target:r,key:i}=jE(n,t);e.__r3f.previousAttach=r[i],r[i]=e}else e.__r3f.previousAttach=t(n,e)}function M2(n,e,t){var r,i;if(Un.str(t)){const{target:s,key:o}=jE(n,t),a=e.__r3f.previousAttach;a===void 0?delete s[o]:s[o]=a}else(r=e.__r3f)==null||r.previousAttach==null||r.previousAttach(n,e);(i=e.__r3f)==null||delete i.previousAttach}function EL(n,{children:e,key:t,ref:r,...i},{children:s,key:o,ref:a,...c}={},l=!1){const u=n.__r3f,h=Object.entries(i),d=[];if(l){const g=Object.keys(c);for(let v=0;v{var y;if((y=n.__r3f)!=null&&y.primitive&&g==="object"||Un.equ(v,c[g]))return;if(/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(g))return d.push([g,v,!0,[]]);let _=[];g.includes("-")&&(_=g.split("-")),d.push([g,v,!1,_]);for(const S in i){const E=i[S];S.startsWith(`${g}-`)&&d.push([S,E,!1,S.split("-")])}});const m={...i};return u!=null&&u.memoizedProps&&u!=null&&u.memoizedProps.args&&(m.args=u.memoizedProps.args),u!=null&&u.memoizedProps&&u!=null&&u.memoizedProps.attach&&(m.attach=u.memoizedProps.attach),{memoized:m,changes:d}}const Aj=typeof process<"u"&&!1;function i1(n,e){var t;const r=n.__r3f,i=r==null?void 0:r.root,s=i==null||i.getState==null?void 0:i.getState(),{memoized:o,changes:a}=bj(e)?e:EL(n,e),c=r==null?void 0:r.eventCount;n.__r3f&&(n.__r3f.memoizedProps=o);for(let u=0;u_[S],n),!(y&&y.set))){const[_,...S]=g.reverse();v=S.reverse().reduce((E,T)=>E[T],n),h=_}if(d===xL+"remove")if(v.constructor){let _=w2.get(v.constructor);_||(_=new v.constructor,w2.set(v.constructor,_)),d=_[h]}else d=0;if(m&&r)d?r.handlers[h]=d:delete r.handlers[h],r.eventCount=Object.keys(r.handlers).length;else if(y&&y.set&&(y.copy||y instanceof Of)){if(Array.isArray(d))y.fromArray?y.fromArray(d):y.set(...d);else if(y.copy&&d&&d.constructor&&(Aj?y.constructor.name===d.constructor.name:y.constructor===d.constructor))y.copy(d);else if(d!==void 0){const _=y instanceof hn;!_&&y.setScalar?y.setScalar(d):y instanceof Of&&d instanceof Of?y.mask=d.mask:y.set(d),!vL()&&s&&!s.linear&&_&&y.convertSRGBToLinear()}}else if(v[h]=d,v[h]instanceof ur&&v[h].format===ao&&v[h].type===Mi&&s){const _=v[h];n1(_)&&n1(s.gl)?_.colorSpace=s.gl.outputColorSpace:_.encoding=s.gl.outputEncoding}gf(n)}if(r&&r.parent&&n.raycast&&c!==r.eventCount){const u=g_(n).getState().internal,h=u.interaction.indexOf(n);h>-1&&u.interaction.splice(h,1),r.eventCount&&u.interaction.push(n)}return!(a.length===1&&a[0][0]==="onUpdate")&&a.length&&(t=n.__r3f)!=null&&t.parent&&$E(n),n}function gf(n){var e,t;const r=(e=n.__r3f)==null||(t=e.root)==null||t.getState==null?void 0:t.getState();r&&r.internal.frames===0&&r.invalidate()}function $E(n){n.onUpdate==null||n.onUpdate(n)}function Mj(n,e){n.manual||(yL(n)?(n.left=e.width/-2,n.right=e.width/2,n.top=e.height/2,n.bottom=e.height/-2):n.aspect=e.width/e.height,n.updateProjectionMatrix(),n.updateMatrixWorld())}function R0(n){return(n.eventObject||n.object).uuid+"/"+n.index+n.instanceId}function Cj(){var n;const e=typeof self<"u"&&self||typeof window<"u"&&window;if(!e)return Ef.DefaultEventPriority;switch((n=e.event)==null?void 0:n.type){case"click":case"contextmenu":case"dblclick":case"pointercancel":case"pointerdown":case"pointerup":return Ef.DiscreteEventPriority;case"pointermove":case"pointerout":case"pointerover":case"pointerenter":case"pointerleave":case"wheel":return Ef.ContinuousEventPriority;default:return Ef.DefaultEventPriority}}function bL(n,e,t,r){const i=t.get(e);i&&(t.delete(e),t.size===0&&(n.delete(r),i.target.releasePointerCapture(r)))}function Rj(n,e){const{internal:t}=n.getState();t.interaction=t.interaction.filter(r=>r!==e),t.initialHits=t.initialHits.filter(r=>r!==e),t.hovered.forEach((r,i)=>{(r.eventObject===e||r.object===e)&&t.hovered.delete(i)}),t.capturedMap.forEach((r,i)=>{bL(t.capturedMap,e,r,i)})}function kj(n){function e(c){const{internal:l}=n.getState(),u=c.offsetX-l.initialClick[0],h=c.offsetY-l.initialClick[1];return Math.round(Math.sqrt(u*u+h*h))}function t(c){return c.filter(l=>["Move","Over","Enter","Out","Leave"].some(u=>{var h;return(h=l.__r3f)==null?void 0:h.handlers["onPointer"+u]}))}function r(c,l){const u=n.getState(),h=new Set,d=[],m=l?l(u.internal.interaction):u.internal.interaction;for(let _=0;_{const E=tp(_.object),T=tp(S.object);return!E||!T?_.distance-S.distance:T.events.priority-E.events.priority||_.distance-S.distance}).filter(_=>{const S=R0(_);return h.has(S)?!1:(h.add(S),!0)});u.events.filter&&(v=u.events.filter(v,u));for(const _ of v){let S=_.object;for(;S;){var y;(y=S.__r3f)!=null&&y.eventCount&&d.push({..._,eventObject:S}),S=S.parent}}if("pointerId"in c&&u.internal.capturedMap.has(c.pointerId))for(let _ of u.internal.capturedMap.get(c.pointerId).values())h.has(R0(_.intersection))||d.push(_.intersection);return d}function i(c,l,u,h){const d=n.getState();if(c.length){const m={stopped:!1};for(const g of c){const v=tp(g.object)||d,{raycaster:y,pointer:_,camera:S,internal:E}=v,T=new xe(_.x,_.y,0).unproject(S),k=I=>{var U,L;return(U=(L=E.capturedMap.get(I))==null?void 0:L.has(g.eventObject))!=null?U:!1},R=I=>{const U={intersection:g,target:l.target};E.capturedMap.has(I)?E.capturedMap.get(I).set(g.eventObject,U):E.capturedMap.set(I,new Map([[g.eventObject,U]])),l.target.setPointerCapture(I)},M=I=>{const U=E.capturedMap.get(I);U&&bL(E.capturedMap,g.eventObject,U,I)};let O={};for(let I in l){let U=l[I];typeof U!="function"&&(O[I]=U)}let C={...g,...O,pointer:_,intersections:c,stopped:m.stopped,delta:u,unprojectedPoint:T,ray:y.ray,camera:S,stopPropagation(){const I="pointerId"in l&&E.capturedMap.get(l.pointerId);if((!I||I.has(g.eventObject))&&(C.stopped=m.stopped=!0,E.hovered.size&&Array.from(E.hovered.values()).find(U=>U.eventObject===g.eventObject))){const U=c.slice(0,c.indexOf(g));s([...U,g])}},target:{hasPointerCapture:k,setPointerCapture:R,releasePointerCapture:M},currentTarget:{hasPointerCapture:k,setPointerCapture:R,releasePointerCapture:M},nativeEvent:l};if(h(C),m.stopped===!0)break}}return c}function s(c){const{internal:l}=n.getState();for(const u of l.hovered.values())if(!c.length||!c.find(h=>h.object===u.object&&h.index===u.index&&h.instanceId===u.instanceId)){const d=u.eventObject.__r3f,m=d==null?void 0:d.handlers;if(l.hovered.delete(R0(u)),d!=null&&d.eventCount){const g={...u,intersections:c};m.onPointerOut==null||m.onPointerOut(g),m.onPointerLeave==null||m.onPointerLeave(g)}}}function o(c,l){for(let u=0;us([]);case"onLostPointerCapture":return l=>{const{internal:u}=n.getState();"pointerId"in l&&u.capturedMap.has(l.pointerId)&&requestAnimationFrame(()=>{u.capturedMap.has(l.pointerId)&&(u.capturedMap.delete(l.pointerId),s([]))})}}return function(u){const{onPointerMissed:h,internal:d}=n.getState();d.lastEvent.current=u;const m=c==="onPointerMove",g=c==="onClick"||c==="onContextMenu"||c==="onDoubleClick",y=r(u,m?t:void 0),_=g?e(u):0;c==="onPointerDown"&&(d.initialClick=[u.offsetX,u.offsetY],d.initialHits=y.map(E=>E.eventObject)),g&&!y.length&&_<=2&&(o(u,d.interaction),h&&h(u)),m&&s(y);function S(E){const T=E.eventObject,k=T.__r3f,R=k==null?void 0:k.handlers;if(k!=null&&k.eventCount)if(m){if(R.onPointerOver||R.onPointerEnter||R.onPointerOut||R.onPointerLeave){const M=R0(E),O=d.hovered.get(M);O?O.stopped&&E.stopPropagation():(d.hovered.set(M,E),R.onPointerOver==null||R.onPointerOver(E),R.onPointerEnter==null||R.onPointerEnter(E))}R.onPointerMove==null||R.onPointerMove(E)}else{const M=R[c];M?(!g||d.initialHits.includes(T))&&(o(u,d.interaction.filter(O=>!d.initialHits.includes(O))),M(E)):g&&d.initialHits.includes(T)&&o(u,d.interaction.filter(O=>!d.initialHits.includes(O)))}}i(y,u,_,S)}}return{handlePointer:a}}const TL=n=>!!(n!=null&&n.render),wL=ke.createContext(null),Nj=(n,e)=>{const t=fj((a,c)=>{const l=new xe,u=new xe,h=new xe;function d(_=c().camera,S=u,E=c().size){const{width:T,height:k,top:R,left:M}=E,O=T/k;S instanceof xe?h.copy(S):h.set(...S);const C=_.getWorldPosition(l).distanceTo(h);if(yL(_))return{width:T/_.zoom,height:k/_.zoom,top:R,left:M,factor:1,distance:C,aspect:O};{const I=_.fov*Math.PI/180,U=2*Math.tan(I/2)*C,L=U*(T/k);return{width:L,height:U,top:R,left:M,factor:T/L,distance:C,aspect:O}}}let m;const g=_=>a(S=>({performance:{...S.performance,current:_}})),v=new Et;return{set:a,get:c,gl:null,camera:null,raycaster:null,events:{priority:1,enabled:!0,connected:!1},xr:null,scene:null,invalidate:(_=1)=>n(c(),_),advance:(_,S)=>e(_,S,c()),legacy:!1,linear:!1,flat:!1,controls:null,clock:new aj,pointer:v,mouse:v,frameloop:"always",onPointerMissed:void 0,performance:{current:1,min:.5,max:1,debounce:200,regress:()=>{const _=c();m&&clearTimeout(m),_.performance.current!==_.performance.min&&g(_.performance.min),m=setTimeout(()=>g(c().performance.max),_.performance.debounce)}},size:{width:0,height:0,top:0,left:0,updateStyle:!1},viewport:{initialDpr:0,dpr:0,width:0,height:0,top:0,left:0,aspect:0,distance:0,factor:0,getCurrentViewport:d},setEvents:_=>a(S=>({...S,events:{...S.events,..._}})),setSize:(_,S,E,T,k)=>{const R=c().camera,M={width:_,height:S,top:T||0,left:k||0,updateStyle:E};a(O=>({size:M,viewport:{...O.viewport,...d(R,u,M)}}))},setDpr:_=>a(S=>{const E=SL(_);return{viewport:{...S.viewport,dpr:E,initialDpr:S.viewport.initialDpr||E}}}),setFrameloop:(_="always")=>{const S=c().clock;S.stop(),S.elapsedTime=0,_!=="never"&&(S.start(),S.elapsedTime=0),a(()=>({frameloop:_}))},previousRoot:void 0,internal:{active:!1,priority:0,frames:0,lastEvent:ke.createRef(),interaction:[],hovered:new Map,subscribers:[],initialClick:[0,0],initialHits:[],capturedMap:new Map,subscribe:(_,S,E)=>{const T=c().internal;return T.priority=T.priority+(S>0?1:0),T.subscribers.push({ref:_,priority:S,store:E}),T.subscribers=T.subscribers.sort((k,R)=>k.priority-R.priority),()=>{const k=c().internal;k!=null&&k.subscribers&&(k.priority=k.priority-(S>0?1:0),k.subscribers=k.subscribers.filter(R=>R.ref!==_))}}}}}),r=t.getState();let i=r.size,s=r.viewport.dpr,o=r.camera;return t.subscribe(()=>{const{camera:a,size:c,viewport:l,gl:u,set:h}=t.getState();if(c.width!==i.width||c.height!==i.height||l.dpr!==s){var d;i=c,s=l.dpr,Mj(a,c),u.setPixelRatio(l.dpr);const m=(d=c.updateStyle)!=null?d:typeof HTMLCanvasElement<"u"&&u.domElement instanceof HTMLCanvasElement;u.setSize(c.width,c.height,m)}a!==o&&(o=a,h(m=>({viewport:{...m.viewport,...m.viewport.getCurrentViewport(a)}})))}),t.subscribe(a=>n(a)),t};function AL(n,e){const t={callback:n};return e.add(t),()=>void e.delete(t)}let k0,ML=new Set,CL=new Set,Ij=new Set;const Oj=n=>AL(n,ML),Lj=n=>AL(n,CL);function s1(n,e){if(n.size)for(const{callback:t}of n.values())t(e)}function np(n,e){switch(n){case"before":return s1(ML,e);case"after":return s1(CL,e);case"tail":return s1(Ij,e)}}let o1,a1;function c1(n,e,t){let r=e.clock.getDelta();for(e.frameloop==="never"&&typeof n=="number"&&(r=n-e.clock.elapsedTime,e.clock.oldTime=e.clock.elapsedTime,e.clock.elapsedTime=n),o1=e.internal.subscribers,k0=0;k00)&&!((u=s.gl.xr)!=null&&u.isPresenting)&&(r+=c1(l,s))}if(t=!1,np("after",l),r===0)return np("tail",l),e=!1,cancelAnimationFrame(i)}function a(l,u=1){var h;if(!l)return n.forEach(d=>a(d.store.getState(),u));(h=l.gl.xr)!=null&&h.isPresenting||!l.internal.active||l.frameloop==="never"||(u>1?l.internal.frames=Math.min(60,l.internal.frames+u):t?l.internal.frames=2:l.internal.frames=1,e||(e=!0,requestAnimationFrame(o)))}function c(l,u=!0,h,d){if(u&&np("before",l),h)c1(l,h,d);else for(const m of n.values())c1(l,m.store.getState());u&&np("after",l)}return{loop:o,invalidate:a,advance:c}}function Dj(n){const e=ke.useRef(null);return ny(()=>void(e.current=n.current.__r3f),[n]),e}function RL(){const n=ke.useContext(wL);if(!n)throw new Error("R3F: Hooks can only be used within the Canvas component!");return n}function Ma(n=t=>t,e){return RL()(n,e)}function ry(n,e=0){const t=RL(),r=t.getState().internal.subscribe,i=Sj(n);return ny(()=>r(i,e,t),[e,r,t]),null}const C2=new WeakMap;function kL(n,e){return function(t,...r){let i=C2.get(t);return i||(i=new t,C2.set(t,i)),n&&n(i),Promise.all(r.map(s=>new Promise((o,a)=>i.load(s,c=>{c.scene&&Object.assign(c,Tj(c.scene)),o(c)},e,c=>a(new Error(`Could not load ${s}: ${c==null?void 0:c.message}`))))))}}function mm(n,e,t,r){const i=Array.isArray(e)?e:[e],s=pj(kL(t,r),[n,...i],{equal:Un.equ});return Array.isArray(e)?s:s[0]}mm.preload=function(n,e,t){const r=Array.isArray(e)?e:[e];return mj(kL(t),[n,...r])};mm.clear=function(n,e){const t=Array.isArray(e)?e:[e];return gj([n,...t])};const Kf=new Map,{invalidate:R2,advance:k2}=Pj(Kf),{reconciler:J_,applyProps:of}=xj(Kf,Cj),af={objects:"shallow",strict:!1},Uj=(n,e)=>{const t=typeof n=="function"?n(e):n;return TL(t)?t:new QW({powerPreference:"high-performance",canvas:e,antialias:!0,alpha:!0,...n})};function Fj(n,e){const t=typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement;if(e){const{width:r,height:i,top:s,left:o,updateStyle:a=t}=e;return{width:r,height:i,top:s,left:o,updateStyle:a}}else if(typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement&&n.parentElement){const{width:r,height:i,top:s,left:o}=n.parentElement.getBoundingClientRect();return{width:r,height:i,top:s,left:o,updateStyle:t}}else if(typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas)return{width:n.width,height:n.height,top:0,left:0,updateStyle:t};return{width:0,height:0,top:0,left:0}}function Bj(n){const e=Kf.get(n),t=e==null?void 0:e.fiber,r=e==null?void 0:e.store;e&&console.warn("R3F.createRoot should only be called once!");const i=typeof reportError=="function"?reportError:console.error,s=r||Nj(R2,k2),o=t||J_.createContainer(s,Ef.ConcurrentRoot,null,!1,null,"",i,null);e||Kf.set(n,{fiber:o,store:s});let a,c=!1,l;return{configure(u={}){let{gl:h,size:d,scene:m,events:g,onCreated:v,shadows:y=!1,linear:_=!1,flat:S=!1,legacy:E=!1,orthographic:T=!1,frameloop:k="always",dpr:R=[1,2],performance:M,raycaster:O,camera:C,onPointerMissed:I}=u,U=s.getState(),L=U.gl;U.gl||U.set({gl:L=Uj(h,n)});let P=U.raycaster;P||U.set({raycaster:P=new cj});const{params:w,...H}=O||{};if(Un.equ(H,P,af)||of(P,{...H}),Un.equ(w,P.params,af)||of(P,{params:{...P.params,...w}}),!U.camera||U.camera===l&&!Un.equ(l,C,af)){l=C;const K=C instanceof Qv,j=K?C:T?new ey(0,0,0,0,.1,1e3):new Ls(75,0,.1,1e3);K||(j.position.z=5,C&&(of(j,C),("aspect"in C||"left"in C||"right"in C||"bottom"in C||"top"in C)&&(j.manual=!0,j.updateProjectionMatrix())),!U.camera&&!(C!=null&&C.rotation)&&j.lookAt(0,0,0)),U.set({camera:j}),P.camera=j}if(!U.scene){let K;m instanceof Z_?K=m:(K=new Z_,m&&of(K,m)),U.set({scene:mf(K)})}if(!U.xr){var V;const K=(ge,Q)=>{const re=s.getState();re.frameloop!=="never"&&k2(ge,!0,re,Q)},j=()=>{const ge=s.getState();ge.gl.xr.enabled=ge.gl.xr.isPresenting,ge.gl.xr.setAnimationLoop(ge.gl.xr.isPresenting?K:null),ge.gl.xr.isPresenting||R2(ge)},Y={connect(){const ge=s.getState().gl;ge.xr.addEventListener("sessionstart",j),ge.xr.addEventListener("sessionend",j)},disconnect(){const ge=s.getState().gl;ge.xr.removeEventListener("sessionstart",j),ge.xr.removeEventListener("sessionend",j)}};typeof((V=L.xr)==null?void 0:V.addEventListener)=="function"&&Y.connect(),U.set({xr:Y})}if(L.shadowMap){const K=L.shadowMap.enabled,j=L.shadowMap.type;if(L.shadowMap.enabled=!!y,Un.boo(y))L.shadowMap.type=l_;else if(Un.str(y)){var B;const Y={basic:Vz,percentage:FT,soft:l_,variance:ga};L.shadowMap.type=(B=Y[y])!=null?B:l_}else Un.obj(y)&&Object.assign(L.shadowMap,y);(K!==L.shadowMap.enabled||j!==L.shadowMap.type)&&(L.shadowMap.needsUpdate=!0)}const z=vL();z&&("enabled"in z?z.enabled=!E:"legacyMode"in z&&(z.legacyMode=E)),c||of(L,{outputEncoding:_?3e3:3001,toneMapping:S?Ra:UO}),U.legacy!==E&&U.set(()=>({legacy:E})),U.linear!==_&&U.set(()=>({linear:_})),U.flat!==S&&U.set(()=>({flat:S})),h&&!Un.fun(h)&&!TL(h)&&!Un.equ(h,L,af)&&of(L,h),g&&!U.events.handlers&&U.set({events:g(s)});const W=Fj(n,d);return Un.equ(W,U.size,af)||U.setSize(W.width,W.height,W.updateStyle,W.top,W.left),R&&U.viewport.dpr!==SL(R)&&U.setDpr(R),U.frameloop!==k&&U.setFrameloop(k),U.onPointerMissed||U.set({onPointerMissed:I}),M&&!Un.equ(M,U.performance,af)&&U.set(K=>({performance:{...K.performance,...M}})),a=v,c=!0,this},render(u){return c||this.configure(),J_.updateContainer(ve.jsx(zj,{store:s,children:u,onCreated:a,rootElement:n}),o,null,()=>{}),s},unmount(){Vj(n)}}}function zj({store:n,children:e,onCreated:t,rootElement:r}){return ny(()=>{const i=n.getState();i.set(s=>({internal:{...s.internal,active:!0}})),t&&t(i),n.getState().events.connected||i.events.connect==null||i.events.connect(r)},[]),ve.jsx(wL.Provider,{value:n,children:e})}function Vj(n,e){const t=Kf.get(n),r=t==null?void 0:t.fiber;if(r){const i=t==null?void 0:t.store.getState();i&&(i.internal.active=!1),J_.updateContainer(null,r,null,()=>{i&&setTimeout(()=>{try{var s,o,a,c;i.events.disconnect==null||i.events.disconnect(),(s=i.gl)==null||(o=s.renderLists)==null||o.dispose==null||o.dispose(),(a=i.gl)==null||a.forceContextLoss==null||a.forceContextLoss(),(c=i.gl)!=null&&c.xr&&i.xr.disconnect(),wj(i),Kf.delete(n)}catch{}},500)})}}J_.injectIntoDevTools({bundleType:0,rendererPackageName:"@react-three/fiber",version:ke.version});const l1={onClick:["click",!1],onContextMenu:["contextmenu",!1],onDoubleClick:["dblclick",!1],onWheel:["wheel",!0],onPointerDown:["pointerdown",!0],onPointerUp:["pointerup",!0],onPointerLeave:["pointerleave",!0],onPointerMove:["pointermove",!0],onPointerCancel:["pointercancel",!0],onLostPointerCapture:["lostpointercapture",!0]};function Hj(n){const{handlePointer:e}=kj(n);return{priority:1,enabled:!0,compute(t,r,i){r.pointer.set(t.offsetX/r.size.width*2-1,-(t.offsetY/r.size.height)*2+1),r.raycaster.setFromCamera(r.pointer,r.camera)},connected:void 0,handlers:Object.keys(l1).reduce((t,r)=>({...t,[r]:e(r)}),{}),update:()=>{var t;const{events:r,internal:i}=n.getState();(t=i.lastEvent)!=null&&t.current&&r.handlers&&r.handlers.onPointerMove(i.lastEvent.current)},connect:t=>{var r;const{set:i,events:s}=n.getState();s.disconnect==null||s.disconnect(),i(o=>({events:{...o.events,connected:t}})),Object.entries((r=s.handlers)!=null?r:[]).forEach(([o,a])=>{const[c,l]=l1[o];t.addEventListener(c,a,{passive:l})})},disconnect:()=>{const{set:t,events:r}=n.getState();if(r.connected){var i;Object.entries((i=r.handlers)!=null?i:[]).forEach(([s,o])=>{if(r&&r.connected instanceof HTMLElement){const[a]=l1[s];r.connected.removeEventListener(a,o)}}),t(s=>({events:{...s.events,connected:void 0}}))}}}}var QT={exports:{}};function NL(n,e=100,t={}){if(typeof n!="function")throw new TypeError(`Expected the first parameter to be a function, got \`${typeof n}\`.`);if(e<0)throw new RangeError("`wait` must not be negative.");const{immediate:r}=typeof t=="boolean"?{immediate:t}:t;let i,s,o,a,c;function l(){const d=i,m=s;return i=void 0,s=void 0,c=n.apply(d,m),c}function u(){const d=Date.now()-a;d=0?o=setTimeout(u,e-d):(o=void 0,r||(c=l()))}const h=function(...d){if(i&&this!==i&&Object.getPrototypeOf(this)===Object.getPrototypeOf(i))throw new Error("Debounced method called with different contexts of the same prototype.");i=this,s=d,a=Date.now();const m=r&&!o;return o||(o=setTimeout(u,e)),m&&(c=l()),c};return Object.defineProperty(h,"isPending",{get(){return o!==void 0}}),h.clear=()=>{o&&(clearTimeout(o),o=void 0)},h.flush=()=>{o&&h.trigger()},h.trigger=()=>{c=l(),h.clear()},h}QT.exports.debounce=NL;QT.exports=NL;var Gj=QT.exports;const Wj=$a(Gj);var IL={exports:{}};(function(n,e){(function(t,r){n.exports=r()})(No,function(){return t.importState=function(i){var s=new t;return s.importState(i),s},t;function t(){return function(i){var s=0,o=0,a=0,c=1;i.length==0&&(i=[+new Date]);var l=r();s=l(" "),o=l(" "),a=l(" ");for(var u=0;u>>0,c-=i,c*=i,i=c>>>0,c-=i,i+=c*4294967296}return(i>>>0)*23283064365386963e-26};return s.version="Mash 0.9",s}})})(IL);var jj=IL.exports;const $j=$a(jj);new Et;new Et;function Nn(n,e,t){return Math.max(e,Math.min(t,n))}const qj=$j("089fad0j9awfem09wavefc09uwaef");function N2(n){return 2*Math.floor(n/2)}function Xj(n,e){return Math.round(n/e)*e}function Kj(){return qj()}function gp(n,e){const t=Math.min(n,e),i=Math.max(n,e)-t+1;return t+Math.floor(Kj()*i)}/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017-2022 Joachim Wester + * MIT licensed + */var Yj=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Zj=Object.prototype.hasOwnProperty;function qE(n,e){return Zj.call(n,e)}function XE(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t=48&&r<=57){e++;continue}return!1}return!0}function Nu(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}function OL(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function YE(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(l[m]===void 0?d=c.slice(0,u).join("/"):u==h-1&&(d=e.path),d!==void 0&&g(e,0,n,d)),u++,Array.isArray(l)){if(m==="-")m=l.length;else{if(t&&!KE(m))throw new sr("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);KE(m)&&(m=~~m)}if(u>=h){if(t&&e.op==="add"&&m>l.length)throw new sr("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var o=Qj[e.op].call(e,l,m,n);if(o.test===!1)throw new sr("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return o}}else if(u>=h){var o=bf[e.op].call(e,l,m,n);if(o.test===!1)throw new sr("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return o}if(l=l[m],t&&u0)throw new sr('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new sr("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new sr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&YE(n.value))throw new sr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new sr("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new sr("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var o={op:"_get",path:n.from,value:void 0},a=LL([o],t);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new sr("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new sr("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}function LL(n,e,t){try{if(!Array.isArray(n))throw new sr("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)iy(Gi(e),Gi(n),t||!0);else{t=t||ev;for(var r=0;r0&&(n.patches=[],n.callback&&n.callback(r)),r}function nw(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=XE(e),o=XE(n),a=!1,c=o.length-1;c>=0;c--){var l=o[c],u=n[l];if(qE(e,l)&&!(e[l]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var h=e[l];typeof u=="object"&&u!=null&&typeof h=="object"&&h!=null&&Array.isArray(u)===Array.isArray(h)?nw(u,h,t,r+"/"+Nu(l),i):u!==h&&(i&&t.push({op:"test",path:r+"/"+Nu(l),value:Gi(u)}),t.push({op:"replace",path:r+"/"+Nu(l),value:Gi(h)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+Nu(l),value:Gi(u)}),t.push({op:"remove",path:r+"/"+Nu(l)}),a=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}))}if(!(!a&&s.length==o.length))for(var c=0;ch.length?u:h})}function i(l){return l.reduce(function(u,h){return u.lengthcrypto.getRandomValues(new Uint8Array(n)),S9=(n,e,t)=>{let r=(2<{let o="";for(;;){let a=t(i),c=i;for(;c--;)if(o+=n[a[c]&r]||"",o.length===s)return o}}},FL=(n,e=21)=>S9(n,e,x9),E9=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n));for(;n--;)e+=y9[t[n]&63];return e};var BL="abcdefghijklmnopqrstuvwxyz",zL="ABCDEFGHIJKLMNOPQRSTUVWXYZ",VL="0123456789",b9="346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz",T9="6789BCDFGHJKLMNPQRTWbcdfghjkmnpqrtwz";const w9=VL,A9=BL,M9=zL;var C9=w9+A9+M9,JE={lowercase:BL,uppercase:zL,numbers:VL,nolookalikes:b9,nolookalikesSafe:T9,alphanumeric:C9};function gr(){return`sid_${E9(12).replaceAll("-",".")}`}const R9=FL(JE.numbers,4),k9=FL(`${JE.numbers}${JE.lowercase}`,16);function HL(){return`pid_${R9()}_${k9()}`}function GL(n){return(n==null?void 0:n.startsWith("pid_"))??!1}function N9(){return v9({capitalize:!1,adjectiveCount:1})}var wn=(n=>(n[n.BLACK=0]="BLACK",n[n.DKBLUE=1]="DKBLUE",n[n.DKGREEN=2]="DKGREEN",n[n.DKCYAN=3]="DKCYAN",n[n.DKRED=4]="DKRED",n[n.DKPURPLE=5]="DKPURPLE",n[n.DKYELLOW=6]="DKYELLOW",n[n.LTGRAY=7]="LTGRAY",n[n.DKGRAY=8]="DKGRAY",n[n.BLUE=9]="BLUE",n[n.GREEN=10]="GREEN",n[n.CYAN=11]="CYAN",n[n.RED=12]="RED",n[n.PURPLE=13]="PURPLE",n[n.YELLOW=14]="YELLOW",n[n.WHITE=15]="WHITE",n[n.ONBLACK=16]="ONBLACK",n[n.ONDKBLUE=17]="ONDKBLUE",n[n.ONDKGREEN=18]="ONDKGREEN",n[n.ONDKCYAN=19]="ONDKCYAN",n[n.ONDKRED=20]="ONDKRED",n[n.ONDKPURPLE=21]="ONDKPURPLE",n[n.ONDKYELLOW=22]="ONDKYELLOW",n[n.ONLTGRAY=23]="ONLTGRAY",n[n.ONDKGRAY=24]="ONDKGRAY",n[n.ONBLUE=25]="ONBLUE",n[n.ONGREEN=26]="ONGREEN",n[n.ONCYAN=27]="ONCYAN",n[n.ONRED=28]="ONRED",n[n.ONPURPLE=29]="ONPURPLE",n[n.ONYELLOW=30]="ONYELLOW",n[n.ONWHITE=31]="ONWHITE",n[n.ONCLEAR=32]="ONCLEAR",n[n.ONSHADOW=33]="ONSHADOW",n[n.ONBORROW=34]="ONBORROW",n))(wn||{}),Gn=(n=>(n[n.ISWALK=0]="ISWALK",n[n.ISSOLID=1]="ISSOLID",n[n.ISSWIM=2]="ISSWIM",n[n.ISBULLET=3]="ISBULLET",n))(Gn||{}),tv=(n=>(n[n.ISTERRAIN=0]="ISTERRAIN",n[n.ISOBJECT=1]="ISOBJECT",n))(tv||{}),st=(n=>(n[n.IDLE=0]="IDLE",n[n.NORTH=1]="NORTH",n[n.SOUTH=2]="SOUTH",n[n.WEST=3]="WEST",n[n.EAST=4]="EAST",n[n.BY=5]="BY",n[n.AT=6]="AT",n[n.FLOW=7]="FLOW",n[n.SEEK=8]="SEEK",n[n.RNDNS=9]="RNDNS",n[n.RNDNE=10]="RNDNE",n[n.RND=11]="RND",n[n.CW=12]="CW",n[n.CCW=13]="CCW",n[n.OPP=14]="OPP",n[n.RNDP=15]="RNDP",n))(st||{}),pt=(n=>(n[n.LOADER=0]="LOADER",n[n.BOARD=1]="BOARD",n[n.OBJECT=2]="OBJECT",n[n.TERRAIN=3]="TERRAIN",n[n.CHARSET=4]="CHARSET",n[n.PALETTE=5]="PALETTE",n[n.CONST=6]="CONST",n[n.RANGE=7]="RANGE",n[n.SELECT=8]="SELECT",n[n.NUMBER=9]="NUMBER",n[n.TEXT=10]="TEXT",n[n.LINK=11]="LINK",n[n.HOTKEY=12]="HOTKEY",n[n.SCROLL=13]="SCROLL",n[n.COPYIT=14]="COPYIT",n))(pt||{});function Kt(n){return n.toLowerCase().trim()}function I9(n,e,t,r){return{id:gr(),target:n,sender:e,data:t,player:r}}function WL(n){const[e,...t]=n.split(":");return{target:e,path:t.join(":")}}function mh(n,e,t){const r=gr(),i=Kt(n),s=e.map(Kt),o={id(){return r},name(){return n},topics(){return e},emit(a,c,l){Pt.emit(a,r,c,l)},reply(a,c,l,u){o.emit(`${a.sender}:${c}`,l,u)},handle(a){const{target:c,path:l}=WL(a.target),u=Kt(c);s.findIndex(h=>h==="all"||h===u)!==-1&&t(a),(r===c||u==="all"||i===u)&&t({...a,target:l})}};return Pt.connect(o),o}const u1=new Set,Pt={emit(n,e,t,r){Pt.invoke(I9(n,e,t,r))},invoke(n){u1.forEach(e=>e.handle(n))},connect(n){u1.add(n)},disconnect(n){u1.delete(n)}};function An(n,e,t,r){const i=r??"";return Pt.emit(`error:${e}`,n,t,i),j9(n,t,i)}function O9(n,e){Pt.emit("gadgetserver:desync",n,void 0,e)}function L9(n,e){Pt.emit("gadgetserver:clearscroll",n,void 0,e)}function jL(n,e,t){Pt.emit("peer:create",n,e,t)}function $L(n,e){Pt.emit("peer:joincode",n,void 0,e)}function P9(n,e){Pt.emit("init",n,void 0,e)}function D9(n,e){Pt.emit("register:ready",n,void 0,e)}function U9(n,e){Pt.emit("register:ackbooks",n,!0,e)}function F9(n,e){Pt.emit("register:dev",n,void 0,e)}function B9(n,e){Pt.emit("register:share",n,void 0,e)}function z9(n,e){Pt.emit("register:refresh",n,void 0,e)}function V9(n,e){Pt.emit("register:nuke",n,void 0,e)}function H9(n,e,t){Pt.emit("synth:tts",n,[e,t])}function G9(n,e,t){Pt.emit("synth:play",n,[e,t])}function h1(n,e,t,r){Pt.emit("synth:voice",n,[e,t,r])}function W9(n,e,t,r,i){Pt.emit("synth:voicefx",n,[e,t,r,i])}function lo(n,...e){return Pt.emit("tape:info",n,e),!0}function j9(n,...e){return Pt.emit("tape:error",n,e),!1}function qL(n,e){Pt.emit("tape:terminal:open",n,void 0,e)}function iw(n,e){Pt.emit("tape:terminal:close",n,void 0,e)}function XL(n,e,t){Pt.emit("tape:terminal:inclayout",n,e,t)}function O2(n,e){Pt.emit("tape:crash",n,void 0,e)}function $9(n,e,t,r,i,s){Pt.emit("tape:editor:open",n,[e,t,r,i],s)}function q9(n,e){Pt.emit("tape:editor:close",n,void 0,e)}function X9(n,e,t,r){Pt.emit("vm:books",n,[e,t],r)}function K9(n,e){Pt.emit("vm:login",n,void 0,e)}function Y9(n,e){Pt.emit("vm:endgame",n,void 0,e)}function Z9(n,e){Pt.emit("vm:doot",n,void 0,e)}function J9(n,e,t,r){Pt.emit("vm:input",n,[e,t],r)}function KL(n,e){return`${n}${e}`}function Q9(n,e,t,r){Pt.emit("vm:codewatch",n,[e,t],r)}function e$(n,e,t,r){Pt.emit("vm:coderelease",n,[e,t],r)}function sy(n,e,t){Pt.emit("vm:cli",n,e,t)}function YL(n,e,t){Pt.emit("vm:flush",n,e,t)}function QE(n,e,t){Pt.emit("vm:loadfile",n,e,t)}function sw(n){return new Promise((e,t)=>{n.oncomplete=n.onsuccess=()=>e(n.result),n.onabort=n.onerror=()=>t(n.error)})}function t$(n,e){const t=indexedDB.open(n);t.onupgradeneeded=()=>t.result.createObjectStore(e);const r=sw(t);return(i,s)=>r.then(o=>s(o.transaction(e,i).objectStore(e)))}let f1;function ZL(){return f1||(f1=t$("keyval-store","keyval")),f1}function n$(n,e=ZL()){return e("readonly",t=>sw(t.get(n)))}function r$(n,e,t=ZL()){return t("readwrite",r=>new Promise((i,s)=>{r.get(n).onsuccess=function(){try{r.put(e(this.result),n),i(sw(r.transaction))}catch(o){s(o)}}}))}function _a(n,e){function t(r){console.error(r),An(n,"crash",r.message)}e().catch(t)}const i$=66.666,JL=Math.round(1e3/i$),s$=3;function mc(n){return new Promise(e=>setTimeout(e,n))}async function eb(n){const e=new FormData;e.append("url",n);const t=new Request("https://bytes.zed.cafe",{method:"POST",body:e});return await(await fetch(t)).text()}function L2(){return location.href.includes("/join/")}function o$(){return location.href.includes("/locked/")}function a$(n){return Z(n)&&typeof n=="object"&&Bt(n.id)&&Bt(n.target)&&Bt(n.sender)}function QL(n){const e=new Set;function t(s){a$(s)&&s.target!=="tick"&&s.target!=="tock"&&e.has(s.id)===!1&&(e.add(s.id),Pt.invoke(s))}const r=mh("forward",["all"],s=>{e.has(s.id)||(e.add(s.id),n(s))});function i(){Pt.disconnect(r)}return{forward:t,disconnect:i}}function c$(n){return new Worker("/assets/simspace-_1023Pw3.js",{name:n==null?void 0:n.name})}function l$(n){return new Worker("/assets/stubspace-Mt81ZBb1.js",{name:n==null?void 0:n.name})}let N0;function u$(n=!1){if(!Z(N0)){N0=n?new l$:new c$;const{forward:e}=QL(t=>N0.postMessage(t));N0.addEventListener("message",t=>e(t.data))}}var Du=(n=>(n[n.Border=-1]="Border",n[n.Data=0]="Data",n[n.Function=1]="Function",n[n.Position=2]="Position",n[n.Timing=3]="Timing",n[n.Alignment=4]="Alignment",n))(Du||{}),h$=Object.defineProperty,f$=(n,e,t)=>e in n?h$(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,I0=(n,e,t)=>(f$(n,typeof e!="symbol"?e+"":e,t),t);const d$=[0,1],eP=[1,0],tP=[2,3],nP=[3,2],p$={L:d$,M:eP,Q:tP,H:nP},m$=/^[0-9]*$/,g$=/^[A-Z0-9 $%*+.\/:-]*$/,d1="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",ow=1,aw=40,P2=3,_$=3,O0=40,v$=10,rP=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],iP=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]];class y${constructor(e,t,r,i){if(this.version=e,this.ecc=t,I0(this,"size"),I0(this,"mask"),I0(this,"modules",[]),I0(this,"types",[]),eaw)throw new RangeError("Version value out of range");if(i<-1||i>7)throw new RangeError("Mask value out of range");this.size=e*4+17;const s=Array.from({length:this.size},()=>!1);for(let a=0;a0));this.drawFunctionPatterns();const o=this.addEccAndInterleave(r);if(this.drawCodewords(o),i===-1){let a=1e9;for(let c=0;c<8;c++){this.applyMask(c),this.drawFormatBits(c);const l=this.getPenaltyScore();l=0&&e=0&&t>>9)*1335;const i=(t<<10|r)^21522;for(let s=0;s<=5;s++)this.setFunctionModule(8,s,gc(i,s));this.setFunctionModule(8,7,gc(i,6)),this.setFunctionModule(8,8,gc(i,7)),this.setFunctionModule(7,8,gc(i,8));for(let s=9;s<15;s++)this.setFunctionModule(14-s,8,gc(i,s));for(let s=0;s<8;s++)this.setFunctionModule(this.size-1-s,8,gc(i,s));for(let s=8;s<15;s++)this.setFunctionModule(8,this.size-15+s,gc(i,s));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let r=0;r<12;r++)e=e<<1^(e>>>11)*7973;const t=this.version<<12|e;for(let r=0;r<18;r++){const i=gc(t,r),s=this.size-11+r%3,o=Math.floor(r/3);this.setFunctionModule(s,o,i),this.setFunctionModule(o,s,i)}}drawFinderPattern(e,t){for(let r=-4;r<=4;r++)for(let i=-4;i<=4;i++){const s=Math.max(Math.abs(i),Math.abs(r)),o=e+i,a=t+r;o>=0&&o=0&&a{(d!==c-s||g>=a)&&h.push(m[d])});return h}drawCodewords(e){if(e.length!==Math.floor(tb(this.version)/8))throw new RangeError("Invalid argument");let t=0;for(let r=this.size-1;r>=1;r-=2){r===6&&(r=5);for(let i=0;i>>3],7-(t&7)),t++)}}}applyMask(e){if(e<0||e>7)throw new RangeError("Mask value out of range");for(let t=0;t5&&e++):(this.finderPenaltyAddHistory(a,c),o||(e+=this.finderPenaltyCountPatterns(c)*O0),o=this.modules[s][l],a=1);e+=this.finderPenaltyTerminateAndCount(o,a,c)*O0}for(let s=0;s5&&e++):(this.finderPenaltyAddHistory(a,c),o||(e+=this.finderPenaltyCountPatterns(c)*O0),o=this.modules[l][s],a=1);e+=this.finderPenaltyTerminateAndCount(o,a,c)*O0}for(let s=0;so+(a?1:0),t);const r=this.size*this.size,i=Math.ceil(Math.abs(t*20-r*10)/r)-1;return e+=i*v$,e}getAlignmentPatternPositions(){if(this.version===1)return[];{const e=Math.floor(this.version/7)+2,t=this.version===32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,r=[6];for(let i=this.size-7;r.length0&&e[2]===t&&e[3]===t*3&&e[4]===t&&e[5]===t;return(r&&e[0]>=t*4&&e[6]>=t?1:0)+(r&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,r){return e&&(this.finderPenaltyAddHistory(t,r),t=0),t+=this.size,this.finderPenaltyAddHistory(t,r),this.finderPenaltyCountPatterns(r)}finderPenaltyAddHistory(e,t){t[0]===0&&(e+=this.size),t.pop(),t.unshift(e)}}function Ac(n,e,t){if(e<0||e>31||n>>>e)throw new RangeError("Value out of range");for(let r=e-1;r>=0;r--)t.push(n>>>r&1)}function gc(n,e){return(n>>>e&1)!==0}class cw{constructor(e,t,r){if(this.mode=e,this.numChars=t,this.bitData=r,t<0)throw new RangeError("Invalid argument");this.bitData=r.slice()}getData(){return this.bitData.slice()}}const x$=[1,10,12,14],S$=[2,9,11,13],E$=[4,8,16,16];function sP(n,e){return n[Math.floor((e+7)/17)+1]}function oP(n){const e=[];for(const t of n)Ac(t,8,e);return new cw(E$,n.length,e)}function b$(n){if(!aP(n))throw new RangeError("String contains non-numeric characters");const e=[];for(let t=0;t=1<aw)throw new RangeError("Version number out of range");let e=(16*n+128)*n+64;if(n>=2){const t=Math.floor(n/7)+2;e-=(25*t-10)*t-55,n>=7&&(e-=36)}return e}function v_(n,e){return Math.floor(tb(n)/8)-rP[e[0]][n]*iP[e[0]][n]}function C$(n){if(n<1||n>255)throw new RangeError("Degree out of range");const e=[];for(let r=0;r0);for(const r of n){const i=r^t.shift();t.push(0),e.forEach((s,o)=>t[o]^=nb(s,i))}return t}function nb(n,e){if(n>>>8||e>>>8)throw new RangeError("Byte out of range");let t=0;for(let r=7;r>=0;r--)t=t<<1^(t>>>7)*285,t^=(e>>>r&1)*n;return t}function k$(n,e,t=1,r=40,i=-1,s=!0){if(!(ow<=t&&t<=r&&r<=aw)||i<-1||i>7)throw new RangeError("Invalid value");let o,a;for(o=t;;o++){const h=v_(o,e)*8,d=A$(n,o);if(d<=h){a=d;break}if(o>=r)throw new RangeError("Data too long")}for(const h of[eP,tP,nP])s&&a<=v_(o,h)*8&&(e=h);const c=[];for(const h of n){Ac(h.mode[0],4,c),Ac(h.numChars,sP(h.mode,o),c);for(const d of h.getData())c.push(d)}const l=v_(o,e)*8;Ac(0,Math.min(4,l-c.length),c),Ac(0,(8-c.length%8)%8,c);for(let h=236;c.length0);return c.forEach((h,d)=>u[d>>>3]|=h<<7-(d&7)),new y$(o,e,u,i)}function N$(n,e){var h;const{ecc:t="L",boostEcc:r=!1,minVersion:i=1,maxVersion:s=40,maskPattern:o=-1,border:a=1}=e||{},c=typeof n=="string"?w$(n):Array.isArray(n)?[oP(n)]:void 0;if(!c)throw new Error(`uqr only supports encoding string and binary data, but got: ${typeof n}`);const l=k$(c,p$[t],i,s,o,r),u=I$({version:l.version,maskPattern:l.mask,size:l.size,data:l.modules,types:l.types},a);return e!=null&&e.invert&&(u.data=u.data.map(d=>d.map(m=>!m))),(h=e==null?void 0:e.onEncoded)==null||h.call(e,u),u}function I$(n,e=1){if(!e)return n;const{size:t}=n,r=t+e*2;n.size=r,n.data.forEach(s=>{for(let o=0;o!1)),n.data.push(Array.from({length:r},o=>!1));const i=Du.Border;n.types.forEach(s=>{for(let o=0;oi)),n.types.push(Array.from({length:r},o=>i));return n}function O$(n,e,t,r=!1){return e<0||t<0||e>=n.length||t>=n.length?r:n[t][e]}function L$(n,e={}){const t={WHITE_ALL:"█",WHITE_BLACK:"▀",BLACK_WHITE:"▄",BLACK_ALL:" "},r=N$(n,e),i=!1,s=!0,o=(l,u)=>O$(r.data,l,u,!0),a=[];let c="";for(let l=0;l`$${i[a.charCodeAt(0)]}`).join("");un(n,o)}un(n,`!copyit ${e};${t}`)}function Fp(){return Fp=Object.assign||function(n){for(var e=1;e0}function sb(n){y_++;try{return n()}finally{y_--,y_===0&&H$()}}var ob=!1;function fP(){return ob}function dP(n){ob=!0;try{n()}finally{ob=!1}}function V$(n){return function(){return dP(n)}}var ab=[];function H$(){var n=[].concat(ab);ab=[],pP(n)}function pP(n){var e=new Set;n.forEach(function(t){var r;(t.type==="add"||t.type==="delete")&&t.observable[Gr].connections.iterate.forEach(function(i){e.add(i)}),(r=t.observable[Gr].connections.byKey.get(t.key))==null||r.forEach(function(i){e.add(i)})}),e.forEach(function(t){t.trigger()})}function L0(n){if(hP()){ab.push(n);return}pP([n])}function U2(n,e){if(n.type==="iterate")n.observable[Gr].connections.iterate.add(e);else{var t=n.observable[Gr].connections.byKey.get(n.key);t||(t=new Set,n.observable[Gr].connections.byKey.set(n.key,t)),t.add(e)}}function P0(n,e){if(!fP()){var t=uP();t&&(U2(n,t),t.registerConnection(n)),e&&(U2(n,e),e.registerConnection(n))}}var hw=Symbol("$skipreactive"),Gr=Symbol("$reactive"),mo=Symbol("$reactiveproxy");function gm(n,e){return!!(n&&n[mo]&&n[mo].implicitObserver===e)}function fw(n){return n[hw]=!0,n}function mP(n){return!!(n&&!gm(n)&&n[Gr])}function cb(n,e,t){if(t===void 0&&(t=!1),n[hw]||gm(n,e))return n;var r=G$(n,t);if(!e)return r;var i=r[Gr].proxiesWithImplicitObserver.get(e);if(!i){var s={implicitObserver:e};Object.setPrototypeOf(s,gP),i=new Proxy(r[Gr].raw,s),r[Gr].proxiesWithImplicitObserver.set(e,i)}return i}var Zf=cb;function G$(n,e){if(e===void 0&&(e=!1),gm(n))return n;if(mP(n))return n[Gr].proxy;if(n[Gr]||n[mo])throw new Error("unexpected");var t={connections:{iterate:new Set,byKey:new Map},proxy:{},raw:n,proxiesWithImplicitObserver:new Map,shallow:e};Object.defineProperty(n,Gr,{enumerable:!1,writable:!0,configurable:!0,value:t});var r=new Proxy(n,gP);return t.proxy=r,r}var gP={has:function(e,t){var r=Reflect.has(e,t);return typeof t=="symbol"||P0({observable:e,key:t,type:"has"},this.implicitObserver),r},get:function(e,t,r){if(t===mo)return{implicitObserver:this.implicitObserver};var i=Reflect.get(e,t,r);if(typeof t=="symbol")return t.toString()==="Symbol($reactiveproxy)"&&console.error("warning, Symbol($reactiveproxy) passed, but does not match $reactiveproxy. Multiple Reactive libraries loaded?"),i;if(t==="length"&&Array.isArray(e)?P0({observable:e,type:"iterate"},this.implicitObserver):P0({observable:e,key:t,type:"get"},this.implicitObserver),mP(i))return cb(i,this.implicitObserver);if(e[Gr].shallow)return i;if(typeof i=="object"&&i!==null&&!gm(i,this.implicitObserver)&&!Object.isFrozen(i)){var s=Reflect.getOwnPropertyDescriptor(e,t);if((!s||!(s.writable===!1&&s.configurable===!1))&&(lP()||this.implicitObserver))return cb(i,this.implicitObserver)}return i},ownKeys:function(e){return P0({observable:e,type:"iterate"},this.implicitObserver),Reflect.ownKeys(e)},set:function(e,t,r,i){return sb(function(){if(typeof t=="symbol")return Reflect.set(e,t,r,i);var s=Object.hasOwnProperty.call(e,t),o=Reflect.get(e,t,i),a=Reflect.set(e,t,r,i);if(!s)L0({observable:e,key:t,value:r,type:"add"});else if(r!==o)if(t==="length"&&Array.isArray(e)){if(!(onew Map,lb=n=>{const e=Do();return n.forEach((t,r)=>{e.set(r,t)}),e},eu=(n,e,t)=>{let r=n.get(e);return r===void 0&&n.set(e,r=t()),r},X$=(n,e)=>{const t=[];for(const[r,i]of n)t.push(e(i,r));return t},K$=(n,e)=>{for(const[t,r]of n)if(e(r,t))return!0;return!1},Jf=()=>new Set,p1=n=>n[n.length-1],Y$=(n,e)=>{for(let t=0;t{this.off(e,r),t(...i)};this.on(e,r)}off(e,t){const r=this._observers.get(e);r!==void 0&&(r.delete(t),r.size===0&&this._observers.delete(e))}emit(e,t){return Hl((this._observers.get(e)||Do()).values()).forEach(r=>r(...t))}destroy(){this._observers=Do()}}const Gl=Math.floor,x_=Math.abs,vP=(n,e)=>nn>e?n:e,yP=n=>n!==0?n<0:1/n<0,F2=1,B2=2,m1=4,g1=8,Bp=32,Pc=64,Vs=128,ay=31,ub=63,Xu=127,Q$=2147483647,xP=Number.MAX_SAFE_INTEGER,e7=Number.isInteger||(n=>typeof n=="number"&&isFinite(n)&&Gl(n)===n),t7=n=>n.toLowerCase(),n7=/^\s*/g,r7=n=>n.replace(n7,""),i7=/([A-Z])/g,z2=(n,e)=>r7(n.replace(i7,t=>`${e}${t7(t)}`)),s7=n=>{const e=unescape(encodeURIComponent(n)),t=e.length,r=new Uint8Array(t);for(let i=0;izp.encode(n),a7=zp?o7:s7;let Cp=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Cp&&Cp.decode(new Uint8Array).length===1&&(Cp=null);class _m{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Ll=()=>new _m,c7=n=>{let e=n.cpos;for(let t=0;t{const e=new Uint8Array(c7(n));let t=0;for(let r=0;r{const t=n.cbuf.length;t-n.cpos{const t=n.cbuf.length;n.cpos===t&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(t*2),n.cpos=0),n.cbuf[n.cpos++]=e},hb=ii,jt=(n,e)=>{for(;e>Xu;)ii(n,Vs|Xu&e),e=Gl(e/128);ii(n,Xu&e)},dw=(n,e)=>{const t=yP(e);for(t&&(e=-e),ii(n,(e>ub?Vs:0)|(t?Pc:0)|ub&e),e=Gl(e/64);e>0;)ii(n,(e>Xu?Vs:0)|Xu&e),e=Gl(e/128)},fb=new Uint8Array(3e4),u7=fb.length/3,h7=(n,e)=>{if(e.length{const t=unescape(encodeURIComponent(e)),r=t.length;jt(n,r);for(let i=0;i{const t=n.cbuf.length,r=n.cpos,i=vP(t-r,e.length),s=e.length-i;n.cbuf.set(e.subarray(0,i),r),n.cpos+=i,s>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(gh(t*2,s)),n.cbuf.set(e.subarray(i)),n.cpos=s)},bi=(n,e)=>{jt(n,e.byteLength),cy(n,e)},pw=(n,e)=>{l7(n,e);const t=new DataView(n.cbuf.buffer,n.cpos,e);return n.cpos+=e,t},d7=(n,e)=>pw(n,4).setFloat32(0,e,!1),p7=(n,e)=>pw(n,8).setFloat64(0,e,!1),m7=(n,e)=>pw(n,8).setBigInt64(0,e,!1),V2=new DataView(new ArrayBuffer(4)),g7=n=>(V2.setFloat32(0,n),V2.getFloat32(0)===n),Vp=(n,e)=>{switch(typeof e){case"string":ii(n,119),Lf(n,e);break;case"number":e7(e)&&x_(e)<=Q$?(ii(n,125),dw(n,e)):g7(e)?(ii(n,124),d7(n,e)):(ii(n,123),p7(n,e));break;case"bigint":ii(n,122),m7(n,e);break;case"object":if(e===null)ii(n,126);else if(Z$(e)){ii(n,117),jt(n,e.length);for(let t=0;t0&&jt(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const G2=n=>{n.count>0&&(dw(n.encoder,n.count===1?n.s:-n.s),n.count>1&&jt(n.encoder,n.count-2))};class S_{constructor(){this.encoder=new _m,this.s=0,this.count=0}write(e){this.s===e?this.count++:(G2(this),this.count=1,this.s=e)}toUint8Array(){return G2(this),Oo(this.encoder)}}const W2=n=>{if(n.count>0){const e=n.diff*2+(n.count===1?0:1);dw(n.encoder,e),n.count>1&&jt(n.encoder,n.count-2)}};class _1{constructor(){this.encoder=new _m,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(W2(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return W2(this),Oo(this.encoder)}}class _7{constructor(){this.sarr=[],this.s="",this.lensE=new S_}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new _m;return this.sarr.push(this.s),this.s="",Lf(e,this.sarr.join("")),cy(e,this.lensE.toUint8Array()),Oo(e)}}const Wl=n=>new Error(n),ka=()=>{throw Wl("Method unimplemented")},Da=()=>{throw Wl("Unexpected case")},SP=Wl("Unexpected end of array"),EP=Wl("Integer out of Range");class ly{constructor(e){this.arr=e,this.pos=0}}const _h=n=>new ly(n),v7=n=>n.pos!==n.arr.length,y7=(n,e)=>{const t=new Uint8Array(n.arr.buffer,n.pos+n.arr.byteOffset,e);return n.pos+=e,t},Ui=n=>y7(n,$t(n)),Qf=n=>n.arr[n.pos++],$t=n=>{let e=0,t=1;const r=n.arr.length;for(;n.posxP)throw EP}throw SP},mw=n=>{let e=n.arr[n.pos++],t=e&ub,r=64;const i=(e&Pc)>0?-1:1;if(!(e&Vs))return i*t;const s=n.arr.length;for(;n.posxP)throw EP}throw SP},x7=n=>{let e=$t(n);if(e===0)return"";{let t=String.fromCodePoint(Qf(n));if(--e<100)for(;e--;)t+=String.fromCodePoint(Qf(n));else for(;e>0;){const r=e<1e4?e:1e4,i=n.arr.subarray(n.pos,n.pos+r);n.pos+=r,t+=String.fromCodePoint.apply(null,i),e-=r}return decodeURIComponent(escape(t))}},S7=n=>Cp.decode(Ui(n)),Pf=Cp?S7:x7,gw=(n,e)=>{const t=new DataView(n.arr.buffer,n.arr.byteOffset+n.pos,e);return n.pos+=e,t},E7=n=>gw(n,4).getFloat32(0,!1),b7=n=>gw(n,8).getFloat64(0,!1),T7=n=>gw(n,8).getBigInt64(0,!1),w7=[n=>{},n=>null,mw,E7,b7,T7,n=>!1,n=>!0,Pf,n=>{const e=$t(n),t={};for(let r=0;r{const e=$t(n),t=[];for(let r=0;rw7[127-Qf(n)](n);class j2 extends ly{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),v7(this)?this.count=$t(this)+1:this.count=-1),this.count--,this.s}}class E_ extends ly{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=mw(this);const e=yP(this.s);this.count=1,e&&(this.s=-this.s,this.count=$t(this)+2)}return this.count--,this.s}}class v1 extends ly{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=mw(this),t=e&1;this.diff=Gl(e/2),this.count=1,t&&(this.count=$t(this)+2)}return this.s+=this.diff,this.count--,this.s}}class A7{constructor(e){this.decoder=new E_(e),this.str=Pf(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}}const M7=crypto.getRandomValues.bind(crypto),bP=()=>M7(new Uint32Array(1))[0],C7="10000000-1000-4000-8000"+-1e11,R7=()=>C7.replace(/[018]/g,n=>(n^bP()&15>>n/4).toString(16)),$2=n=>new Promise(n);Promise.all.bind(Promise);const q2=n=>n===void 0?null:n;class k7{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}}let TP=new k7,N7=!0;try{typeof localStorage<"u"&&localStorage&&(TP=localStorage,N7=!1)}catch{}const I7=TP,O7=Object.assign,L7=Object.keys,P7=(n,e)=>{for(const t in n)e(n[t],t)},X2=n=>L7(n).length,D7=n=>{for(const e in n)return!1;return!0},U7=(n,e)=>{for(const t in n)if(!e(n[t],t))return!1;return!0},F7=(n,e)=>Object.prototype.hasOwnProperty.call(n,e),B7=(n,e)=>n===e||X2(n)===X2(e)&&U7(n,(t,r)=>(t!==void 0||F7(e,r))&&e[r]===t),z7=Object.freeze,wP=n=>{for(const e in n){const t=n[e];(typeof t=="object"||typeof t=="function")&&wP(n[e])}return z7(n)},_w=(n,e,t=0)=>{try{for(;tn,H7=(n,e)=>e.includes(n);var AP={};const Gp=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let ha;const G7=()=>{if(ha===void 0)if(Gp){ha=Do();const n=process.argv;let e=null;for(let t=0;t{if(n.length!==0){const[e,t]=n.split("=");ha.set(`--${z2(e,"-")}`,t),ha.set(`-${z2(e,"-")}`,t)}})):ha=Do();return ha},db=n=>G7().has(n),nv=n=>q2(Gp?AP[n.toUpperCase().replaceAll("-","_")]:I7.getItem(n)),MP=n=>db("--"+n)||nv(n)!==null;MP("production");const W7=Gp&&H7(AP.FORCE_COLOR,["true","1","2"]),j7=W7||!db("--no-colors")&&!MP("no-color")&&(!Gp||process.stdout.isTTY)&&(!Gp||db("--color")||nv("COLORTERM")!==null||(nv("TERM")||"").includes("color")),$7=n=>new Uint8Array(n),q7=n=>{const e=$7(n.byteLength);return e.set(n),e};class X7{constructor(e,t){this.left=e,this.right=t}}const vc=(n,e)=>new X7(n,e);typeof DOMParser<"u"&&new DOMParser;const K7=n=>X$(n,(e,t)=>`${t}:${e};`).join(""),Yc=Symbol,CP=Yc(),RP=Yc(),Y7=Yc(),Z7=Yc(),J7=Yc(),kP=Yc(),Q7=Yc(),vw=Yc(),eq=Yc(),tq=n=>{var i;n.length===1&&((i=n[0])==null?void 0:i.constructor)===Function&&(n=n[0]());const e=[],t=[];let r=0;for(;r0&&t.push(e.join(""));r{var o;n.length===1&&((o=n[0])==null?void 0:o.constructor)===Function&&(n=n[0]());const e=[],t=[],r=Do();let i=[],s=0;for(;s0||l.length>0?(e.push("%c"+a),t.push(l)):e.push(a)}else break}}for(s>0&&(i=t,i.unshift(e.join("")));s{console.log(...NP(n)),IP.forEach(e=>e.print(n))},sq=(...n)=>{console.warn(...NP(n)),n.unshift(vw),IP.forEach(e=>e.print(n))},IP=Jf(),OP=n=>({[Symbol.iterator](){return this},next:n}),oq=(n,e)=>OP(()=>{let t;do t=n.next();while(!t.done&&!e(t.value));return t}),y1=(n,e)=>OP(()=>{const{done:t,value:r}=n.next();return{done:t,value:t?void 0:e(r)}});class yw{constructor(e,t){this.clock=e,this.len=t}}class vm{constructor(){this.clients=new Map}}const LP=(n,e,t)=>e.clients.forEach((r,i)=>{const s=n.doc.store.clients.get(i);for(let o=0;o{let t=0,r=n.length-1;for(;t<=r;){const i=Gl((t+r)/2),s=n[i],o=s.clock;if(o<=e){if(e{const t=n.clients.get(e.client);return t!==void 0&&aq(t,e.clock)!==null},xw=n=>{n.clients.forEach(e=>{e.sort((i,s)=>i.clock-s.clock);let t,r;for(t=1,r=1;t=s.clock?i.len=gh(i.len,s.clock+s.len-i.clock):(r{const e=new vm;for(let t=0;t{if(!e.clients.has(i)){const s=r.slice();for(let o=t+1;o{eu(n.clients,e,()=>[]).push(new yw(t,r))},lq=()=>new vm,uq=n=>{const e=lq();return n.clients.forEach((t,r)=>{const i=[];for(let s=0;s0&&e.clients.set(r,i)}),e},Sd=(n,e)=>{jt(n.restEncoder,e.clients.size),Hl(e.clients.entries()).sort((t,r)=>r[0]-t[0]).forEach(([t,r])=>{n.resetDsCurVal(),jt(n.restEncoder,t);const i=r.length;jt(n.restEncoder,i);for(let s=0;s{const e=new vm,t=$t(n.restDecoder);for(let r=0;r0){const o=eu(e.clients,i,()=>[]);for(let a=0;a{const r=new vm,i=$t(n.restDecoder);for(let s=0;s0){const s=new Qu;return jt(s.restEncoder,0),Sd(s,r),s.toUint8Array()}return null},DP=bP;class Zc extends J${constructor({guid:e=R7(),collectionid:t=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:a=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=DP(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new jP,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=$2(l=>{this.on("load",()=>{this.isLoaded=!0,l(this)})});const c=()=>$2(l=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),l())};this.on("sync",u)});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;e!==null&&!this.shouldLoad&&Bn(e.parent.doc,t=>{t.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Hl(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Bn(this,e,t)}get(e,t=fr){const r=eu(this.share,e,()=>{const s=new t;return s._integrate(this,null),s}),i=r.constructor;if(t!==fr&&i!==t)if(i===fr){const s=new t;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(e,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,Na)}getText(e=""){return this.get(e,Bo)}getMap(e=""){return this.get(e,Ua)}getXmlElement(e=""){return this.get(e,Hc)}getXmlFragment(e=""){return this.get(e,Fa)}toJSON(){const e={};return this.share.forEach((t,r)=>{e[r]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Hl(this.subdocs).forEach(t=>t.destroy());const e=this._item;if(e!==null){this._item=null;const t=e.content;t.doc=new Zc({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,Bn(e.parent.doc,r=>{const i=t.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class UP{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return $t(this.restDecoder)}readDsLen(){return $t(this.restDecoder)}}class FP extends UP{readLeftID(){return ln($t(this.restDecoder),$t(this.restDecoder))}readRightID(){return ln($t(this.restDecoder),$t(this.restDecoder))}readClient(){return $t(this.restDecoder)}readInfo(){return Qf(this.restDecoder)}readString(){return Pf(this.restDecoder)}readParentInfo(){return $t(this.restDecoder)===1}readTypeRef(){return $t(this.restDecoder)}readLen(){return $t(this.restDecoder)}readAny(){return Hp(this.restDecoder)}readBuf(){return q7(Ui(this.restDecoder))}readJSON(){return JSON.parse(Pf(this.restDecoder))}readKey(){return Pf(this.restDecoder)}}class hq{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=$t(this.restDecoder),this.dsCurrVal}readDsLen(){const e=$t(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class ed extends hq{constructor(e){super(e),this.keys=[],$t(e),this.keyClockDecoder=new v1(Ui(e)),this.clientDecoder=new E_(Ui(e)),this.leftClockDecoder=new v1(Ui(e)),this.rightClockDecoder=new v1(Ui(e)),this.infoDecoder=new j2(Ui(e),Qf),this.stringDecoder=new A7(Ui(e)),this.parentInfoDecoder=new j2(Ui(e),Qf),this.typeRefDecoder=new E_(Ui(e)),this.lenDecoder=new E_(Ui(e))}readLeftID(){return new Df(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Df(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Hp(this.restDecoder)}readBuf(){return Ui(this.restDecoder)}readJSON(){return Hp(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e{r=gh(r,e[0].id.clock);const i=Fo(e,r);jt(n.restEncoder,e.length-i),n.writeClient(t),jt(n.restEncoder,r);const s=e[i];s.write(n,r-s.id.clock);for(let o=i+1;o{const r=new Map;t.forEach((i,s)=>{li(e,s)>i&&r.set(s,i)}),uy(e).forEach((i,s)=>{t.has(s)||r.set(s,0)}),jt(n.restEncoder,r.size),Hl(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{fq(n,e.clients.get(i),i,s)})},dq=(n,e)=>{const t=Do(),r=$t(n.restDecoder);for(let i=0;i{const r=[];let i=Hl(t.keys()).sort((m,g)=>m-g);if(i.length===0)return null;const s=()=>{if(i.length===0)return null;let m=t.get(i[i.length-1]);for(;m.refs.length===m.i;)if(i.pop(),i.length>0)m=t.get(i[i.length-1]);else return null;return m};let o=s();if(o===null)return null;const a=new jP,c=new Map,l=(m,g)=>{const v=c.get(m);(v==null||v>g)&&c.set(m,g)};let u=o.refs[o.i++];const h=new Map,d=()=>{for(const m of r){const g=m.id.client,v=t.get(g);v?(v.i--,a.clients.set(g,v.refs.slice(v.i)),t.delete(g),v.i=0,v.refs=[]):a.clients.set(g,[m]),i=i.filter(y=>y!==g)}r.length=0};for(;;){if(u.constructor!==so){const g=eu(h,u.id.client,()=>li(e,u.id.client))-u.id.clock;if(g<0)r.push(u),l(u.id.client,u.id.clock-1),d();else{const v=u.getMissing(n,e);if(v!==null){r.push(u);const y=t.get(v)||{refs:[],i:0};if(y.refs.length===y.i)l(v,li(e,v)),d();else{u=y.refs[y.i++];continue}}else(g===0||g0)u=r.pop();else if(o!==null&&o.i0){const m=new Qu;return Ew(m,a,new Map),jt(m.restEncoder,0),{missing:c,update:m.toUint8Array()}}return null},mq=(n,e)=>Ew(n,e.doc.store,e.beforeState),gq=(n,e,t,r=new ed(n))=>Bn(e,i=>{i.local=!1;let s=!1;const o=i.doc,a=o.store,c=dq(r,o),l=pq(i,a,c),u=a.pendingStructs;if(u){for(const[d,m]of u.missing)if(mm)&&u.missing.set(d,m)}u.update=iv([u.update,l.update])}}else a.pendingStructs=l;const h=K2(r,i,a);if(a.pendingDs){const d=new ed(_h(a.pendingDs));$t(d.restDecoder);const m=K2(d,i,a);h&&m?a.pendingDs=iv([h,m]):a.pendingDs=h||m}else a.pendingDs=h;if(s){const d=a.pendingStructs.update;a.pendingStructs=null,VP(i.doc,d)}},t,!1),VP=(n,e,t,r=ed)=>{const i=_h(e);gq(i,n,t,new r(i))},_q=(n,e,t)=>VP(n,e,t,FP),vq=(n,e,t=new Map)=>{Ew(n,e.store,t),Sd(n,uq(e.store))},yq=(n,e=new Uint8Array([0]),t=new Qu)=>{const r=HP(e);vq(t,n,r);const i=[t.toUint8Array()];if(n.store.pendingDs&&i.push(n.store.pendingDs),n.store.pendingStructs&&i.push(Pq(n.store.pendingStructs.update,e)),i.length>1){if(t.constructor===ym)return Oq(i.map((s,o)=>o===0?s:Uq(s)));if(t.constructor===Qu)return iv(i)}return i[0]},xq=(n,e)=>yq(n,e,new ym),Sq=n=>{const e=new Map,t=$t(n.restDecoder);for(let r=0;rSq(new UP(_h(n))),GP=(n,e)=>(jt(n.restEncoder,e.size),Hl(e.entries()).sort((t,r)=>r[0]-t[0]).forEach(([t,r])=>{jt(n.restEncoder,t),jt(n.restEncoder,r)}),n),Eq=(n,e)=>GP(n,uy(e.store)),bq=(n,e=new zP)=>(n instanceof Map?GP(e,n):Eq(e,n),e.toUint8Array()),Tq=n=>bq(n,new BP);class wq{constructor(){this.l=[]}}const Y2=()=>new wq,Z2=(n,e)=>n.l.push(e),J2=(n,e)=>{const t=n.l,r=t.length;n.l=t.filter(i=>e!==i),r===n.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},WP=(n,e,t)=>_w(n.l,[e,t]);class Df{constructor(e,t){this.client=e,this.clock=t}}const D0=(n,e)=>n===e||n!==null&&e!==null&&n.client===e.client&&n.clock===e.clock,ln=(n,e)=>new Df(n,e),Aq=n=>{for(const[e,t]of n.doc.share.entries())if(t===n)return e;throw Da()},_f=(n,e)=>e===void 0?!n.deleted:e.sv.has(n.id.client)&&(e.sv.get(n.id.client)||0)>n.id.clock&&!PP(e.ds,n.id),pb=(n,e)=>{const t=eu(n.meta,pb,Jf),r=n.doc.store;t.has(e)||(e.sv.forEach((i,s)=>{i{}),t.add(e))};class jP{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const uy=n=>{const e=new Map;return n.clients.forEach((t,r)=>{const i=t[t.length-1];e.set(r,i.id.clock+i.length)}),e},li=(n,e)=>{const t=n.clients.get(e);if(t===void 0)return 0;const r=t[t.length-1];return r.id.clock+r.length},$P=(n,e)=>{let t=n.clients.get(e.id.client);if(t===void 0)t=[],n.clients.set(e.id.client,t);else{const r=t[t.length-1];if(r.id.clock+r.length!==e.id.clock)throw Da()}t.push(e)},Fo=(n,e)=>{let t=0,r=n.length-1,i=n[r],s=i.id.clock;if(s===e)return r;let o=Gl(e/(s+i.length-1)*r);for(;t<=r;){if(i=n[o],s=i.id.clock,s<=e){if(e{const t=n.clients.get(e.client);return t[Fo(t,e.clock)]},x1=Mq,mb=(n,e,t)=>{const r=Fo(e,t),i=e[r];return i.id.clock{const t=n.doc.store.clients.get(e.client);return t[mb(n,t,e.clock)]},Q2=(n,e,t)=>{const r=e.clients.get(t.client),i=Fo(r,t.clock),s=r[i];return t.clock!==s.id.clock+s.length-1&&s.constructor!==Fs&&r.splice(i+1,0,cv(n,s,t.clock-s.id.clock+1)),s},Cq=(n,e,t)=>{const r=n.clients.get(e.id.client);r[Fo(r,e.id.clock)]=t},qP=(n,e,t,r,i)=>{if(r===0)return;const s=t+r;let o=mb(n,e,t),a;do a=e[o++],se.deleteSet.clients.size===0&&!K$(e.afterState,(t,r)=>e.beforeState.get(r)!==t)?!1:(xw(e.deleteSet),mq(n,e),Sd(n,e.deleteSet),!0),tk=(n,e,t)=>{const r=e._item;(r===null||r.id.clock<(n.beforeState.get(r.id.client)||0)&&!r.deleted)&&eu(n.changed,e,Jf).add(t)},b_=(n,e)=>{let t=n[e],r=n[e-1],i=e;for(;i>0;t=r,r=n[--i-1]){if(r.deleted===t.deleted&&r.constructor===t.constructor&&r.mergeWith(t)){t instanceof Hr&&t.parentSub!==null&&t.parent._map.get(t.parentSub)===t&&t.parent._map.set(t.parentSub,r);continue}break}const s=e-i;return s&&n.splice(e+1-s,s),s},kq=(n,e,t)=>{for(const[r,i]of n.clients.entries()){const s=e.clients.get(r);for(let o=i.length-1;o>=0;o--){const a=i[o],c=a.clock+a.len;for(let l=Fo(s,a.clock),u=s[l];l{n.clients.forEach((t,r)=>{const i=e.clients.get(r);for(let s=t.length-1;s>=0;s--){const o=t[s],a=vP(i.length-1,1+Fo(i,o.clock+o.len-1));for(let c=a,l=i[c];c>0&&l.id.clock>=o.clock;l=i[c])c-=1+b_(i,c)}})},XP=(n,e)=>{if(ea.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(t,c)})),a.push(()=>{t.changedParentTypes.forEach((c,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=l,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),WP(l._dEH,c,t))})}),a.push(()=>r.emit("afterTransaction",[t,r])),_w(a,[]),t._needFormattingCleanup&&Zq(t)}finally{r.gc&&kq(s,i,r.gcFilter),Nq(s,i),t.afterState.forEach((u,h)=>{const d=t.beforeState.get(h)||0;if(d!==u){const m=i.clients.get(h),g=gh(Fo(m,d),1);for(let v=m.length-1;v>=g;)v-=1+b_(m,v)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:d}=o[u].id,m=i.clients.get(h),g=Fo(m,d);g+11||g>0&&b_(m,g)}if(!t.local&&t.afterState.get(r.clientID)!==t.beforeState.get(r.clientID)&&(iq(vw,CP,"[yjs] ",RP,kP,"Changed the client-id because another client seems to be using it."),r.clientID=DP()),r.emit("afterTransactionCleanup",[t,r]),r._observers.has("update")){const u=new ym;ek(u,t)&&r.emit("update",[u.toUint8Array(),t.origin,r,t])}if(r._observers.has("updateV2")){const u=new Qu;ek(u,t)&&r.emit("updateV2",[u.toUint8Array(),t.origin,r,t])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:l}=t;(a.size>0||l.size>0||c.size>0)&&(a.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),l.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:c,added:a,removed:l},r,t]),l.forEach(u=>u.destroy())),n.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,n])):XP(n,e+1)}}},Bn=(n,e,t=null,r=!0)=>{const i=n._transactionCleanups;let s=!1,o=null;n._transaction===null&&(s=!0,n._transaction=new Rq(n,t,r),i.push(n._transaction),i.length===1&&n.emit("beforeAllTransactions",[n]),n.emit("beforeTransaction",[n._transaction,n]));try{o=e(n._transaction)}finally{if(s){const a=n._transaction===i[0];n._transaction=null,a&&XP(i,0)}}return o};function*Iq(n){const e=$t(n.restDecoder);for(let t=0;tiv(n,FP,ym),Lq=(n,e)=>{if(n.constructor===Fs){const{client:t,clock:r}=n.id;return new Fs(ln(t,r+e),n.length-e)}else if(n.constructor===so){const{client:t,clock:r}=n.id;return new so(ln(t,r+e),n.length-e)}else{const t=n,{client:r,clock:i}=t.id;return new Hr(ln(r,i+e),null,ln(r,i+e-1),null,t.rightOrigin,t.parent,t.parentSub,t.content.splice(e))}},iv=(n,e=ed,t=Qu)=>{if(n.length===1)return n[0];const r=n.map(u=>new e(_h(u)));let i=r.map(u=>new bw(u,!0)),s=null;const o=new t,a=new Tw(o);for(;i=i.filter(d=>d.curr!==null),i.sort((d,m)=>{if(d.curr.id.client===m.curr.id.client){const g=d.curr.id.clock-m.curr.id.clock;return g===0?d.curr.constructor===m.curr.constructor?0:d.curr.constructor===so?1:-1:g}else return m.curr.id.client-d.curr.id.client}),i.length!==0;){const u=i[0],h=u.curr.id.client;if(s!==null){let d=u.curr,m=!1;for(;d!==null&&d.id.clock+d.length<=s.struct.id.clock+s.struct.length&&d.id.client>=s.struct.id.client;)d=u.next(),m=!0;if(d===null||d.id.client!==h||m&&d.id.clock>s.struct.id.clock+s.struct.length)continue;if(h!==s.struct.id.client)Rl(a,s.struct,s.offset),s={struct:d,offset:0},u.next();else if(s.struct.id.clock+s.struct.length0&&(s.struct.constructor===so?s.struct.length-=g:d=Lq(d,g)),s.struct.mergeWith(d)||(Rl(a,s.struct,s.offset),s={struct:d,offset:0},u.next())}}else s={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===h&&d.id.clock===s.struct.id.clock+s.struct.length&&d.constructor!==so;d=u.next())Rl(a,s.struct,s.offset),s={struct:d,offset:0}}s!==null&&(Rl(a,s.struct,s.offset),s=null),ww(a);const c=r.map(u=>Sw(u)),l=cq(c);return Sd(o,l),o.toUint8Array()},Pq=(n,e,t=ed,r=Qu)=>{const i=HP(e),s=new r,o=new Tw(s),a=new t(_h(n)),c=new bw(a,!1);for(;c.curr;){const u=c.curr,h=u.id.client,d=i.get(h)||0;if(c.curr.constructor===so){c.next();continue}if(u.id.clock+u.length>d)for(Rl(o,u,gh(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Rl(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=d;)c.next()}ww(o);const l=Sw(a);return Sd(s,l),s.toUint8Array()},KP=n=>{n.written>0&&(n.clientStructs.push({written:n.written,restEncoder:Oo(n.encoder.restEncoder)}),n.encoder.restEncoder=Ll(),n.written=0)},Rl=(n,e,t)=>{n.written>0&&n.currClient!==e.id.client&&KP(n),n.written===0&&(n.currClient=e.id.client,n.encoder.writeClient(e.id.client),jt(n.encoder.restEncoder,e.id.clock+t)),e.write(n.encoder,t),n.written++},ww=n=>{KP(n);const e=n.encoder.restEncoder;jt(e,n.clientStructs.length);for(let t=0;t{const i=new t(_h(n)),s=new bw(i,!1),o=new r,a=new Tw(o);for(let l=s.curr;l!==null;l=s.next())Rl(a,e(l),0);ww(a);const c=Sw(i);return Sd(o,c),o.toUint8Array()},Uq=n=>Dq(n,V7,ed,ym),nk="You must not compute changes after the event-handler fired.";class hy{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Fq(this.currentTarget,this.target))}deletes(e){return PP(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Wl(nk);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach(i=>{if(i!==null){const s=t._map.get(i);let o,a;if(this.adds(s)){let c=s.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(s))if(c!==null&&this.deletes(c))o="delete",a=p1(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",a=p1(c.content.getContent())):(o="add",a=void 0)}else if(this.deletes(s))o="delete",a=p1(s.content.getContent());else return;e.set(i,{action:o,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Wl(nk);const t=this.target,r=Jf(),i=Jf(),s=[];if(e={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(t).has(null)){let a=null;const c=()=>{a&&s.push(a)};for(let l=t._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=l.length,i.add(l)):this.adds(l)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(l.content.getContent()),r.add(l)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=l.length);a!==null&&a.retain===void 0&&c()}this._changes=e}return e}}const Fq=(n,e)=>{const t=[];for(;e._item!==null&&e!==n;){if(e._item.parentSub!==null)t.unshift(e._item.parentSub);else{let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;t.unshift(r)}e=e._item.parent}return t},wi=()=>{sq("Invalid access: Add Yjs type to a document before reading data.")},YP=80;let Aw=0;class Bq{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Aw++}}const zq=n=>{n.timestamp=Aw++},ZP=(n,e,t)=>{n.p.marker=!1,n.p=e,e.marker=!0,n.index=t,n.timestamp=Aw++},Vq=(n,e,t)=>{if(n.length>=YP){const r=n.reduce((i,s)=>i.timestamp{if(n._start===null||e===0||n._searchMarker===null)return null;const t=n._searchMarker.length===0?null:n._searchMarker.reduce((s,o)=>x_(e-s.index)e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return t!==null&&x_(t.index-i){for(let r=n.length-1;r>=0;r--){const i=n[r];if(t>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){n.splice(r,1);continue}i.p=s,s.marker=!0}(e0&&e===i.index)&&(i.index=gh(e,i.index+t))}},dy=(n,e,t)=>{const r=n,i=e.changedParentTypes;for(;eu(i,n,()=>[]).push(t),n._item!==null;)n=n._item.parent;WP(r._eH,t,e)};class fr{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Y2(),this._dEH=Y2(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw ka()}clone(){throw ka()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Z2(this._eH,e)}observeDeep(e){Z2(this._dEH,e)}unobserve(e){J2(this._eH,e)}unobserveDeep(e){J2(this._dEH,e)}toJSON(){}}const JP=(n,e,t)=>{n.doc??wi(),e<0&&(e=n._length+e),t<0&&(t=n._length+t);let r=t-e;const i=[];let s=n._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){const o=s.content.getContent();if(o.length<=e)e-=o.length;else{for(let a=e;a0;a++)i.push(o[a]),r--;e=0}}s=s.right}return i},QP=n=>{n.doc??wi();const e=[];let t=n._start;for(;t!==null;){if(t.countable&&!t.deleted){const r=t.content.getContent();for(let i=0;i{let t=0,r=n._start;for(n.doc??wi();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let s=0;s{const t=[];return jp(n,(r,i)=>{t.push(e(r,i,n))}),t},Hq=n=>{let e=n._start,t=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(t===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};t=e.content.getContent(),r=0,e=e.right}const i=t[r++];return t.length<=r&&(t=null),{done:!1,value:i}}}},tD=(n,e)=>{n.doc??wi();const t=fy(n,e);let r=n._start;for(t!==null&&(r=t.p,e-=t.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e{let i=t;const s=n.doc,o=s.clientID,a=s.store,c=t===null?e._start:t.right;let l=[];const u=()=>{l.length>0&&(i=new Hr(ln(o,li(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new th(l)),i.integrate(n,0),l=[])};r.forEach(h=>{if(h===null)l.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:i=new Hr(ln(o,li(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new xm(new Uint8Array(h))),i.integrate(n,0);break;case Zc:i=new Hr(ln(o,li(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new Sm(h)),i.integrate(n,0);break;default:if(h instanceof fr)i=new Hr(ln(o,li(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new Jc(h)),i.integrate(n,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},nD=()=>Wl("Length exceeded!"),rD=(n,e,t,r)=>{if(t>e._length)throw nD();if(t===0)return e._searchMarker&&Wp(e._searchMarker,t,r.length),sv(n,e,null,r);const i=t,s=fy(e,t);let o=e._start;for(s!==null&&(o=s.p,t-=s.index,t===0&&(o=o.prev,t+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(t<=o.length){t{let i=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return sv(n,e,i,t)},iD=(n,e,t,r)=>{if(r===0)return;const i=t,s=r,o=fy(e,t);let a=e._start;for(o!==null&&(a=o.p,t-=o.index);a!==null&&t>0;a=a.right)!a.deleted&&a.countable&&(t0&&a!==null;)a.deleted||(r0)throw nD();e._searchMarker&&Wp(e._searchMarker,i,-s+r)},ov=(n,e,t)=>{const r=e._map.get(t);r!==void 0&&r.delete(n)},Mw=(n,e,t,r)=>{const i=e._map.get(t)||null,s=n.doc,o=s.clientID;let a;if(r==null)a=new th([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:a=new th([r]);break;case Uint8Array:a=new xm(r);break;case Zc:a=new Sm(r);break;default:if(r instanceof fr)a=new Jc(r);else throw new Error("Unexpected content type")}new Hr(ln(o,li(s.store,o)),i,i&&i.lastId,null,null,e,t,a).integrate(n,0)},Cw=(n,e)=>{n.doc??wi();const t=n._map.get(e);return t!==void 0&&!t.deleted?t.content.getContent()[t.length-1]:void 0},sD=n=>{const e={};return n.doc??wi(),n._map.forEach((t,r)=>{t.deleted||(e[r]=t.content.getContent()[t.length-1])}),e},oD=(n,e)=>{n.doc??wi();const t=n._map.get(e);return t!==void 0&&!t.deleted},Wq=(n,e)=>{const t={};return n._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&_f(s,e)&&(t[i]=s.content.getContent()[s.length-1])}),t},U0=n=>(n.doc??wi(),oq(n._map.entries(),e=>!e[1].deleted));class jq extends hy{}class Na extends fr{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Na;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Na}clone(){const e=new Na;return e.insert(0,this.toArray().map(t=>t instanceof fr?t.clone():t)),e}get length(){return this.doc??wi(),this._length}_callObserver(e,t){super._callObserver(e,t),dy(this,e,new jq(this,e))}insert(e,t){this.doc!==null?Bn(this.doc,r=>{rD(r,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){this.doc!==null?Bn(this.doc,t=>{Gq(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc!==null?Bn(this.doc,r=>{iD(r,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return tD(this,e)}toArray(){return QP(this)}slice(e=0,t=this.length){return JP(this,e,t)}toJSON(){return this.map(e=>e instanceof fr?e.toJSON():e)}map(e){return eD(this,e)}forEach(e){jp(this,e)}[Symbol.iterator](){return Hq(this)}_write(e){e.writeTypeRef(gX)}}const $q=n=>new Na;class qq extends hy{constructor(e,t,r){super(e,t),this.keysChanged=r}}class Ua extends fr{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new Ua}clone(){const e=new Ua;return this.forEach((t,r)=>{e.set(r,t instanceof fr?t.clone():t)}),e}_callObserver(e,t){dy(this,e,new qq(this,e,t))}toJSON(){this.doc??wi();const e={};return this._map.forEach((t,r)=>{if(!t.deleted){const i=t.content.getContent()[t.length-1];e[r]=i instanceof fr?i.toJSON():i}}),e}get size(){return[...U0(this)].length}keys(){return y1(U0(this),e=>e[0])}values(){return y1(U0(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return y1(U0(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??wi(),this._map.forEach((t,r)=>{t.deleted||e(t.content.getContent()[t.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?Bn(this.doc,t=>{ov(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return this.doc!==null?Bn(this.doc,r=>{Mw(r,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return Cw(this,e)}has(e){return oD(this,e)}clear(){this.doc!==null?Bn(this.doc,e=>{this.forEach(function(t,r,i){ov(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(_X)}}const Xq=n=>new Ua,Nl=(n,e)=>n===e||typeof n=="object"&&typeof e=="object"&&n&&e&&B7(n,e);class gb{constructor(e,t,r,i){this.left=e,this.right=t,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Da(),this.right.content.constructor){case qr:this.right.deleted||Ed(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const rk=(n,e,t)=>{for(;e.right!==null&&t>0;){switch(e.right.content.constructor){case qr:e.right.deleted||Ed(e.currentAttributes,e.right.content);break;default:e.right.deleted||(t{const i=new Map,s=r?fy(e,t):null;if(s){const o=new gb(s.p.left,s.p,s.index,i);return rk(n,o,t-s.index)}else{const o=new gb(null,e._start,0,i);return rk(n,o,t)}},aD=(n,e,t,r)=>{for(;t.right!==null&&(t.right.deleted===!0||t.right.content.constructor===qr&&Nl(r.get(t.right.content.key),t.right.content.value));)t.right.deleted||r.delete(t.right.content.key),t.forward();const i=n.doc,s=i.clientID;r.forEach((o,a)=>{const c=t.left,l=t.right,u=new Hr(ln(s,li(i.store,s)),c,c&&c.lastId,l,l&&l.id,e,null,new qr(a,o));u.integrate(n,0),t.right=u,t.forward()})},Ed=(n,e)=>{const{key:t,value:r}=e;r===null?n.delete(t):n.set(t,r)},cD=(n,e)=>{for(;n.right!==null;){if(!(n.right.deleted||n.right.content.constructor===qr&&Nl(e[n.right.content.key]??null,n.right.content.value)))break;n.forward()}},lD=(n,e,t,r)=>{const i=n.doc,s=i.clientID,o=new Map;for(const a in r){const c=r[a],l=t.currentAttributes.get(a)??null;if(!Nl(l,c)){o.set(a,l);const{left:u,right:h}=t;t.right=new Hr(ln(s,li(i.store,s)),u,u&&u.lastId,h,h&&h.id,e,null,new qr(a,c)),t.right.integrate(n,0),t.forward()}}return o},S1=(n,e,t,r,i)=>{t.currentAttributes.forEach((d,m)=>{i[m]===void 0&&(i[m]=null)});const s=n.doc,o=s.clientID;cD(t,i);const a=lD(n,e,t,i),c=r.constructor===String?new Ba(r):r instanceof fr?new Jc(r):new vh(r);let{left:l,right:u,index:h}=t;e._searchMarker&&Wp(e._searchMarker,t.index,c.getLength()),u=new Hr(ln(o,li(s.store,o)),l,l&&l.lastId,u,u&&u.id,e,null,c),u.integrate(n,0),t.right=u,t.index=h,t.forward(),aD(n,e,t,a)},ik=(n,e,t,r,i)=>{const s=n.doc,o=s.clientID;cD(t,i);const a=lD(n,e,t,i);e:for(;t.right!==null&&(r>0||a.size>0&&(t.right.deleted||t.right.content.constructor===qr));){if(!t.right.deleted)switch(t.right.content.constructor){case qr:{const{key:c,value:l}=t.right.content,u=i[c];if(u!==void 0){if(Nl(u,l))a.delete(c);else{if(r===0)break e;a.set(c,l)}t.right.delete(n)}else t.currentAttributes.set(c,l);break}default:r0){let c="";for(;r>0;r--)c+=` +`;t.right=new Hr(ln(o,li(s.store,o)),t.left,t.left&&t.left.lastId,t.right,t.right&&t.right.id,e,null,new Ba(c)),t.right.integrate(n,0),t.forward()}aD(n,e,t,a)},uD=(n,e,t,r,i)=>{let s=e;const o=Do();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===qr){const l=s.content;o.set(l.key,l)}s=s.right}let a=0,c=!1;for(;e!==s;){if(t===e&&(c=!0),!e.deleted){const l=e.content;switch(l.constructor){case qr:{const{key:u,value:h}=l,d=r.get(u)??null;(o.get(u)!==l||d===h)&&(e.delete(n),a++,!c&&(i.get(u)??null)===h&&d!==h&&(d===null?i.delete(u):i.set(u,d))),!c&&!e.deleted&&Ed(i,l);break}}}e=e.right}return a},Kq=(n,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const t=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===qr){const r=e.content.key;t.has(r)?e.delete(n):t.add(r)}e=e.left}},Yq=n=>{let e=0;return Bn(n.doc,t=>{let r=n._start,i=n._start,s=Do();const o=lb(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case qr:Ed(o,i.content);break;default:e+=uD(t,r,i,s,o),s=lb(o),r=i;break}i=i.right}}),e},Zq=n=>{const e=new Set,t=n.doc;for(const[r,i]of n.afterState.entries()){const s=n.beforeState.get(r)||0;i!==s&&qP(n,t.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===qr&&o.constructor!==Fs&&e.add(o.parent)})}Bn(t,r=>{LP(n,n.deleteSet,i=>{if(i instanceof Fs||!i.parent._hasFormatting||e.has(i.parent))return;const s=i.parent;i.content.constructor===qr?e.add(s):Kq(r,i)});for(const i of e)Yq(i)})},sk=(n,e,t)=>{const r=t,i=lb(e.currentAttributes),s=e.right;for(;t>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case Jc:case vh:case Ba:t{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,t=[];Bn(e,r=>{const i=new Map,s=new Map;let o=this.target._start,a=null;const c={};let l="",u=0,h=0;const d=()=>{if(a!==null){let m=null;switch(a){case"delete":h>0&&(m={delete:h}),h=0;break;case"insert":(typeof l=="object"||l.length>0)&&(m={insert:l},i.size>0&&(m.attributes={},i.forEach((g,v)=>{g!==null&&(m.attributes[v]=g)}))),l="";break;case"retain":u>0&&(m={retain:u},D7(c)||(m.attributes=O7({},c))),u=0;break}m&&t.push(m),a=null}};for(;o!==null;){switch(o.content.constructor){case Jc:case vh:this.adds(o)?this.deletes(o)||(d(),a="insert",l=o.content.getContent()[0],d()):this.deletes(o)?(a!=="delete"&&(d(),a="delete"),h+=1):o.deleted||(a!=="retain"&&(d(),a="retain"),u+=1);break;case Ba:this.adds(o)?this.deletes(o)||(a!=="insert"&&(d(),a="insert"),l+=o.content.str):this.deletes(o)?(a!=="delete"&&(d(),a="delete"),h+=o.length):o.deleted||(a!=="retain"&&(d(),a="retain"),u+=o.length);break;case qr:{const{key:m,value:g}=o.content;if(this.adds(o)){if(!this.deletes(o)){const v=i.get(m)??null;Nl(v,g)?g!==null&&o.delete(r):(a==="retain"&&d(),Nl(g,s.get(m)??null)?delete c[m]:c[m]=g)}}else if(this.deletes(o)){s.set(m,g);const v=i.get(m)??null;Nl(v,g)||(a==="retain"&&d(),c[m]=v)}else if(!o.deleted){s.set(m,g);const v=c[m];v!==void 0&&(Nl(v,g)?v!==null&&o.delete(r):(a==="retain"&&d(),g===null?delete c[m]:c[m]=g))}o.deleted||(a==="insert"&&d(),Ed(i,o.content));break}}o=o.right}for(d();t.length>0;){const m=t[t.length-1];if(m.retain!==void 0&&m.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}}class Bo extends fr{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??wi(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new Bo}clone(){const e=new Bo;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const r=new Jq(this,e,t);dy(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??wi();let e="",t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Ba&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc!==null?Bn(this.doc,r=>{const i=new gb(null,this._start,0,new Map);for(let s=0;s0)&&S1(r,this,i,a,o.attributes||{})}else o.retain!==void 0?ik(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&sk(r,i,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,r){this.doc??wi();const i=[],s=new Map,o=this.doc;let a="",c=this._start;function l(){if(a.length>0){const h={};let d=!1;s.forEach((g,v)=>{d=!0,h[v]=g});const m={insert:a};d&&(m.attributes=h),i.push(m),a=""}}const u=()=>{for(;c!==null;){if(_f(c,e)||t!==void 0&&_f(c,t))switch(c.content.constructor){case Ba:{const h=s.get("ychange");e!==void 0&&!_f(c,e)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(l(),s.set("ychange",r?r("removed",c.id):{type:"removed"})):t!==void 0&&!_f(c,t)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(l(),s.set("ychange",r?r("added",c.id):{type:"added"})):h!==void 0&&(l(),s.delete("ychange")),a+=c.content.str;break}case Jc:case vh:{l();const h={insert:c.content.getContent()[0]};if(s.size>0){const d={};h.attributes=d,s.forEach((m,g)=>{d[g]=m})}i.push(h);break}case qr:_f(c,e)&&(l(),Ed(s,c.content));break}c=c.right}l()};return e||t?Bn(o,h=>{e&&pb(h,e),t&&pb(h,t),u()},"cleanup"):u(),i}insert(e,t,r){if(t.length<=0)return;const i=this.doc;i!==null?Bn(i,s=>{const o=F0(s,this,e,!r);r||(r={},o.currentAttributes.forEach((a,c)=>{r[c]=a})),S1(s,this,o,t,r)}):this._pending.push(()=>this.insert(e,t,r))}insertEmbed(e,t,r){const i=this.doc;i!==null?Bn(i,s=>{const o=F0(s,this,e,!r);S1(s,this,o,t,r||{})}):this._pending.push(()=>this.insertEmbed(e,t,r||{}))}delete(e,t){if(t===0)return;const r=this.doc;r!==null?Bn(r,i=>{sk(i,F0(i,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,r){if(t===0)return;const i=this.doc;i!==null?Bn(i,s=>{const o=F0(s,this,e,!1);o.right!==null&&ik(s,this,o,t,r)}):this._pending.push(()=>this.format(e,t,r))}removeAttribute(e){this.doc!==null?Bn(this.doc,t=>{ov(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){this.doc!==null?Bn(this.doc,r=>{Mw(r,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return Cw(this,e)}getAttributes(){return sD(this)}_write(e){e.writeTypeRef(vX)}}const Qq=n=>new Bo;class E1{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??wi()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===Hc||t.constructor===Fa)&&t._start!==null)e=t._start;else for(;e!==null;)if(e.right!==null){e=e.right;break}else e.parent===this._root?e=null:e=e.parent._item;while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class Fa extends fr{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Fa}clone(){const e=new Fa;return e.insert(0,this.toArray().map(t=>t instanceof fr?t.clone():t)),e}get length(){return this.doc??wi(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new E1(this,e)}querySelector(e){e=e.toUpperCase();const r=new E1(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),Hl(new E1(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){dy(this,e,new nX(this,t,e))}toString(){return eD(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},r){const i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),jp(this,s=>{i.insertBefore(s.toDOM(e,t,r),null)}),i}insert(e,t){this.doc!==null?Bn(this.doc,r=>{rD(r,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(this.doc!==null)Bn(this.doc,r=>{const i=e&&e instanceof fr?e._item:e;sv(r,this,i,t)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(s=>s===e)+1;if(i===0&&e!==null)throw Wl("Reference item not found");r.splice(i,0,...t)}}delete(e,t=1){this.doc!==null?Bn(this.doc,r=>{iD(r,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return QP(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return tD(this,e)}slice(e=0,t=this.length){return JP(this,e,t)}forEach(e){jp(this,e)}_write(e){e.writeTypeRef(xX)}}const eX=n=>new Fa;class Hc extends Fa{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new Hc(this.nodeName)}clone(){const e=new Hc(this.nodeName),t=this.getAttributes();return P7(t,(r,i)=>{typeof r=="string"&&e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof fr?r.clone():r)),e}toString(){const e=this.getAttributes(),t=[],r=[];for(const a in e)r.push(a);r.sort();const i=r.length;for(let a=0;a0?" "+t.join(" "):"";return`<${s}${o}>${super.toString()}`}removeAttribute(e){this.doc!==null?Bn(this.doc,t=>{ov(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){this.doc!==null?Bn(this.doc,r=>{Mw(r,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return Cw(this,e)}hasAttribute(e){return oD(this,e)}getAttributes(e){return e?Wq(this,e):sD(this)}toDOM(e=document,t={},r){const i=e.createElement(this.nodeName),s=this.getAttributes();for(const o in s){const a=s[o];typeof a=="string"&&i.setAttribute(o,a)}return jp(this,o=>{i.appendChild(o.toDOM(e,t,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(yX),e.writeKey(this.nodeName)}}const tX=n=>new Hc(n.readKey());class nX extends hy{constructor(e,t,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class td extends Ua{constructor(e){super(),this.hookName=e}_copy(){return new td(this.hookName)}clone(){const e=new td(this.hookName);return this.forEach((t,r)=>{e.set(r,t)}),e}toDOM(e=document,t={},r){const i=t[this.hookName];let s;return i!==void 0?s=i.createDom(this):s=document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(s,this),s}_write(e){e.writeTypeRef(SX),e.writeKey(this.hookName)}}const rX=n=>new td(n.readKey());class eh extends Bo{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new eh}clone(){const e=new eh;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,r){const i=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const t=[];for(const i in e.attributes){const s=[];for(const o in e.attributes[i])s.push({key:o,value:e.attributes[i][o]});s.sort((o,a)=>o.keyi.nodeName=0;i--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(EX)}}const iX=n=>new eh;class Rw{constructor(e,t){this.id=e,this.length=t}get deleted(){throw ka()}mergeWith(e){return!1}write(e,t,r){throw ka()}integrate(e,t){throw ka()}}const sX=0;class Fs extends Rw{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),$P(e.doc.store,this)}write(e,t){e.writeInfo(sX),e.writeLen(this.length-t)}getMissing(e,t){return null}}class xm{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new xm(this.content)}splice(e){throw ka()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}const oX=n=>new xm(n.readBuf());class $p{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new $p(this.len)}splice(e){const t=new $p(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){rv(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}const aX=n=>new $p(n.readLen()),hD=(n,e)=>new Zc({guid:n,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Sm{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Sm(hD(this.doc.guid,this.opts))}splice(e){throw ka()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const cX=n=>new Sm(hD(n.readString(),n.readAny()));class vh{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new vh(this.embed)}splice(e){throw ka()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}const lX=n=>new vh(n.readJSON());class qr{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new qr(this.key,this.value)}splice(e){throw ka()}mergeWith(e){return!1}integrate(e,t){const r=t.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const uX=n=>new qr(n.readKey(),n.readJSON());class av{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new av(this.arr)}splice(e){const t=new av(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const r=this.arr.length;e.writeLen(r-t);for(let i=t;i{const e=n.readLen(),t=[];for(let r=0;r{const e=n.readLen(),t=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"�",t.str="�"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}}const pX=n=>new Ba(n.readString()),mX=[$q,Xq,Qq,tX,eX,rX,iX],gX=0,_X=1,vX=2,yX=3,xX=4,SX=5,EX=6;class Jc{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Jc(this.type._copy())}splice(e){throw ka()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}const bX=n=>new Jc(mX[n.readTypeRef()](n)),cv=(n,e,t)=>{const{client:r,clock:i}=e.id,s=new Hr(ln(r,i+t),e,ln(r,i+t-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=ln(e.redone.client,e.redone.clock+t)),e.right=s,s.right!==null&&(s.right.left=s),n._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=t,s};class Hr extends Rw{constructor(e,t,r,i,s,o,a,c){super(e,c.getLength()),this.origin=r,this.left=t,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?B2:0}set marker(e){(this.info&g1)>0!==e&&(this.info^=g1)}get marker(){return(this.info&g1)>0}get keep(){return(this.info&F2)>0}set keep(e){this.keep!==e&&(this.info^=F2)}get countable(){return(this.info&B2)>0}get deleted(){return(this.info&m1)>0}set deleted(e){this.deleted!==e&&(this.info^=m1)}markDeleted(){this.info|=m1}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=li(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=li(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Df&&this.id.client!==this.parent.client&&this.parent.clock>=li(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Q2(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=jl(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Fs||this.right&&this.right.constructor===Fs)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Hr&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===Hr&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Df){const r=x1(t,this.parent);r.constructor===Fs?this.parent=null:this.parent=r.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Q2(e,e.doc.store,ln(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),D0(this.origin,i.origin)){if(i.id.client{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),rv(e.deleteSet,this.id.client,this.id.clock,this.length),tk(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Da();this.content.gc(e),t?Cq(e,this,new Fs(this.id,this.length)):this.content=new $p(this.length)}write(e,t){const r=t>0?ln(this.id.client,this.id.clock+t-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&ay|(r===null?0:Vs)|(i===null?0:Pc)|(s===null?0:Bp);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const a=this.parent;if(a._item!==void 0){const c=a._item;if(c===null){const l=Aq(a);e.writeParentInfo(!0),e.writeString(l)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else a.constructor===String?(e.writeParentInfo(!0),e.writeString(a)):a.constructor===Df?(e.writeParentInfo(!1),e.writeLeftID(a)):Da();s!==null&&e.writeString(s)}this.content.write(e,t)}}const fD=(n,e)=>TX[e&ay](n),TX=[()=>{Da()},aX,hX,oX,pX,lX,uX,bX,dX,cX,()=>{Da()}],wX=10;class so extends Rw{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,t){Da()}write(e,t){e.writeInfo(wX),jt(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const dD=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},pD="__ $YJS$ __";dD[pD]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");dD[pD]=!0;let _b,vb,AX=n=>n();function MX(n,e){if(vb)return vb(n,e);AX(n)}function nh(n,e,t){if(_b)return _b.apply(null,arguments);throw new Error("observable implementation not provided. Call enableReactiveBindings, enableVueBindings or enableMobxBindings.")}function CX(n){_b=function(e,t,r){const i=n.createAtom(e);return t&&t(),i},vb=(e,t)=>n.reaction(e,t,{fireImmediately:!1})}const ok=new WeakSet;function RX(n){if(ok.has(n))return n;ok.add(n);let e;const t=new Map;function r(){if(!e){const h=d=>{(d.changes.added.size||d.changes.deleted.size||d.changes.keys.size||d.changes.delta.length)&&e.reportChanged()};e=nh("map",()=>{n.observe(h)},()=>{n.unobserve(h)})}e.reportObserved(n._implicitObserver)}function i(h){let d=t.get(h);if(!d){const m=g=>{d.reportChanged()};d=nh(h+"",()=>{n.observe(m)},()=>{n.unobserve(m)}),t.set(h,d)}d.reportObserved(n._implicitObserver)}const s=n.get;n.get=function(h){if(typeof h!="number")throw new Error("unexpected");return i(h),Reflect.apply(s,this,arguments)};function o(h){const d=n[h];n[h]=function(){return r(),Reflect.apply(d,this,arguments)}}function a(h){let d=n,m=Object.getOwnPropertyDescriptor(d,h);if(m||(d=Object.getPrototypeOf(d),m=Object.getOwnPropertyDescriptor(d,h)),m||(d=Object.getPrototypeOf(d),m=Object.getOwnPropertyDescriptor(d,h)),!m)throw new Error("property not found");const g=m.get;m.get=function(){return this._disableTracking||r(),Reflect.apply(g,this,arguments)},Object.defineProperty(n,h,m)}function c(h,d){let m=n,g=Object.getOwnPropertyDescriptor(m,h);if(g||(m=Object.getPrototypeOf(m),g=Object.getOwnPropertyDescriptor(m,h)),g||(m=Object.getPrototypeOf(m),g=Object.getOwnPropertyDescriptor(m,h)),!g)throw new Error("property not found");Object.defineProperty(n,d,g)}o("forEach"),o("toJSON"),o("toArray"),o("slice"),o("map"),c("length","lengthUntracked"),a("length");const l=n.push;n.push=function(h){this._disableTracking=!0;const d=l.call(this,h);return this._disableTracking=!1,d};const u=n.slice;return n.slice=function(h,d){this._disableTracking=!0;const m=u.call(this,h,d);return this._disableTracking=!1,m},n}const ak=new WeakSet;function kX(n){if(ak.has(n))return n;ak.add(n);let e;function t(){if(!e){let s=Array.from(n.share.keys());const o=a=>{const c=Array.from(n.share.keys());JSON.stringify(s)!==JSON.stringify(c)&&(s=c,e.reportChanged())};e=nh("map",()=>{n.on("beforeObserverCalls",o)},()=>{n.off("beforeObserverCalls",o)})}e.reportObserved(n._implicitObserver)}const r=n.get;n.get=function(s){if(typeof s!="string")throw new Error("unexpected");const o=Reflect.apply(r,this,arguments);return py(o),o};function i(s){const o=n[s];let a;n[s]=function(){let c,l=arguments;return t(),a&&a.removeObservers(),a=MX(()=>(c=Reflect.apply(o,n,l),c),()=>e.reportChanged()),c}}return i("toJSON"),Object.defineProperty(n,"keys",{get:()=>(t(),Object.keys(n.share))}),n}const ck=new WeakSet;function NX(n){if(ck.has(n))return n;ck.add(n);let e;const t=new Map;function r(){if(!e){const a=c=>{(c.changes.added.size||c.changes.deleted.size||c.changes.keys.size||c.changes.delta.length)&&e.reportChanged()};e=nh("map",()=>{n.observe(a)},()=>{n.unobserve(a)})}e.reportObserved(n._implicitObserver)}function i(a){let c=t.get(a);if(!c){const l=u=>{u.keysChanged.has(a)&&(u.changes.added.size||u.changes.deleted.size||u.changes.keys.size||u.changes.delta.length)&&c.reportChanged()};c=nh(a,()=>{n.observe(l)},()=>{n.unobserve(l)}),t.set(a,c)}c.reportObserved(n._implicitObserver)}const s=n.get;n.get=function(a){if(typeof a!="string")throw new Error("unexpected");return i(a),Reflect.apply(s,this,arguments)};function o(a){const c=n[a];n[a]=function(){return r(),Reflect.apply(c,this,arguments)}}return o("values"),o("entries"),o("keys"),o("forEach"),o("toJSON"),n}const lk=new WeakSet;function uk(n){if(lk.has(n))return n;lk.add(n);let e;const t=i=>{e.reportChanged()};e=nh("text",()=>{n.observe(t)},()=>{n.unobserve(t)});function r(i){const s=n[i];n[i]=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(s,this,arguments)}}return r("toString"),r("toJSON"),n}const hk=new WeakSet;function fk(n){if(hk.has(n))return n;hk.add(n);let e;const t=s=>{(s.changes.added.size||s.changes.deleted.size||s.changes.keys.size||s.changes.delta.length)&&e.reportChanged()};e=nh("xml",()=>{n.observe(t)},()=>{n.unobserve(t)});function r(s){const o=n[s];n[s]=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(o,this,arguments)}}function i(s){let o=n,a=Object.getOwnPropertyDescriptor(o,s);if(a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),!a)throw new Error("property not found");const c=a.get;a.get=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(c,this,arguments)},Object.defineProperty(n,s,a)}return r("toString"),r("toDOM"),r("toArray"),r("getAttribute"),i("firstChild"),n}function py(n){return n instanceof eh||n instanceof Bo?uk(n):n instanceof Na?RX(n):n instanceof Ua?NX(n):n instanceof Zc||Object.prototype.hasOwnProperty.call(n,"autoLoad")?kX(n):n instanceof Fa||n instanceof Hc?fk(n):n}function dk(n){n.share.forEach(e=>{e.constructor!==fr&&py(e)})}function pk(n,e){for(let r=n.length-1;r>=e;r--){let i=n[r];if(!i.deleted){var t;if(i instanceof Fs)continue;(t=i.content)==null||t.getContent().forEach(s=>{s instanceof fr&&py(s)})}}}const mk=new WeakSet;function IX(n){mk.has(n)||(mk.add(n),py(n),n.store.clients.forEach(e=>{e&&pk(e,0)}),dk(n),n.on("beforeObserverCalls",e=>{dk(n),e.afterState.forEach((t,r)=>{const i=e.beforeState.get(r)||0;if(i!==t){const s=e.doc.store.clients.get(r);if(!s)return;const o=Fo(s,i);pk(s,o)}})}))}class qp{constructor(e){this.value=void 0,this.value=e}}function OX(n){return ArrayBuffer.isView(n)?new qp(n):new qp(Object.freeze(n))}function LX(n){const e=function(){var a;let c=(a=this[mo])==null?void 0:a.implicitObserver;return n._implicitObserver=c,n.slice.bind(n).apply(n,arguments).map(u=>{const h=my(u,c);return c&&typeof h=="object"?Zf(h,c):h})},t=function(a){return a.map(c=>{const l=kw(c);let u=$l(l)||l;if(u instanceof qp&&(u=u.value),u instanceof fr&&u.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return u})},r=function(){return[].findIndex.apply(e.apply(this),arguments)},i={slice:e,unshift:(...o)=>(n.unshift(t(o)),n.lengthUntracked),push:(...o)=>(n.push(t(o)),n.lengthUntracked),insert:n.insert.bind(n),toJSON:n.toJSON.bind(n),forEach:function(){return[].forEach.apply(e.apply(this),arguments)},every:function(){return[].every.apply(e.apply(this),arguments)},filter:function(){return[].filter.apply(e.apply(this),arguments)},find:function(){return[].find.apply(e.apply(this),arguments)},findIndex:r,some:function(){return[].some.apply(e.apply(this),arguments)},includes:function(){return[].includes.apply(e.apply(this),arguments)},map:function(){return[].map.apply(e.apply(this),arguments)},indexOf:function(){const o=arguments[0];return r.call(this,a=>BX(a,o))},splice:function(){let o=arguments[0]<0?n.length-Math.abs(arguments[0]):arguments[0],a=arguments[1],c=Array.from(Array.from(arguments).slice(2)),l=e.apply(this,[o,Number.isInteger(a)?o+a:void 0]);return n.doc?n.doc.transact(()=>{n.delete(o,a),n.insert(o,t(c))}):(n.delete(o,a),n.insert(o,t(c))),l}},s=[];for(let o in i)s[o]=i[o];return s}function rp(n){if(typeof n=="string"&&n.trim().length){const e=Number(n);if(Number.isInteger(e))return e}return n}function gk(n,e=new Na){if(e[Gr])throw new Error("unexpected");const t=LX(e),r=new Proxy(t,{set:(i,s,o)=>{throw typeof rp(s)!="number"?new Error:new Error("array assignment is not implemented / supported")},get:(i,s,o)=>{const a=rp(s);if(a===gy)return e;if(typeof a=="number"){let u;if(o&&o[mo]){var c;u=(c=o[mo])==null?void 0:c.implicitObserver,e._implicitObserver=u}let h=e.get(a);return h=my(h,u),h}if(a===Symbol.toStringTag)return"Array";if(a===Symbol.iterator){const u=e.slice();return Reflect.get(u,a)}return a==="length"?e.length:Reflect.get(i,a,o)},deleteProperty:(i,s)=>{const o=rp(s);if(typeof o!="number")throw new Error;return o=0?(e.delete(o),!0):!1},has:(i,s)=>{const o=rp(s);return typeof o!="number"?Reflect.has(i,o):o=0},getOwnPropertyDescriptor(i,s){const o=rp(s);if(o==="length")return{enumerable:!1,configurable:!1,writable:!0};if(typeof o=="number"&&o>=0&&o{const s=[];for(let o=0;o{if(typeof i!="string")throw new Error;const o=kw(s);let a=$l(o)||o;if(a instanceof qp&&(a=a.value),a instanceof fr&&a.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return e.set(i,a),!0},get:(r,i,s)=>{if(i===gy)return e;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[mo]){var a;o=(a=s[mo])==null?void 0:a.implicitObserver,e._implicitObserver=o}let c=e.get(i);return c=my(c,o),c},deleteProperty:(r,i)=>{if(typeof i!="string")throw new Error;return e.has(i)?(e.delete(i),!0):!1},has:(r,i)=>!!(typeof i=="string"&&e.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&e.has(i))return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(e.keys())});Rp.set(e,t);for(let r in n)t[r]=n[r];return t}function PX(n){return n instanceof fr}const Rp=new WeakMap;function my(n,e){if(PX(n)){if(n._implicitObserver=e,n instanceof Na||n instanceof Ua){if(!Rp.has(n)){const t=kw(n);Rp.set(n,t)}n=Rp.get(n)}else if(n instanceof Hc||n instanceof Fa||n instanceof eh||n instanceof td||n instanceof Bo)fw(n),n.__v_skip=!0;else throw new Error("unknown YType");return n}else{if(n===null)return null;if(typeof n=="object")return OX(n)}return n}function kw(n){if(n==null)return n;if(n=$l(n)||n,n instanceof Na)return gk([],n);if(n instanceof Ua)return _k({},n);if(typeof n=="string")return n;if(Array.isArray(n))return gk(n);if(n instanceof Hc||n instanceof Fa||n instanceof eh||n instanceof td)return n;if(n instanceof Bo)return n;if(typeof n=="object")return n instanceof qp?n:_k(n);if(typeof n=="number"||typeof n=="boolean")return n;throw new Error("invalid")}function DX(n){for(let[e,t]of Object.entries(n))if(Array.isArray(t)){if(t.length!==0)throw new Error("Root Array initializer must always be empty array")}else if(t&&typeof t=="object"){if(Object.keys(t).length!==0||Object.getPrototypeOf(t)!==Object.prototype)throw new Error("Root Object initializer must always be {}")}else if(t!=="xml"&&t!=="text")throw new Error("unknown Root initializer")}function vk(n,e,t){let r=e[t];if(!r){t!=="__v_raw"&&t!=="__v_isRef"&&t!=="__v_isReadonly"&&console.warn("property not found on root doc",t);return}return r==="xml"?n.getXmlFragment(t):r==="text"?n.getText(t):Array.isArray(r)?n.getArray(t):n.getMap(t)}function UX(n,e){if(n[Gr])throw new Error("unexpected");DX(e);const t=new Proxy({},{set:(r,i,s)=>{throw typeof i!="string"?new Error:new Error("cannot set new elements on root doc")},get:(r,i,s)=>{if(i===gy)return n;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[mo]){var a;o=(a=s[mo])==null?void 0:a.implicitObserver,n._implicitObserver=o}if(i==="toJSON"){for(let u of Object.keys(e))vk(n,e,u);return Reflect.get(n,i)}let c=vk(n,e,i);return c=my(c,o),c},deleteProperty:(r,i)=>{throw new Error("deleteProperty not available for doc")},has:(r,i)=>!!(typeof i=="string"&&n.share.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&n.share.has(i)||i==="toJSON")return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(n.share.keys())});return Rp.set(n,t),t}CX(q$);const gy=Symbol("INTERNAL_SYMBOL");function yk(n,e){const t=$l(n)||n;if(!t)throw new Error("not a valid synced object");return t instanceof Zc?(t.on("update",e),()=>{t.off("update",e)}):(t.observeDeep(e),()=>{t.unobserveDeep(e)})}function FX(n){const e=$l(n);if(!(e instanceof Zc))throw new Error("store is not a valid syncedStore that maps to a Y.Doc");return e}function $l(n){if(typeof n!="object"||n===null)return;const e=n[gy];return e&&(fw(e),e.__v_skip=!0),e}function BX(n,e){if(n===e)return!0;if(typeof n=="object"&&typeof e=="object"){const t=$l(n),r=$l(e);return!t||!r?!1:t===r}return!1}function zX(n,e=new Zc){return IX(e),UX(e,n)}function VX(n,e){var t=ke.useReducer(function(a){return a+1},0),r=t[1],i=ke.useRef(),s=ke.useRef(!1);i.current||(i.current=new uw(function(){s.current&&r()}));var o=ke.useMemo(function(){var a;return(a=i.current)==null||a.removeObservers(),Zf(n,i.current)},[]);return ke.useEffect(function(){return s.current=!0,i.current||r(),function(){var a;s.current=!1,(a=i.current)==null||a.removeObservers(),i.current=null}},[]),o}function HX(n,e){if(!$l(n))throw new Error("syncedObject passed to useSyncedStore is not a SyncedStore Store or internal data type.");return VX(n)}const Nw=0,mD=1,gD=2,GX=(n,e)=>{jt(n,Nw);const t=Tq(e);bi(n,t)},_D=(n,e,t)=>{jt(n,mD),bi(n,xq(e,t))},WX=(n,e,t)=>_D(e,t,Ui(n)),vD=(n,e,t)=>{try{_q(e,Ui(n),t)}catch(r){console.error("Caught error while handling a Yjs update",r)}},jX=(n,e)=>{jt(n,gD),bi(n,e)},$X=vD,qX=(n,e,t,r)=>{const i=$t(n);switch(i){case Nw:WX(n,e,t);break;case mD:vD(n,t,r);break;case gD:$X(n,t,r);break;default:throw new Error("Unknown message type")}return i},za=zX({shared:[]});function Em(n,e,t){return n.find(r=>r.key===e&&r.type===t)}function XX(){return HX(za)}function yD(n,e){const t=XX(),r=Em(t.shared,n,e);return Z(r)?r:void 0}function Iw(n){return yD(n,0)}function xD(n){return yD(n,1)}function SD(n,e,t){const r=Em(za.shared,n,e);Z(r)||za.shared.push({key:n,type:e,value:t})}function KX(n,e){SD(n,0,e)}function ED(n,e){const t=new Bo(e);SD(n,1,t)}function Pl(n,e){const t=Em(za.shared,n,0);if(Z(t)){t.value=e;return}za.shared.push({key:n,type:0,value:e})}function YX(n,e){const t=new Bo(e),r=Em(za.shared,n,1);if(Z(r)){r.value=t;return}za.shared.push({key:n,type:1,value:t})}function bD(n,e,t){let r;function i(){const o=Em(za.shared,n,e);Z(o)&&(s(),r=yk(o,()=>t(o.value)))}const s=yk(za.shared,i);return i(),()=>r==null?void 0:r()}function ZX(n,e){return bD(n,0,e)}function JX(n,e){return bD(n,1,t=>e(t.toJSON()))}function T_(n){return Oo(n)}const Il=FX(za),da=mh("modem",["second"],n=>{switch(n.target){case"second":break;case"join":if(n.sender!==da.id()){da.reply(n,"joinack");const e=Ll();GX(e,Il),da.reply(n,"sync",T_(e));const t=Ll();_D(t,Il),da.reply(n,"sync",T_(t))}break;case"joinack":n.sender,da.id();break;case"sync":{if(n.sender!==da.id()&&Z(n.data))try{const e=_h(n.data),t=Ll();qX(e,t,Il,da)===Nw&&da.emit("modem:sync",T_(t))}catch(e){An(da.name(),"sync",e.message)}break}}});function TD(n){const e=Ll();jX(e,n),da.emit("modem:sync",T_(e))}Il.on("update",TD);Il.on("destroy",()=>{Il==null||Il.off("update",TD)});async function QX(n){return n$(n)}async function eK(n,e){return r$(n,e)}function tK(n){try{return sessionStorage.getItem(n)??void 0}catch(e){An(rr.name(),`readsession ${n}`,e.message)}}function nK(n,e){try{Z(e)?sessionStorage.setItem(n,e):sessionStorage.removeItem(n)}catch(t){An(rr.name(),`writesession ${n} <- ${e}`,t.message)}}function xk(){try{const n=location.hash.slice(1);if(n.length)return n}catch(n){An("register","crash",n.message)}return""}let yb=!0;window.addEventListener("hashchange",()=>{yb?location.reload():yb=!0});function rK(n){const e=`#${n}`;location.hash!==e&&(yb=!1,location.hash=e,lo(rr.name(),`wrote ${(n==null?void 0:n.length)??0} chars [${n.slice(0,8)}...${n.slice(-8)}]`))}async function iK(){return QX("SELECTED_ID")}async function sK(n){return eK("SELECTED_ID",()=>n)}let b1=0;const Sk=1,Rr=tK("SESSION_ID")??HL();nK("SESSION_ID",Rr);function Xi(){return Rr}const rr=mh("register",["started","second","error"],function(n){switch(n.target){case"ready":{un("register","creating platform"),u$(L2());break}case"started":{_a("register:started",async()=>{await mc(256),un("register",`sessionid ${Rr}`),P9("register",Rr)});break}case"error:login:main":case"error:login:title":case"error:login:player":n.player===Rr&&O2(rr.name(),Rr);break;case"ackinit":{_a("register:ackinit",async()=>{if(n.player===Rr)if(L2())qL(rr.name(),Rr),jL(rr.name(),xk(),n.player);else{const e=xk();if(e.length===0){An(rr.name(),"content","no content found"),O2(rr.name(),Rr);return}const t=await iK()??"";X9(rr.name(),e,t,n.player)}});break}case"ackbooks":n.player===Rr&&K9(rr.name(),n.player);break;case"acklogin":_a("register:acklogin",async()=>{if(n.player===Rr){const{player:e}=n;await mc(128),O9(rr.name(),e),await mc(512),iw(rr.name(),Rr)}});break;case"dev":n.player===Rr&&_a("register:dev",async function(){if(o$()){const e=await eb(location.href);rb("devshare",e,e)}else Mc(rr.name(),"creating locked terminal"),await mc(100),location.href=location.href.replace("/#","/locked/#")});break;case"share":n.player===Rr&&_a("register:share",async function(){const e=await eb(location.href.replace(/cafe.*locked/,"cafe"));rb("share",e,e)});break;case"refresh":n.player===Rr&&_a("register:refresh",async function(){Mc(rr.name(),"BYE"),await mc(100),location.reload()});break;case"nuke":n.player===Rr&&_a("register:nuke",async function(){Mc(rr.name(),"nuke in"),sn(rr.name(),"3","..."),await mc(1e3),sn(rr.name(),"2","..."),await mc(1e3),sn(rr.name(),"1","..."),await mc(1e3),Mc(rr.name(),"BYE"),await mc(100),location.hash="",location.reload()});break;case"flush":if(n.player===Rr&&cn(n.data)){const[e,t]=n.data;Bt(e)&&Bt(t)&&(document.title=e,rK(t))}break;case"select":n.player===Rr&&_a("register:select",async()=>{Bt(n.data)&&(await sK(n.data),z9(rr.name(),Rr))});break;case"second":++b1,b1>=Sk&&(b1-=Sk,Z9(rr.name(),Xi()));break}});setTimeout(()=>D9(rr.name(),Rr),100);function rh(n){"@babel/helpers - typeof";return rh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},rh(n)}function Ps(){Ps=function(){return e};var n,e={},t=Object.prototype,r=t.hasOwnProperty,i=Object.defineProperty||function(V,B,z){V[B]=z.value},s=typeof Symbol=="function"?Symbol:{},o=s.iterator||"@@iterator",a=s.asyncIterator||"@@asyncIterator",c=s.toStringTag||"@@toStringTag";function l(V,B,z){return Object.defineProperty(V,B,{value:z,enumerable:!0,configurable:!0,writable:!0}),V[B]}try{l({},"")}catch{l=function(z,W,K){return z[W]=K}}function u(V,B,z,W){var K=B&&B.prototype instanceof _?B:_,j=Object.create(K.prototype),Y=new w(W||[]);return i(j,"_invoke",{value:I(V,z,Y)}),j}function h(V,B,z){try{return{type:"normal",arg:V.call(B,z)}}catch(W){return{type:"throw",arg:W}}}e.wrap=u;var d="suspendedStart",m="suspendedYield",g="executing",v="completed",y={};function _(){}function S(){}function E(){}var T={};l(T,o,function(){return this});var k=Object.getPrototypeOf,R=k&&k(k(H([])));R&&R!==t&&r.call(R,o)&&(T=R);var M=E.prototype=_.prototype=Object.create(T);function O(V){["next","throw","return"].forEach(function(B){l(V,B,function(z){return this._invoke(B,z)})})}function C(V,B){function z(K,j,Y,ge){var Q=h(V[K],V,j);if(Q.type!=="throw"){var re=Q.arg,be=re.value;return be&&rh(be)=="object"&&r.call(be,"__await")?B.resolve(be.__await).then(function(Ae){z("next",Ae,Y,ge)},function(Ae){z("throw",Ae,Y,ge)}):B.resolve(be).then(function(Ae){re.value=Ae,Y(re)},function(Ae){return z("throw",Ae,Y,ge)})}ge(Q.arg)}var W;i(this,"_invoke",{value:function(j,Y){function ge(){return new B(function(Q,re){z(j,Y,Q,re)})}return W=W?W.then(ge,ge):ge()}})}function I(V,B,z){var W=d;return function(K,j){if(W===g)throw Error("Generator is already running");if(W===v){if(K==="throw")throw j;return{value:n,done:!0}}for(z.method=K,z.arg=j;;){var Y=z.delegate;if(Y){var ge=U(Y,z);if(ge){if(ge===y)continue;return ge}}if(z.method==="next")z.sent=z._sent=z.arg;else if(z.method==="throw"){if(W===d)throw W=v,z.arg;z.dispatchException(z.arg)}else z.method==="return"&&z.abrupt("return",z.arg);W=g;var Q=h(V,B,z);if(Q.type==="normal"){if(W=z.done?v:m,Q.arg===y)continue;return{value:Q.arg,done:z.done}}Q.type==="throw"&&(W=v,z.method="throw",z.arg=Q.arg)}}}function U(V,B){var z=B.method,W=V.iterator[z];if(W===n)return B.delegate=null,z==="throw"&&V.iterator.return&&(B.method="return",B.arg=n,U(V,B),B.method==="throw")||z!=="return"&&(B.method="throw",B.arg=new TypeError("The iterator does not provide a '"+z+"' method")),y;var K=h(W,V.iterator,B.arg);if(K.type==="throw")return B.method="throw",B.arg=K.arg,B.delegate=null,y;var j=K.arg;return j?j.done?(B[V.resultName]=j.value,B.next=V.nextLoc,B.method!=="return"&&(B.method="next",B.arg=n),B.delegate=null,y):j:(B.method="throw",B.arg=new TypeError("iterator result is not an object"),B.delegate=null,y)}function L(V){var B={tryLoc:V[0]};1 in V&&(B.catchLoc=V[1]),2 in V&&(B.finallyLoc=V[2],B.afterLoc=V[3]),this.tryEntries.push(B)}function P(V){var B=V.completion||{};B.type="normal",delete B.arg,V.completion=B}function w(V){this.tryEntries=[{tryLoc:"root"}],V.forEach(L,this),this.reset(!0)}function H(V){if(V||V===""){var B=V[o];if(B)return B.call(V);if(typeof V.next=="function")return V;if(!isNaN(V.length)){var z=-1,W=function K(){for(;++z=0;--K){var j=this.tryEntries[K],Y=j.completion;if(j.tryLoc==="root")return W("end");if(j.tryLoc<=this.prev){var ge=r.call(j,"catchLoc"),Q=r.call(j,"finallyLoc");if(ge&&Q){if(this.prev=0;--W){var K=this.tryEntries[W];if(K.tryLoc<=this.prev&&r.call(K,"finallyLoc")&&this.prev=0;--z){var W=this.tryEntries[z];if(W.finallyLoc===B)return this.complete(W.completion,W.afterLoc),P(W),y}},catch:function(B){for(var z=this.tryEntries.length-1;z>=0;--z){var W=this.tryEntries[z];if(W.tryLoc===B){var K=W.completion;if(K.type==="throw"){var j=K.arg;P(W)}return j}}throw Error("illegal catch attempt")},delegateYield:function(B,z,W){return this.delegate={iterator:H(B),resultName:z,nextLoc:W},this.method==="next"&&(this.arg=n),y}},e}function Ek(n,e,t,r,i,s,o){try{var a=n[s](o),c=a.value}catch(l){return void t(l)}a.done?e(c):Promise.resolve(c).then(r,i)}function Uf(n){return function(){var e=this,t=arguments;return new Promise(function(r,i){var s=n.apply(e,t);function o(c){Ek(s,r,i,o,a,"next",c)}function a(c){Ek(s,r,i,o,a,"throw",c)}o(void 0)})}}function oK(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}function aK(n,e){if(rh(n)!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var r=t.call(n,e||"default");if(rh(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function wD(n){var e=aK(n,"string");return rh(e)=="symbol"?e:e+""}function cK(n,e){for(var t=0;tn.length)&&(e=n.length);for(var t=0,r=Array(e);tn==null,SK=n=>encodeURIComponent(n).replaceAll(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Sb=Symbol("encodeFragmentIdentifier");function EK(n){switch(n.arrayFormat){case"index":return e=>(t,r)=>{const i=t.length;return r===void 0||n.skipNull&&r===null||n.skipEmptyString&&r===""?t:r===null?[...t,[kr(e,n),"[",i,"]"].join("")]:[...t,[kr(e,n),"[",kr(i,n),"]=",kr(r,n)].join("")]};case"bracket":return e=>(t,r)=>r===void 0||n.skipNull&&r===null||n.skipEmptyString&&r===""?t:r===null?[...t,[kr(e,n),"[]"].join("")]:[...t,[kr(e,n),"[]=",kr(r,n)].join("")];case"colon-list-separator":return e=>(t,r)=>r===void 0||n.skipNull&&r===null||n.skipEmptyString&&r===""?t:r===null?[...t,[kr(e,n),":list="].join("")]:[...t,[kr(e,n),":list=",kr(r,n)].join("")];case"comma":case"separator":case"bracket-separator":{const e=n.arrayFormat==="bracket-separator"?"[]=":"=";return t=>(r,i)=>i===void 0||n.skipNull&&i===null||n.skipEmptyString&&i===""?r:(i=i===null?"":i,r.length===0?[[kr(t,n),e,kr(i,n)].join("")]:[[r,kr(i,n)].join(n.arrayFormatSeparator)])}default:return e=>(t,r)=>r===void 0||n.skipNull&&r===null||n.skipEmptyString&&r===""?t:r===null?[...t,kr(e,n)]:[...t,[kr(e,n),"=",kr(r,n)].join("")]}}function bK(n){let e;switch(n.arrayFormat){case"index":return(t,r,i)=>{if(e=/\[(\d*)]$/.exec(t),t=t.replace(/\[\d*]$/,""),!e){i[t]=r;return}i[t]===void 0&&(i[t]={}),i[t][e[1]]=r};case"bracket":return(t,r,i)=>{if(e=/(\[])$/.exec(t),t=t.replace(/\[]$/,""),!e){i[t]=r;return}if(i[t]===void 0){i[t]=[r];return}i[t]=[...i[t],r]};case"colon-list-separator":return(t,r,i)=>{if(e=/(:list)$/.exec(t),t=t.replace(/:list$/,""),!e){i[t]=r;return}if(i[t]===void 0){i[t]=[r];return}i[t]=[...i[t],r]};case"comma":case"separator":return(t,r,i)=>{const s=typeof r=="string"&&r.includes(n.arrayFormatSeparator),o=typeof r=="string"&&!s&&wc(r,n).includes(n.arrayFormatSeparator);r=o?wc(r,n):r;const a=s||o?r.split(n.arrayFormatSeparator).map(c=>wc(c,n)):r===null?r:wc(r,n);i[t]=a};case"bracket-separator":return(t,r,i)=>{const s=/(\[])$/.test(t);if(t=t.replace(/\[]$/,""),!s){i[t]=r&&wc(r,n);return}const o=r===null?[]:wc(r,n).split(n.arrayFormatSeparator);if(i[t]===void 0){i[t]=o;return}i[t]=[...i[t],...o]};default:return(t,r,i)=>{if(i[t]===void 0){i[t]=r;return}i[t]=[...[i[t]].flat(),r]}}}function RD(n){if(typeof n!="string"||n.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function kr(n,e){return e.encode?e.strict?SK(n):encodeURIComponent(n):n}function wc(n,e){return e.decode?vK(n):n}function kD(n){return Array.isArray(n)?n.sort():typeof n=="object"?kD(Object.keys(n)).sort((e,t)=>Number(e)-Number(t)).map(e=>n[e]):n}function ND(n){const e=n.indexOf("#");return e!==-1&&(n=n.slice(0,e)),n}function TK(n){let e="";const t=n.indexOf("#");return t!==-1&&(e=n.slice(t)),e}function Ak(n,e,t){return t==="string"&&typeof n=="string"?n:typeof t=="function"&&typeof n=="string"?t(n):e.parseBooleans&&n!==null&&(n.toLowerCase()==="true"||n.toLowerCase()==="false")?n.toLowerCase()==="true":t==="number"&&!Number.isNaN(Number(n))&&typeof n=="string"&&n.trim()!==""||e.parseNumbers&&!Number.isNaN(Number(n))&&typeof n=="string"&&n.trim()!==""?Number(n):n}function Lw(n){n=ND(n);const e=n.indexOf("?");return e===-1?"":n.slice(e+1)}function Pw(n,e){e={decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1,types:Object.create(null),...e},RD(e.arrayFormatSeparator);const t=bK(e),r=Object.create(null);if(typeof n!="string"||(n=n.trim().replace(/^[?#&]/,""),!n))return r;for(const i of n.split("&")){if(i==="")continue;const s=e.decode?i.replaceAll("+"," "):i;let[o,a]=CD(s,"=");o===void 0&&(o=s),a=a===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?a:wc(a,e),t(wc(o,e),a,r)}for(const[i,s]of Object.entries(r))if(typeof s=="object"&&s!==null&&e.types[i]!=="string")for(const[o,a]of Object.entries(s)){const c=e.types[i]?e.types[i].replace("[]",""):void 0;s[o]=Ak(a,e,c)}else typeof s=="object"&&s!==null&&e.types[i]==="string"?r[i]=Object.values(s).join(e.arrayFormatSeparator):r[i]=Ak(s,e,e.types[i]);return e.sort===!1?r:(e.sort===!0?Object.keys(r).sort():Object.keys(r).sort(e.sort)).reduce((i,s)=>{const o=r[s];return i[s]=o&&typeof o=="object"&&!Array.isArray(o)?kD(o):o,i},Object.create(null))}function ID(n,e){if(!n)return"";e={encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:",",...e},RD(e.arrayFormatSeparator);const t=o=>e.skipNull&&xK(n[o])||e.skipEmptyString&&n[o]==="",r=EK(e),i={};for(const[o,a]of Object.entries(n))t(o)||(i[o]=a);const s=Object.keys(i);return e.sort!==!1&&s.sort(e.sort),s.map(o=>{const a=n[o];return a===void 0?"":a===null?kr(o,e):Array.isArray(a)?a.length===0&&e.arrayFormat==="bracket-separator"?kr(o,e)+"[]":a.reduce(r(o),[]).join("&"):kr(o,e)+"="+kr(a,e)}).filter(o=>o.length>0).join("&")}function OD(n,e){var i;e={decode:!0,...e};let[t,r]=CD(n,"#");return t===void 0&&(t=n),{url:((i=t==null?void 0:t.split("?"))==null?void 0:i[0])??"",query:Pw(Lw(n),e),...e&&e.parseFragmentIdentifier&&r?{fragmentIdentifier:wc(r,e)}:{}}}function LD(n,e){e={encode:!0,strict:!0,[Sb]:!0,...e};const t=ND(n.url).split("?")[0]||"",r=Lw(n.url),i={...Pw(r,{sort:!1}),...n.query};let s=ID(i,e);s&&(s=`?${s}`);let o=TK(n.url);if(typeof n.fragmentIdentifier=="string"){const a=new URL(t);a.hash=n.fragmentIdentifier,o=e[Sb]?a.hash:`#${n.fragmentIdentifier}`}return`${t}${s}${o}`}function PD(n,e,t){t={parseFragmentIdentifier:!0,[Sb]:!1,...t};const{url:r,query:i,fragmentIdentifier:s}=OD(n,t);return LD({url:r,query:yK(i,e),fragmentIdentifier:s},t)}function wK(n,e,t){const r=Array.isArray(e)?i=>!e.includes(i):(i,s)=>!e(i,s);return PD(n,r,t)}const AK=Object.freeze(Object.defineProperty({__proto__:null,exclude:wK,extract:Lw,parse:Pw,parseUrl:OD,pick:PD,stringify:ID,stringifyUrl:LD},Symbol.toStringTag,{value:"Module"}));var fi=[];for(var T1=0;T1<256;++T1)fi.push((T1+256).toString(16).slice(1));function MK(n,e=0){return(fi[n[e+0]]+fi[n[e+1]]+fi[n[e+2]]+fi[n[e+3]]+"-"+fi[n[e+4]]+fi[n[e+5]]+"-"+fi[n[e+6]]+fi[n[e+7]]+"-"+fi[n[e+8]]+fi[n[e+9]]+"-"+fi[n[e+10]]+fi[n[e+11]]+fi[n[e+12]]+fi[n[e+13]]+fi[n[e+14]]+fi[n[e+15]]).toLowerCase()}var B0,CK=new Uint8Array(16);function RK(){if(!B0&&(B0=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!B0))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return B0(CK)}var kK=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Mk={randomUUID:kK};function NK(n,e,t){if(Mk.randomUUID&&!e&&!n)return Mk.randomUUID();n=n||{};var r=n.random||(n.rng||RK)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,MK(r)}var IK=function(e,t){var r=t.voice;return'').concat(e,"")},OK=function(e,t){var r=t.style;return r?'').concat(e,""):e},LK=function(e,t){var r=t.pitch,i=t.rate;return!r&&!i?e:'').concat(e,"")},PK=function(e){return''.concat(e,"")},DK=function(e,t){var r=LK(e,t);return r=OK(r,t),r=IK(r,t),r=PK(r),r},Ck=function(e,t){for(var r=[],i=0,s=Object.entries(e);i=n.length?{done:!0}:{done:!1,value:n[r++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s,o=!0,a=!1;return{s:function(){t=t.call(n)},n:function(){var l=t.next();return o=l.done,l},e:function(l){a=!0,s=l},f:function(){try{o||t.return==null||t.return()}finally{if(a)throw s}}}}var FK=function(e){var t={},r=UK(e.slice(0,e.indexOf(`\r +\r +`)).split(`\r +`)),i;try{for(r.s();!(i=r.n()).done;){var s=i.value,o=s.split(":",2),a=Ow(o,2),c=a[0],l=a[1];t[c]=l}}catch(u){r.e(u)}finally{r.f()}return{data:e.slice(e.indexOf(`\r +\r +`)+4),headers:t}},BK="wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1",zK="6A5AA1D4EAFF4E9FB37E23D68491D6F4",VK=JSON.stringify({context:{synthesis:{audio:{metadataoptions:{sentenceBoundaryEnabled:!1,wordBoundaryEnabled:!0},outputFormat:"audio-24khz-48kbitrate-mono-mp3"}}}}),HK=function(e){var t=new Date().toString(),r={"Content-Type":"application/json; charset=utf-8",Path:"speech.config","X-Timestamp":t},i={"Content-Type":"application/ssml+xml",Path:"ssml","X-RequestId":e,"X-Timestamp":t};return{configHeader:r,contentHeader:i}},DD=function(){var n=Uf(Ps().mark(function e(t){var r,i,s,o,a,c,l,u,h,d,m,g,v,y=arguments;return Ps().wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return r=t.payload,i=y.length>1&&y[1]!==void 0?y[1]:{},s=i.proxyUrl,o=i.token,a=r.input,c=r.options,l=NK().replaceAll("-",""),u=AK.stringifyUrl({query:{ConnectionId:l,TrustedClientToken:o||zK},url:s||BK}),h=HK(l),d=h.configHeader,m=h.contentHeader,g=Ck(d,VK),v=Ck(m,DK(a,c)),S.abrupt("return",new Promise(function(E,T){var k=new WebSocket(u);k.binaryType="arraybuffer";var R=function(){k.send(g),k.send(v)},M=new ArrayBuffer(0),O=function(){var I=Uf(Ps().mark(function U(L){var P,w,H,V,B,z,W,K;return Ps().wrap(function(Y){for(;;)switch(Y.prev=Y.next){case 0:if(typeof L.data!="string"){Y.next=13;break}P=FK(L.data),w=P.headers,Y.t0=w.Path,Y.next=Y.t0==="turn.end"?5:11;break;case 5:if(k.close(),M.byteLength){Y.next=8;break}return Y.abrupt("return");case 8:return H=new Response(M),E(H),Y.abrupt("break",11);case 11:Y.next=14;break;case 13:L.data instanceof ArrayBuffer&&(V=new DataView(L.data),B=V.getInt16(0),L.data.byteLength>B+2&&(z=L.data.slice(2+B),W=new ArrayBuffer(M.byteLength+z.byteLength),K=new Uint8Array(W),K.set(new Uint8Array(M),0),K.set(new Uint8Array(z),M.byteLength),M=W));case 14:case"end":return Y.stop()}},U)}));return function(L){return I.apply(this,arguments)}}(),C=function(){T(new Error("WebSocket error occurred.")),k.close()};k.addEventListener("open",R),k.addEventListener("message",O),k.addEventListener("error",C)}));case 9:case"end":return S.stop()}},e)}));return function(t){return n.apply(this,arguments)}}(),UD=typeof global=="object"&&global&&global.Object===Object&&global,GK=typeof self=="object"&&self&&self.Object===Object&&self,qa=UD||GK||Function("return this")(),go=qa.Symbol,FD=Object.prototype,WK=FD.hasOwnProperty,jK=FD.toString,ip=go?go.toStringTag:void 0;function $K(n){var e=WK.call(n,ip),t=n[ip];try{n[ip]=void 0;var r=!0}catch{}var i=jK.call(n);return r&&(e?n[ip]=t:delete n[ip]),i}var qK=Object.prototype,XK=qK.toString;function KK(n){return XK.call(n)}var YK="[object Null]",ZK="[object Undefined]",Rk=go?go.toStringTag:void 0;function tu(n){return n==null?n===void 0?ZK:YK:Rk&&Rk in Object(n)?$K(n):KK(n)}function zo(n){return n!=null&&typeof n=="object"}var JK="[object Symbol]";function _y(n){return typeof n=="symbol"||zo(n)&&tu(n)==JK}function vy(n,e){for(var t=-1,r=n==null?0:n.length,i=Array(r);++t0){if(++e>=kY)return arguments[0]}else e=0;return n.apply(void 0,arguments)}}function LY(n){return function(){return n}}var lv=function(){try{var n=xh(Object,"defineProperty");return n({},"",{}),n}catch{}}(),PY=lv?function(n,e){return lv(n,"toString",{configurable:!0,enumerable:!1,value:LY(e),writable:!0})}:nd,DY=OY(PY);function zD(n,e){for(var t=-1,r=n==null?0:n.length;++t-1}var BY=9007199254740991,zY=/^(?:0|[1-9]\d*)$/;function xy(n,e){var t=typeof n;return e=e??BY,!!e&&(t=="number"||t!="symbol"&&zY.test(n))&&n>-1&&n%1==0&&n-1&&n%1==0&&n<=WY}function Xa(n){return n!=null&&zw(n.length)&&!Qc(n)}function GD(n,e,t){if(!_o(t))return!1;var r=typeof e;return(r=="number"?Xa(t)&&xy(e,t.length):r=="string"&&e in t)?bm(t[e],n):!1}function jY(n){return Bw(function(e,t){var r=-1,i=t.length,s=i>1?t[i-1]:void 0,o=i>2?t[2]:void 0;for(s=n.length>3&&typeof s=="function"?(i--,s):void 0,o&&GD(t[0],t[1],o)&&(s=i<3?void 0:s,i=1),e=Object(e);++r-1}function nJ(n,e){var t=this.__data__,r=Ty(t,n);return r<0?(++this.size,t.push([n,e])):t[r][1]=e,this}function el(n){var e=-1,t=n==null?0:n.length;for(this.clear();++ei?0:i+e),t=t>i?i:t,t<0&&(t+=i),i=e>t?0:t-e>>>0,e>>>=0;for(var s=Array(i);++r=r?n:qw(n,e,t)}var yJ="\\ud800-\\udfff",xJ="\\u0300-\\u036f",SJ="\\ufe20-\\ufe2f",EJ="\\u20d0-\\u20ff",bJ=xJ+SJ+EJ,TJ="\\ufe0e\\ufe0f",wJ="\\u200d",AJ=RegExp("["+wJ+yJ+bJ+TJ+"]");function QD(n){return AJ.test(n)}function MJ(n){return n.split("")}var eU="\\ud800-\\udfff",CJ="\\u0300-\\u036f",RJ="\\ufe20-\\ufe2f",kJ="\\u20d0-\\u20ff",NJ=CJ+RJ+kJ,IJ="\\ufe0e\\ufe0f",OJ="["+eU+"]",bb="["+NJ+"]",Tb="\\ud83c[\\udffb-\\udfff]",LJ="(?:"+bb+"|"+Tb+")",tU="[^"+eU+"]",nU="(?:\\ud83c[\\udde6-\\uddff]){2}",rU="[\\ud800-\\udbff][\\udc00-\\udfff]",PJ="\\u200d",iU=LJ+"?",sU="["+IJ+"]?",DJ="(?:"+PJ+"(?:"+[tU,nU,rU].join("|")+")"+sU+iU+")*",UJ=sU+iU+DJ,FJ="(?:"+[tU+bb+"?",bb,nU,rU,OJ].join("|")+")",BJ=RegExp(Tb+"(?="+Tb+")|"+FJ+UJ,"g");function zJ(n){return n.match(BJ)||[]}function VJ(n){return QD(n)?zJ(n):MJ(n)}function HJ(n){return function(e){e=ZD(e);var t=QD(e)?VJ(e):void 0,r=t?t[0]:e.charAt(0),i=t?vJ(t,1).join(""):e.slice(1);return r[n]()+i}}var oU=HJ("toUpperCase");function GJ(n,e,t,r){var i=-1,s=n==null?0:n.length;for(r&&s&&(t=n[++i]);++ia))return!1;var l=s.get(n),u=s.get(e);if(l&&u)return l==e&&u==n;var h=-1,d=!0,m=t&See?new rd:void 0;for(s.set(n,e),s.set(e,n);++h2?e[2]:void 0;for(i&&GD(e[0],e[1],i)&&(r=1);++t=hte&&(s=Yw,o=!1,e=new rd(e));e:for(;++i-1?i[s?e[o]:o]:void 0}}var _te=Math.max;function vte(n,e,t){var r=n==null?0:n.length;if(!r)return-1;var i=t==null?0:yy(t);return i<0&&(i=_te(r+i,0)),VD(n,Ka(e),i)}var sd=gte(vte);function Vo(n){return n&&n.length?n[0]:void 0}function yte(n,e){var t=-1,r=Xa(n)?Array(n.length):[];return Sh(n,function(i,s,o){r[++t]=e(i,s,o)}),r}function ot(n,e){var t=fn(n)?vy:yte;return t(n,Ka(e))}function uo(n,e){return $w(ot(n,e))}var xte=Object.prototype,Ste=xte.hasOwnProperty,xU=lte(function(n,e,t){Ste.call(n,t)?n[t].push(e):Uw(n,t,[e])}),Ete=Object.prototype,bte=Ete.hasOwnProperty;function Tte(n,e){return n!=null&&bte.call(n,e)}function Tt(n,e){return n!=null&&_U(n,e,Tte)}var wte="[object String]";function xs(n){return typeof n=="string"||!fn(n)&&zo(n)&&tu(n)==wte}function Ate(n,e){return vy(e,function(t){return n[t]})}function Lr(n){return n==null?[]:Ate(n,vo(n))}var Mte=Math.max;function Qi(n,e,t,r){n=Xa(n)?n:Lr(n),t=t&&!r?yy(t):0;var i=n.length;return t<0&&(t=Mte(i+t,0)),xs(n)?t<=i&&n.indexOf(e,t)>-1:!!i&&Dw(n,e,t)>-1}function oN(n,e,t){var r=n==null?0:n.length;if(!r)return-1;var i=0;return Dw(n,e,i)}var Cte="[object Map]",Rte="[object Set]",kte=Object.prototype,Nte=kte.hasOwnProperty;function zn(n){if(n==null)return!0;if(Xa(n)&&(fn(n)||typeof n=="string"||typeof n.splice=="function"||Xp(n)||Vw(n)||Ey(n)))return!n.length;var e=no(n);if(e==Cte||e==Rte)return!n.size;if(Tm(n))return!KD(n).length;for(var t in n)if(Nte.call(n,t))return!1;return!0}var Ite="[object RegExp]";function Ote(n){return zo(n)&&tu(n)==Ite}var aN=ql&&ql.isRegExp,Gc=aN?by(aN):Ote;function Wc(n){return n===void 0}var Lte="Expected a function";function Pte(n){if(typeof n!="function")throw new TypeError(Lte);return function(){var e=arguments;switch(e.length){case 0:return!n.call(this);case 1:return!n.call(this,e[0]);case 2:return!n.call(this,e[0],e[1]);case 3:return!n.call(this,e[0],e[1],e[2])}return!n.apply(this,e)}}function Dte(n,e,t,r){if(!_o(n))return n;e=Ay(e,n);for(var i=-1,s=e.length,o=s-1,a=n;a!=null&&++i=Hte){var l=Vte(n);if(l)return Zw(l);o=!1,i=Yw,c=new rd}else c=a;e:for(;++r0&&arguments[0]!==void 0?arguments[0]:{},r=t.serviceUrl,i=t.locale,s=t.headers;oK(this,n),xa(this,"locale",void 0),xa(this,"serviceUrl",void 0),xa(this,"headers",void 0),xa(this,"fetch",function(){var o=Uf(Ps().mark(function a(c){var l;return Ps().wrap(function(h){for(;;)switch(h.prev=h.next){case 0:return h.next=2,e.serviceUrl?fetch(e.serviceUrl,{body:JSON.stringify(c),headers:e.headers,method:"POST"}):DD({payload:c});case 2:return l=h.sent,h.abrupt("return",l);case 4:case"end":return h.stop()}},a)}));return function(a){return o.apply(this,arguments)}}()),xa(this,"create",function(){var o=Uf(Ps().mark(function a(c){return Ps().wrap(function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",e.fetch(c));case 1:case"end":return u.stop()}},a)}));return function(a){return o.apply(this,arguments)}}()),xa(this,"createAudio",function(){var o=Uf(Ps().mark(function a(c){var l,u;return Ps().wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.next=2,e.create(c);case 2:return l=d.sent,d.next=5,l.arrayBuffer();case 5:return u=d.sent,d.abrupt("return",uK(u));case 7:case"end":return d.stop()}},a)}));return function(a){return o.apply(this,arguments)}}()),this.locale=i,this.serviceUrl=r,this.headers=s}return lK(n,[{key:"voiceOptions",get:function(){return Wte(this.locale)}}]),n}();xa(Mm,"localeOptions",mK());xa(Mm,"voiceList",w_);xa(Mm,"voiceName",A_);xa(Mm,"createRequest",DD);const SU="15.0.4",cN=(n,e,t)=>({endTime:e,insertTime:t,type:"exponentialRampToValue",value:n}),lN=(n,e,t)=>({endTime:e,insertTime:t,type:"linearRampToValue",value:n}),Cb=(n,e)=>({startTime:e,type:"setValue",value:n}),EU=(n,e,t)=>({duration:t,startTime:e,type:"setValueCurve",values:n}),bU=(n,e,{startTime:t,target:r,timeConstant:i})=>r+(e-r)*Math.exp((t-n)/i),Tf=n=>n.type==="exponentialRampToValue",hv=n=>n.type==="linearRampToValue",Ml=n=>Tf(n)||hv(n),tA=n=>n.type==="setValue",Tc=n=>n.type==="setValueCurve",fv=(n,e,t,r)=>{const i=n[e];return i===void 0?r:Ml(i)||tA(i)?i.value:Tc(i)?i.values[i.values.length-1]:bU(t,fv(n,e-1,i.startTime,r),i)},uN=(n,e,t,r,i)=>t===void 0?[r.insertTime,i]:Ml(t)?[t.endTime,t.value]:tA(t)?[t.startTime,t.value]:Tc(t)?[t.startTime+t.duration,t.values[t.values.length-1]]:[t.startTime,fv(n,e-1,t.startTime,i)],Rb=n=>n.type==="cancelAndHold",kb=n=>n.type==="cancelScheduledValues",wl=n=>Rb(n)||kb(n)?n.cancelTime:Tf(n)||hv(n)?n.endTime:n.startTime,hN=(n,e,t,{endTime:r,value:i})=>t===i?i:0t+(n-e)/(r-e)*(i-t),jte=(n,e)=>{const t=Math.floor(e),r=Math.ceil(e);return t===r?n[t]:(1-(e-t))*n[t]+(1-(r-e))*n[r]},$te=(n,{duration:e,startTime:t,values:r})=>{const i=(n-t)/e*(r.length-1);return jte(r,i)},V0=n=>n.type==="setTarget";class qte{constructor(e){this._automationEvents=[],this._currenTime=0,this._defaultValue=e}[Symbol.iterator](){return this._automationEvents[Symbol.iterator]()}add(e){const t=wl(e);if(Rb(e)||kb(e)){const r=this._automationEvents.findIndex(s=>kb(e)&&Tc(s)?s.startTime+s.duration>=t:wl(s)>=t),i=this._automationEvents[r];if(r!==-1&&(this._automationEvents=this._automationEvents.slice(0,r)),Rb(e)){const s=this._automationEvents[this._automationEvents.length-1];if(i!==void 0&&Ml(i)){if(s!==void 0&&V0(s))throw new Error("The internal list is malformed.");const o=s===void 0?i.insertTime:Tc(s)?s.startTime+s.duration:wl(s),a=s===void 0?this._defaultValue:Tc(s)?s.values[s.values.length-1]:s.value,c=Tf(i)?hN(t,o,a,i):fN(t,o,a,i),l=Tf(i)?cN(c,t,this._currenTime):lN(c,t,this._currenTime);this._automationEvents.push(l)}if(s!==void 0&&V0(s)&&this._automationEvents.push(Cb(this.getValue(t),t)),s!==void 0&&Tc(s)&&s.startTime+s.duration>t){const o=t-s.startTime,a=(s.values.length-1)/s.duration,c=Math.max(2,1+Math.ceil(o*a)),l=o/(c-1)*a,u=s.values.slice(0,c);if(l<1)for(let h=1;hwl(o)>t),i=r===-1?this._automationEvents[this._automationEvents.length-1]:this._automationEvents[r-1];if(i!==void 0&&Tc(i)&&wl(i)+i.duration>t)return!1;const s=Tf(e)?cN(e.value,e.endTime,this._currenTime):hv(e)?lN(e.value,t,this._currenTime):e;if(r===-1)this._automationEvents.push(s);else{if(Tc(e)&&t+e.duration>wl(this._automationEvents[r]))return!1;this._automationEvents.splice(r,0,s)}}return!0}flush(e){const t=this._automationEvents.findIndex(r=>wl(r)>e);if(t>1){const r=this._automationEvents.slice(t-1),i=r[0];V0(i)&&r.unshift(Cb(fv(this._automationEvents,t-2,i.startTime,this._defaultValue),i.startTime)),this._automationEvents=r}}getValue(e){if(this._automationEvents.length===0)return this._defaultValue;const t=this._automationEvents.findIndex(o=>wl(o)>e),r=this._automationEvents[t],i=(t===-1?this._automationEvents.length:t)-1,s=this._automationEvents[i];if(s!==void 0&&V0(s)&&(r===void 0||!Ml(r)||r.insertTime>e))return bU(e,fv(this._automationEvents,i-1,s.startTime,this._defaultValue),s);if(s!==void 0&&tA(s)&&(r===void 0||!Ml(r)))return s.value;if(s!==void 0&&Tc(s)&&(r===void 0||!Ml(r)||s.startTime+s.duration>e))return e({cancelTime:n,type:"cancelAndHold"}),Kte=n=>({cancelTime:n,type:"cancelScheduledValues"}),Yte=(n,e)=>({endTime:e,type:"exponentialRampToValue",value:n}),Zte=(n,e)=>({endTime:e,type:"linearRampToValue",value:n}),Jte=(n,e,t)=>({startTime:e,target:n,timeConstant:t,type:"setTarget"}),Qte=()=>new DOMException("","AbortError"),ene=n=>(e,t,[r,i,s],o)=>{n(e[i],[t,r,s],a=>a[0]===t&&a[1]===r,o)},tne=n=>(e,t,r)=>{const i=[];for(let s=0;s(e,t)=>{n.set(e,{activeInputs:new Set,passiveInputs:new WeakMap,renderer:t})},od=new WeakSet,TU=new WeakMap,nA=new WeakMap,wU=new WeakMap,rA=new WeakMap,ky=new WeakMap,AU=new WeakMap,Nb=new WeakMap,Ib=new WeakMap,Ob=new WeakMap,MU={construct(){return MU}},rne=n=>{try{const e=new Proxy(n,MU);new e}catch{return!1}return!0},dN=/^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/,pN=(n,e)=>{const t=[];let r=n.replace(/^[\s]+/,""),i=r.match(dN);for(;i!==null;){const s=i[1].slice(1,-1),o=i[0].replace(/([\s]+)?;?$/,"").replace(s,new URL(s,e).toString());t.push(o),r=r.slice(i[0].length).replace(/^[\s]+/,""),i=r.match(dN)}return[t.join(";"),r]},mN=n=>{if(n!==void 0&&!Array.isArray(n))throw new TypeError("The parameterDescriptors property of given value for processorCtor is not an array.")},gN=n=>{if(!rne(n))throw new TypeError("The given value for processorCtor should be a constructor.");if(n.prototype===null||typeof n.prototype!="object")throw new TypeError("The given value for processorCtor should have a prototype.")},ine=(n,e,t,r,i,s,o,a,c,l,u,h,d)=>{let m=0;return(g,v,y={credentials:"omit"})=>{const _=u.get(g);if(_!==void 0&&_.has(v))return Promise.resolve();const S=l.get(g);if(S!==void 0){const k=S.get(v);if(k!==void 0)return k}const E=s(g),T=E.audioWorklet===void 0?i(v).then(([k,R])=>{const[M,O]=pN(k,R),C=`${M};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${O} +})})(window,'_AWGS')`;return t(C)}).then(()=>{const k=d._AWGS.pop();if(k===void 0)throw new SyntaxError;r(E.currentTime,E.sampleRate,()=>k(class{},void 0,(R,M)=>{if(R.trim()==="")throw e();const O=Ib.get(E);if(O!==void 0){if(O.has(R))throw e();gN(M),mN(M.parameterDescriptors),O.set(R,M)}else gN(M),mN(M.parameterDescriptors),Ib.set(E,new Map([[R,M]]))},E.sampleRate,void 0,void 0))}):Promise.all([i(v),Promise.resolve(n(h,h))]).then(([[k,R],M])=>{const O=m+1;m=O;const[C,I]=pN(k,R),w=`${C};((AudioWorkletProcessor,registerProcessor)=>{${I} +})(${M?"AudioWorkletProcessor":"class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}"},(n,p)=>registerProcessor(n,class extends p{${M?"":"__c = (a) => a.forEach(e=>this.__b.add(e.buffer));"}process(i,o,p){${M?"":"i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));"}return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac${O}',class extends AudioWorkletProcessor{process(){return !1}})`,H=new Blob([w],{type:"application/javascript; charset=utf-8"}),V=URL.createObjectURL(H);return E.audioWorklet.addModule(V,y).then(()=>{if(a(E))return E;const B=o(E);return B.audioWorklet.addModule(V,y).then(()=>B)}).then(B=>{if(c===null)throw new SyntaxError;try{new c(B,`__sac${O}`)}catch{throw new SyntaxError}}).finally(()=>URL.revokeObjectURL(V))});return S===void 0?l.set(g,new Map([[v,T]])):S.set(v,T),T.then(()=>{const k=u.get(g);k===void 0?u.set(g,new Set([v])):k.add(v)}).finally(()=>{const k=l.get(g);k!==void 0&&k.delete(v)}),T}},Ho=(n,e)=>{const t=n.get(e);if(t===void 0)throw new Error("A value with the given key could not be found.");return t},Ny=(n,e)=>{const t=Array.from(n).filter(e);if(t.length>1)throw Error("More than one element was found.");if(t.length===0)throw Error("No element was found.");const[r]=t;return n.delete(r),r},CU=(n,e,t,r)=>{const i=Ho(n,e),s=Ny(i,o=>o[0]===t&&o[1]===r);return i.size===0&&n.delete(e),s},Cm=n=>Ho(AU,n),ad=n=>{if(od.has(n))throw new Error("The AudioNode is already stored.");od.add(n),Cm(n).forEach(e=>e(!0))},RU=n=>"port"in n,Rm=n=>{if(!od.has(n))throw new Error("The AudioNode is not stored.");od.delete(n),Cm(n).forEach(e=>e(!1))},Lb=(n,e)=>{!RU(n)&&e.every(t=>t.size===0)&&Rm(n)},sne=(n,e,t,r,i,s,o,a,c,l,u,h,d)=>{const m=new WeakMap;return(g,v,y,_,S)=>{const{activeInputs:E,passiveInputs:T}=s(v),{outputs:k}=s(g),R=a(g),M=O=>{const C=c(v),I=c(g);if(O){const U=CU(T,g,y,_);n(E,g,U,!1),!S&&!h(g)&&t(I,C,y,_),d(v)&&ad(v)}else{const U=r(E,g,y,_);e(T,_,U,!1),!S&&!h(g)&&i(I,C,y,_);const L=o(v);if(L===0)u(v)&&Lb(v,E);else{const P=m.get(v);P!==void 0&&clearTimeout(P),m.set(v,setTimeout(()=>{u(v)&&Lb(v,E)},L*1e3))}}};return l(k,[v,y,_],O=>O[0]===v&&O[1]===y&&O[2]===_,!0)?(R.add(M),u(g)?n(E,g,[y,_,M],!0):e(T,_,[g,y,M],!0),!0):!1}},one=n=>(e,t,[r,i,s],o)=>{const a=e.get(r);a===void 0?e.set(r,new Set([[i,t,s]])):n(a,[i,t,s],c=>c[0]===i&&c[1]===t,o)},ane=n=>(e,t)=>{const r=n(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});t.connect(r).connect(e.destination);const i=()=>{t.removeEventListener("ended",i),t.disconnect(r),r.disconnect()};t.addEventListener("ended",i)},cne=n=>(e,t)=>{n(e).add(t)},lne={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",fftSize:2048,maxDecibels:-30,minDecibels:-100,smoothingTimeConstant:.8},une=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=i(a),u={...lne,...c},h=r(l,u),d=s(l)?e():null;super(a,!1,h,d),this._nativeAnalyserNode=h}get fftSize(){return this._nativeAnalyserNode.fftSize}set fftSize(a){this._nativeAnalyserNode.fftSize=a}get frequencyBinCount(){return this._nativeAnalyserNode.frequencyBinCount}get maxDecibels(){return this._nativeAnalyserNode.maxDecibels}set maxDecibels(a){const c=this._nativeAnalyserNode.maxDecibels;if(this._nativeAnalyserNode.maxDecibels=a,!(a>this._nativeAnalyserNode.minDecibels))throw this._nativeAnalyserNode.maxDecibels=c,t()}get minDecibels(){return this._nativeAnalyserNode.minDecibels}set minDecibels(a){const c=this._nativeAnalyserNode.minDecibels;if(this._nativeAnalyserNode.minDecibels=a,!(this._nativeAnalyserNode.maxDecibels>a))throw this._nativeAnalyserNode.minDecibels=c,t()}get smoothingTimeConstant(){return this._nativeAnalyserNode.smoothingTimeConstant}set smoothingTimeConstant(a){this._nativeAnalyserNode.smoothingTimeConstant=a}getByteFrequencyData(a){this._nativeAnalyserNode.getByteFrequencyData(a)}getByteTimeDomainData(a){this._nativeAnalyserNode.getByteTimeDomainData(a)}getFloatFrequencyData(a){this._nativeAnalyserNode.getFloatFrequencyData(a)}getFloatTimeDomainData(a){this._nativeAnalyserNode.getFloatTimeDomainData(a)}},ki=(n,e)=>n.context===e,hne=(n,e,t)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!ki(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,fftSize:a.fftSize,maxDecibels:a.maxDecibels,minDecibels:a.minDecibels,smoothingTimeConstant:a.smoothingTimeConstant};a=n(o,l)}return r.set(o,a),await t(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},dv=n=>{try{n.copyToChannel(new Float32Array(1),0,-1)}catch{return!1}return!0},Ya=()=>new DOMException("","IndexSizeError"),iA=n=>{n.getChannelData=(e=>t=>{try{return e.call(n,t)}catch(r){throw r.code===12?Ya():r}})(n.getChannelData)},fne={numberOfChannels:1},dne=(n,e,t,r,i,s,o,a)=>{let c=null;return class kU{constructor(u){if(i===null)throw new Error("Missing the native OfflineAudioContext constructor.");const{length:h,numberOfChannels:d,sampleRate:m}={...fne,...u};c===null&&(c=new i(1,1,44100));const g=r!==null&&e(s,s)?new r({length:h,numberOfChannels:d,sampleRate:m}):c.createBuffer(d,h,m);if(g.numberOfChannels===0)throw t();return typeof g.copyFromChannel!="function"?(o(g),iA(g)):e(dv,()=>dv(g))||a(g),n.add(g),g}static[Symbol.hasInstance](u){return u!==null&&typeof u=="object"&&Object.getPrototypeOf(u)===kU.prototype||n.has(u)}}},ls=-34028234663852886e22,Vi=-ls,Dc=n=>od.has(n),pne={buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1},mne=(n,e,t,r,i,s,o,a)=>class extends n{constructor(l,u){const h=s(l),d={...pne,...u},m=i(h,d),g=o(h),v=g?e():null;super(l,!1,m,v),this._audioBufferSourceNodeRenderer=v,this._isBufferNullified=!1,this._isBufferSet=d.buffer!==null,this._nativeAudioBufferSourceNode=m,this._onended=null,this._playbackRate=t(this,g,m.playbackRate,Vi,ls)}get buffer(){return this._isBufferNullified?null:this._nativeAudioBufferSourceNode.buffer}set buffer(l){if(this._nativeAudioBufferSourceNode.buffer=l,l!==null){if(this._isBufferSet)throw r();this._isBufferSet=!0}}get loop(){return this._nativeAudioBufferSourceNode.loop}set loop(l){this._nativeAudioBufferSourceNode.loop=l}get loopEnd(){return this._nativeAudioBufferSourceNode.loopEnd}set loopEnd(l){this._nativeAudioBufferSourceNode.loopEnd=l}get loopStart(){return this._nativeAudioBufferSourceNode.loopStart}set loopStart(l){this._nativeAudioBufferSourceNode.loopStart=l}get onended(){return this._onended}set onended(l){const u=typeof l=="function"?a(this,l):null;this._nativeAudioBufferSourceNode.onended=u;const h=this._nativeAudioBufferSourceNode.onended;this._onended=h!==null&&h===u?l:h}get playbackRate(){return this._playbackRate}start(l=0,u=0,h){if(this._nativeAudioBufferSourceNode.start(l,u,h),this._audioBufferSourceNodeRenderer!==null&&(this._audioBufferSourceNodeRenderer.start=h===void 0?[l,u]:[l,u,h]),this.context.state!=="closed"){ad(this);const d=()=>{this._nativeAudioBufferSourceNode.removeEventListener("ended",d),Dc(this)&&Rm(this)};this._nativeAudioBufferSourceNode.addEventListener("ended",d)}}stop(l=0){this._nativeAudioBufferSourceNode.stop(l),this._audioBufferSourceNodeRenderer!==null&&(this._audioBufferSourceNodeRenderer.stop=l)}},gne=(n,e,t,r,i)=>()=>{const s=new WeakMap;let o=null,a=null;const c=async(l,u)=>{let h=t(l);const d=ki(h,u);if(!d){const m={buffer:h.buffer,channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,loop:h.loop,loopEnd:h.loopEnd,loopStart:h.loopStart,playbackRate:h.playbackRate.value};h=e(u,m),o!==null&&h.start(...o),a!==null&&h.stop(a)}return s.set(u,h),d?await n(u,l.playbackRate,h.playbackRate):await r(u,l.playbackRate,h.playbackRate),await i(l,u,h),h};return{set start(l){o=l},set stop(l){a=l},render(l,u){const h=s.get(u);return h!==void 0?Promise.resolve(h):c(l,u)}}},_ne=n=>"playbackRate"in n,vne=n=>"frequency"in n&&"gain"in n,yne=n=>"offset"in n,xne=n=>!("frequency"in n)&&"gain"in n,Sne=n=>"detune"in n&&"frequency"in n&&!("gain"in n),Ene=n=>"pan"in n,Wi=n=>Ho(TU,n),km=n=>Ho(wU,n),Pb=(n,e)=>{const{activeInputs:t}=Wi(n);t.forEach(i=>i.forEach(([s])=>{e.includes(n)||Pb(s,[...e,n])}));const r=_ne(n)?[n.playbackRate]:RU(n)?Array.from(n.parameters.values()):vne(n)?[n.Q,n.detune,n.frequency,n.gain]:yne(n)?[n.offset]:xne(n)?[n.gain]:Sne(n)?[n.detune,n.frequency]:Ene(n)?[n.pan]:[];for(const i of r){const s=km(i);s!==void 0&&s.activeInputs.forEach(([o])=>Pb(o,e))}Dc(n)&&Rm(n)},NU=n=>{Pb(n.destination,[])},bne=n=>n===void 0||typeof n=="number"||typeof n=="string"&&(n==="balanced"||n==="interactive"||n==="playback"),Tne=(n,e,t,r,i,s,o,a,c)=>class extends n{constructor(u={}){if(c===null)throw new Error("Missing the native AudioContext constructor.");let h;try{h=new c(u)}catch(g){throw g.code===12&&g.message==="sampleRate is not in range"?t():g}if(h===null)throw r();if(!bne(u.latencyHint))throw new TypeError(`The provided value '${u.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(u.sampleRate!==void 0&&h.sampleRate!==u.sampleRate)throw t();super(h,2);const{latencyHint:d}=u,{sampleRate:m}=h;if(this._baseLatency=typeof h.baseLatency=="number"?h.baseLatency:d==="balanced"?512/m:d==="interactive"||d===void 0?256/m:d==="playback"?1024/m:Math.max(2,Math.min(128,Math.round(d*m/128)))*128/m,this._nativeAudioContext=h,c.name==="webkitAudioContext"?(this._nativeGainNode=h.createGain(),this._nativeOscillatorNode=h.createOscillator(),this._nativeGainNode.gain.value=1e-37,this._nativeOscillatorNode.connect(this._nativeGainNode).connect(h.destination),this._nativeOscillatorNode.start()):(this._nativeGainNode=null,this._nativeOscillatorNode=null),this._state=null,h.state==="running"){this._state="suspended";const g=()=>{this._state==="suspended"&&(this._state=null),h.removeEventListener("statechange",g)};h.addEventListener("statechange",g)}}get baseLatency(){return this._baseLatency}get state(){return this._state!==null?this._state:this._nativeAudioContext.state}close(){return this.state==="closed"?this._nativeAudioContext.close().then(()=>{throw e()}):(this._state==="suspended"&&(this._state=null),this._nativeAudioContext.close().then(()=>{this._nativeGainNode!==null&&this._nativeOscillatorNode!==null&&(this._nativeOscillatorNode.stop(),this._nativeGainNode.disconnect(),this._nativeOscillatorNode.disconnect()),NU(this)}))}createMediaElementSource(u){return new i(this,{mediaElement:u})}createMediaStreamDestination(){return new s(this)}createMediaStreamSource(u){return new o(this,{mediaStream:u})}createMediaStreamTrackSource(u){return new a(this,{mediaStreamTrack:u})}resume(){return this._state==="suspended"?new Promise((u,h)=>{const d=()=>{this._nativeAudioContext.removeEventListener("statechange",d),this._nativeAudioContext.state==="running"?u():this.resume().then(u,h)};this._nativeAudioContext.addEventListener("statechange",d)}):this._nativeAudioContext.resume().catch(u=>{throw u===void 0||u.code===15?e():u})}suspend(){return this._nativeAudioContext.suspend().catch(u=>{throw u===void 0?e():u})}},wne=(n,e,t,r,i,s,o,a)=>class extends n{constructor(l,u){const h=s(l),d=o(h),m=i(h,u,d),g=d?e(a):null;super(l,!1,m,g),this._isNodeOfNativeOfflineAudioContext=d,this._nativeAudioDestinationNode=m}get channelCount(){return this._nativeAudioDestinationNode.channelCount}set channelCount(l){if(this._isNodeOfNativeOfflineAudioContext)throw r();if(l>this._nativeAudioDestinationNode.maxChannelCount)throw t();this._nativeAudioDestinationNode.channelCount=l}get channelCountMode(){return this._nativeAudioDestinationNode.channelCountMode}set channelCountMode(l){if(this._isNodeOfNativeOfflineAudioContext)throw r();this._nativeAudioDestinationNode.channelCountMode=l}get maxChannelCount(){return this._nativeAudioDestinationNode.maxChannelCount}},Ane=n=>{const e=new WeakMap,t=async(r,i)=>{const s=i.destination;return e.set(i,s),await n(r,i,s),s};return{render(r,i){const s=e.get(i);return s!==void 0?Promise.resolve(s):t(r,i)}}},Mne=(n,e,t,r,i,s,o,a)=>(c,l)=>{const u=l.listener,h=()=>{const k=new Float32Array(1),R=e(l,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:9}),M=o(l);let O=!1,C=[0,0,-1,0,1,0],I=[0,0,0];const U=()=>{if(O)return;O=!0;const H=r(l,256,9,0);H.onaudioprocess=({inputBuffer:V})=>{const B=[s(V,k,0),s(V,k,1),s(V,k,2),s(V,k,3),s(V,k,4),s(V,k,5)];B.some((W,K)=>W!==C[K])&&(u.setOrientation(...B),C=B);const z=[s(V,k,6),s(V,k,7),s(V,k,8)];z.some((W,K)=>W!==I[K])&&(u.setPosition(...z),I=z)},R.connect(H)},L=H=>V=>{V!==C[H]&&(C[H]=V,u.setOrientation(...C))},P=H=>V=>{V!==I[H]&&(I[H]=V,u.setPosition(...I))},w=(H,V,B)=>{const z=t(l,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:V});z.connect(R,0,H),z.start(),Object.defineProperty(z.offset,"defaultValue",{get(){return V}});const W=n({context:c},M,z.offset,Vi,ls);return a(W,"value",K=>()=>K.call(W),K=>j=>{try{K.call(W,j)}catch(Y){if(Y.code!==9)throw Y}U(),M&&B(j)}),W.cancelAndHoldAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.cancelAndHoldAtTime),W.cancelScheduledValues=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.cancelScheduledValues),W.exponentialRampToValueAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.exponentialRampToValueAtTime),W.linearRampToValueAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.linearRampToValueAtTime),W.setTargetAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.setTargetAtTime),W.setValueAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.setValueAtTime),W.setValueCurveAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.setValueCurveAtTime),W};return{forwardX:w(0,0,L(0)),forwardY:w(1,0,L(1)),forwardZ:w(2,-1,L(2)),positionX:w(6,0,P(0)),positionY:w(7,0,P(1)),positionZ:w(8,0,P(2)),upX:w(3,0,L(3)),upY:w(4,1,L(4)),upZ:w(5,0,L(5))}},{forwardX:d,forwardY:m,forwardZ:g,positionX:v,positionY:y,positionZ:_,upX:S,upY:E,upZ:T}=u.forwardX===void 0?h():u;return{get forwardX(){return d},get forwardY(){return m},get forwardZ(){return g},get positionX(){return v},get positionY(){return y},get positionZ(){return _},get upX(){return S},get upY(){return E},get upZ(){return T}}},pv=n=>"context"in n,Nm=n=>pv(n[0]),Eh=(n,e,t,r)=>{for(const i of n)if(t(i)){if(r)return!1;throw Error("The set contains at least one similar element.")}return n.add(e),!0},_N=(n,e,[t,r],i)=>{Eh(n,[e,t,r],s=>s[0]===e&&s[1]===t,i)},vN=(n,[e,t,r],i)=>{const s=n.get(e);s===void 0?n.set(e,new Set([[t,r]])):Eh(s,[t,r],o=>o[0]===t,i)},bd=n=>"inputs"in n,mv=(n,e,t,r)=>{if(bd(e)){const i=e.inputs[r];return n.connect(i,t,0),[i,t,0]}return n.connect(e,t,r),[e,t,r]},IU=(n,e,t)=>{for(const r of n)if(r[0]===e&&r[1]===t)return n.delete(r),r;return null},Cne=(n,e,t)=>Ny(n,r=>r[0]===e&&r[1]===t),OU=(n,e)=>{if(!Cm(n).delete(e))throw new Error("Missing the expected event listener.")},LU=(n,e,t)=>{const r=Ho(n,e),i=Ny(r,s=>s[0]===t);return r.size===0&&n.delete(e),i},gv=(n,e,t,r)=>{bd(e)?n.disconnect(e.inputs[r],t,0):n.disconnect(e,t,r)},jn=n=>Ho(nA,n),Jp=n=>Ho(rA,n),sh=n=>Nb.has(n),C_=n=>!od.has(n),yN=(n,e)=>new Promise(t=>{if(e!==null)t(!0);else{const r=n.createScriptProcessor(256,1,1),i=n.createGain(),s=n.createBuffer(1,2,44100),o=s.getChannelData(0);o[0]=1,o[1]=1;const a=n.createBufferSource();a.buffer=s,a.loop=!0,a.connect(r).connect(n.destination),a.connect(i),a.disconnect(i),r.onaudioprocess=c=>{const l=c.inputBuffer.getChannelData(0);Array.prototype.some.call(l,u=>u===1)?t(!0):t(!1),a.stop(),r.onaudioprocess=null,a.disconnect(r),r.disconnect(n.destination)},a.start()}}),C1=(n,e)=>{const t=new Map;for(const r of n)for(const i of r){const s=t.get(i);t.set(i,s===void 0?1:s+1)}t.forEach((r,i)=>e(i,r))},_v=n=>"context"in n,Rne=n=>{const e=new Map;n.connect=(t=>(r,i=0,s=0)=>{const o=_v(r)?t(r,i,s):t(r,i),a=e.get(r);return a===void 0?e.set(r,[{input:s,output:i}]):a.every(c=>c.input!==s||c.output!==i)&&a.push({input:s,output:i}),o})(n.connect.bind(n)),n.disconnect=(t=>(r,i,s)=>{if(t.apply(n),r===void 0)e.clear();else if(typeof r=="number")for(const[o,a]of e){const c=a.filter(l=>l.output!==r);c.length===0?e.delete(o):e.set(o,c)}else if(e.has(r))if(i===void 0)e.delete(r);else{const o=e.get(r);if(o!==void 0){const a=o.filter(c=>c.output!==i&&(c.input!==s||s===void 0));a.length===0?e.delete(r):e.set(r,a)}}for(const[o,a]of e)a.forEach(c=>{_v(o)?n.connect(o,c.output,c.input):n.connect(o,c.output)})})(n.disconnect)},kne=(n,e,t,r)=>{const{activeInputs:i,passiveInputs:s}=km(e),{outputs:o}=Wi(n),a=Cm(n),c=l=>{const u=jn(n),h=Jp(e);if(l){const d=LU(s,n,t);_N(i,n,d,!1),!r&&!sh(n)&&u.connect(h,t)}else{const d=Cne(i,n,t);vN(s,d,!1),!r&&!sh(n)&&u.disconnect(h,t)}};return Eh(o,[e,t],l=>l[0]===e&&l[1]===t,!0)?(a.add(c),Dc(n)?_N(i,n,[t,c],!0):vN(s,[n,t,c],!0),!0):!1},Nne=(n,e,t,r)=>{const{activeInputs:i,passiveInputs:s}=Wi(e),o=IU(i[r],n,t);return o===null?[CU(s,n,t,r)[2],!1]:[o[2],!0]},Ine=(n,e,t)=>{const{activeInputs:r,passiveInputs:i}=km(e),s=IU(r,n,t);return s===null?[LU(i,n,t)[1],!1]:[s[2],!0]},sA=(n,e,t,r,i)=>{const[s,o]=Nne(n,t,r,i);if(s!==null&&(OU(n,s),o&&!e&&!sh(n)&&gv(jn(n),jn(t),r,i)),Dc(t)){const{activeInputs:a}=Wi(t);Lb(t,a)}},oA=(n,e,t,r)=>{const[i,s]=Ine(n,t,r);i!==null&&(OU(n,i),s&&!e&&!sh(n)&&jn(n).disconnect(Jp(t),r))},One=(n,e)=>{const t=Wi(n),r=[];for(const i of t.outputs)Nm(i)?sA(n,e,...i):oA(n,e,...i),r.push(i[0]);return t.outputs.clear(),r},Lne=(n,e,t)=>{const r=Wi(n),i=[];for(const s of r.outputs)s[1]===t&&(Nm(s)?sA(n,e,...s):oA(n,e,...s),i.push(s[0]),r.outputs.delete(s));return i},Pne=(n,e,t,r,i)=>{const s=Wi(n);return Array.from(s.outputs).filter(o=>o[0]===t&&(r===void 0||o[1]===r)&&(i===void 0||o[2]===i)).map(o=>(Nm(o)?sA(n,e,...o):oA(n,e,...o),s.outputs.delete(o),o[0]))},Dne=(n,e,t,r,i,s,o,a,c,l,u,h,d,m,g,v)=>class extends l{constructor(_,S,E,T){super(E),this._context=_,this._nativeAudioNode=E;const k=u(_);h(k)&&t(yN,()=>yN(k,v))!==!0&&Rne(E),nA.set(this,E),AU.set(this,new Set),_.state!=="closed"&&S&&ad(this),n(this,T,E)}get channelCount(){return this._nativeAudioNode.channelCount}set channelCount(_){this._nativeAudioNode.channelCount=_}get channelCountMode(){return this._nativeAudioNode.channelCountMode}set channelCountMode(_){this._nativeAudioNode.channelCountMode=_}get channelInterpretation(){return this._nativeAudioNode.channelInterpretation}set channelInterpretation(_){this._nativeAudioNode.channelInterpretation=_}get context(){return this._context}get numberOfInputs(){return this._nativeAudioNode.numberOfInputs}get numberOfOutputs(){return this._nativeAudioNode.numberOfOutputs}connect(_,S=0,E=0){if(S<0||S>=this._nativeAudioNode.numberOfOutputs)throw i();const T=u(this._context),k=g(T);if(d(_)||m(_))throw s();if(pv(_)){const O=jn(_);try{const I=mv(this._nativeAudioNode,O,S,E),U=C_(this);(k||U)&&this._nativeAudioNode.disconnect(...I),this.context.state!=="closed"&&!U&&C_(_)&&ad(_)}catch(I){throw I.code===12?s():I}if(e(this,_,S,E,k)){const I=c([this],_);C1(I,r(k))}return _}const R=Jp(_);if(R.name==="playbackRate"&&R.maxValue===1024)throw o();try{this._nativeAudioNode.connect(R,S),(k||C_(this))&&this._nativeAudioNode.disconnect(R,S)}catch(O){throw O.code===12?s():O}if(kne(this,_,S,k)){const O=c([this],_);C1(O,r(k))}}disconnect(_,S,E){let T;const k=u(this._context),R=g(k);if(_===void 0)T=One(this,R);else if(typeof _=="number"){if(_<0||_>=this.numberOfOutputs)throw i();T=Lne(this,R,_)}else{if(S!==void 0&&(S<0||S>=this.numberOfOutputs)||pv(_)&&E!==void 0&&(E<0||E>=_.numberOfInputs))throw i();if(T=Pne(this,R,_,S,E),T.length===0)throw s()}for(const M of T){const O=c([this],M);C1(O,a)}}},Une=(n,e,t,r,i,s,o,a,c,l,u,h,d)=>(m,g,v,y=null,_=null)=>{const S=v.value,E=new qte(S),T=g?r(E):null,k={get defaultValue(){return S},get maxValue(){return y===null?v.maxValue:y},get minValue(){return _===null?v.minValue:_},get value(){return v.value},set value(R){v.value=R,k.setValueAtTime(R,m.context.currentTime)},cancelAndHoldAtTime(R){if(typeof v.cancelAndHoldAtTime=="function")T===null&&E.flush(m.context.currentTime),E.add(i(R)),v.cancelAndHoldAtTime(R);else{const M=Array.from(E).pop();T===null&&E.flush(m.context.currentTime),E.add(i(R));const O=Array.from(E).pop();v.cancelScheduledValues(R),M!==O&&O!==void 0&&(O.type==="exponentialRampToValue"?v.exponentialRampToValueAtTime(O.value,O.endTime):O.type==="linearRampToValue"?v.linearRampToValueAtTime(O.value,O.endTime):O.type==="setValue"?v.setValueAtTime(O.value,O.startTime):O.type==="setValueCurve"&&v.setValueCurveAtTime(O.values,O.startTime,O.duration))}return k},cancelScheduledValues(R){return T===null&&E.flush(m.context.currentTime),E.add(s(R)),v.cancelScheduledValues(R),k},exponentialRampToValueAtTime(R,M){if(R===0)throw new RangeError;if(!Number.isFinite(M)||M<0)throw new RangeError;const O=m.context.currentTime;return T===null&&E.flush(O),Array.from(E).length===0&&(E.add(l(S,O)),v.setValueAtTime(S,O)),E.add(o(R,M)),v.exponentialRampToValueAtTime(R,M),k},linearRampToValueAtTime(R,M){const O=m.context.currentTime;return T===null&&E.flush(O),Array.from(E).length===0&&(E.add(l(S,O)),v.setValueAtTime(S,O)),E.add(a(R,M)),v.linearRampToValueAtTime(R,M),k},setTargetAtTime(R,M,O){return T===null&&E.flush(m.context.currentTime),E.add(c(R,M,O)),v.setTargetAtTime(R,M,O),k},setValueAtTime(R,M){return T===null&&E.flush(m.context.currentTime),E.add(l(R,M)),v.setValueAtTime(R,M),k},setValueCurveAtTime(R,M,O){const C=R instanceof Float32Array?R:new Float32Array(R);if(h!==null&&h.name==="webkitAudioContext"){const I=M+O,U=m.context.sampleRate,L=Math.ceil(M*U),P=Math.floor(I*U),w=P-L,H=new Float32Array(w);for(let B=0;B({replay(e){for(const t of n)if(t.type==="exponentialRampToValue"){const{endTime:r,value:i}=t;e.exponentialRampToValueAtTime(i,r)}else if(t.type==="linearRampToValue"){const{endTime:r,value:i}=t;e.linearRampToValueAtTime(i,r)}else if(t.type==="setTarget"){const{startTime:r,target:i,timeConstant:s}=t;e.setTargetAtTime(i,r,s)}else if(t.type==="setValue"){const{startTime:r,value:i}=t;e.setValueAtTime(i,r)}else if(t.type==="setValueCurve"){const{duration:r,startTime:i,values:s}=t;e.setValueCurveAtTime(s,i,r)}else throw new Error("Can't apply an unknown automation.")}});class PU{constructor(e){this._map=new Map(e)}get size(){return this._map.size}entries(){return this._map.entries()}forEach(e,t=null){return this._map.forEach((r,i)=>e.call(t,r,i,this))}get(e){return this._map.get(e)}has(e){return this._map.has(e)}keys(){return this._map.keys()}values(){return this._map.values()}}const Bne={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,parameterData:{},processorOptions:{}},zne=(n,e,t,r,i,s,o,a,c,l,u,h,d,m)=>class extends e{constructor(v,y,_){var S;const E=a(v),T=c(E),k=u({...Bne,..._});d(k);const R=Ib.get(E),M=R==null?void 0:R.get(y),O=T||E.state!=="closed"?E:(S=o(E))!==null&&S!==void 0?S:E,C=i(O,T?null:v.baseLatency,l,y,M,k),I=T?r(y,k,M):null;super(v,!0,C,I);const U=[];C.parameters.forEach((P,w)=>{const H=t(this,T,P);U.push([w,H])}),this._nativeAudioWorkletNode=C,this._onprocessorerror=null,this._parameters=new PU(U),T&&n(E,this);const{activeInputs:L}=s(this);h(C,L)}get onprocessorerror(){return this._onprocessorerror}set onprocessorerror(v){const y=typeof v=="function"?m(this,v):null;this._nativeAudioWorkletNode.onprocessorerror=y;const _=this._nativeAudioWorkletNode.onprocessorerror;this._onprocessorerror=_!==null&&_===y?v:_}get parameters(){return this._parameters===null?this._nativeAudioWorkletNode.parameters:this._parameters}get port(){return this._nativeAudioWorkletNode.port}};function vv(n,e,t,r,i){if(typeof n.copyFromChannel=="function")e[t].byteLength===0&&(e[t]=new Float32Array(128)),n.copyFromChannel(e[t],r,i);else{const s=n.getChannelData(r);if(e[t].byteLength===0)e[t]=s.slice(i,i+128);else{const o=new Float32Array(s.buffer,i*Float32Array.BYTES_PER_ELEMENT,128);e[t].set(o)}}}const DU=(n,e,t,r,i)=>{typeof n.copyToChannel=="function"?e[t].byteLength!==0&&n.copyToChannel(e[t],r,i):e[t].byteLength!==0&&n.getChannelData(r).set(e[t],i)},yv=(n,e)=>{const t=[];for(let r=0;r{const t=Ho(Ob,n),r=jn(e);return Ho(t,r)},Hne=async(n,e,t,r,i,s,o)=>{const a=e===null?Math.ceil(n.context.length/128)*128:e.length,c=r.channelCount*r.numberOfInputs,l=i.reduce((y,_)=>y+_,0),u=l===0?null:t.createBuffer(l,a,t.sampleRate);if(s===void 0)throw new Error("Missing the processor constructor.");const h=Wi(n),d=await Vne(t,n),m=yv(r.numberOfInputs,r.channelCount),g=yv(r.numberOfOutputs,i),v=Array.from(n.parameters.keys()).reduce((y,_)=>({...y,[_]:new Float32Array(128)}),{});for(let y=0;y0&&e!==null)for(let _=0;_{vv(e,v,_,c+S,y)});for(let _=0;_h.activeInputs[T].size===0?[]:E),S=o(y/t.sampleRate,t.sampleRate,()=>d.process(_,g,v));if(u!==null)for(let E=0,T=0;E(y,_,S)=>{const E=new WeakMap;let T=null;const k=async(R,M)=>{let O=u(R),C=null;const I=ki(O,M),U=Array.isArray(_.outputChannelCount)?_.outputChannelCount:Array.from(_.outputChannelCount);if(h===null){const L=U.reduce((V,B)=>V+B,0),P=i(M,{channelCount:Math.max(1,L),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,L)}),w=[];for(let V=0;V{const j=new d(W,Math.ceil(R.context.length/128)*128,M.sampleRate),Y=[],ge=[];for(let be=0;be<_.numberOfInputs;be+=1)Y.push(o(j,{channelCount:_.channelCount,channelCountMode:_.channelCountMode,channelInterpretation:_.channelInterpretation,gain:1})),ge.push(i(j,{channelCount:_.channelCount,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:_.channelCount}));const Q=await Promise.all(Array.from(R.parameters.values()).map(async be=>{const Ae=s(j,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:be.value});return await m(j,be,Ae.offset),Ae})),re=r(j,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,B+z)});for(let be=0;be<_.numberOfInputs;be+=1){Y[be].connect(ge[be]);for(let Ae=0;Ae<_.channelCount;Ae+=1)ge[be].connect(re,Ae,be*_.channelCount+Ae)}for(const[be,Ae]of Q.entries())Ae.connect(re,0,B+be),Ae.start(0);return re.connect(j.destination),await Promise.all(Y.map(be=>g(R,j,be))),v(j)})(),M,_,U,S,l)}const L=await T,P=t(M,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),[w,H,V]=C;L!==null&&(P.buffer=L,P.start(0)),P.connect(w);for(let B=0,z=0;Bclass extends g{constructor(k,R){super(k,R),this._nativeContext=k,this._audioWorklet=n===void 0?void 0:{addModule:(M,O)=>n(this,M,O)}}get audioWorklet(){return this._audioWorklet}createAnalyser(){return new e(this)}createBiquadFilter(){return new i(this)}createBuffer(k,R,M){return new t({length:R,numberOfChannels:k,sampleRate:M})}createBufferSource(){return new r(this)}createChannelMerger(k=6){return new s(this,{numberOfInputs:k})}createChannelSplitter(k=6){return new o(this,{numberOfOutputs:k})}createConstantSource(){return new a(this)}createConvolver(){return new c(this)}createDelay(k=1){return new u(this,{maxDelayTime:k})}createDynamicsCompressor(){return new h(this)}createGain(){return new d(this)}createIIRFilter(k,R){return new m(this,{feedback:R,feedforward:k})}createOscillator(){return new v(this)}createPanner(){return new y(this)}createPeriodicWave(k,R,M={disableNormalization:!1}){return new _(this,{...M,imag:R,real:k})}createStereoPanner(){return new S(this)}createWaveShaper(){return new E(this)}decodeAudioData(k,R,M){return l(this._nativeContext,k).then(O=>(typeof R=="function"&&R(O),O),O=>{throw typeof M=="function"&&M(O),O})}},jne={Q:1,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:350,gain:0,type:"lowpass"},$ne=(n,e,t,r,i,s,o,a)=>class extends n{constructor(l,u){const h=s(l),d={...jne,...u},m=i(h,d),g=o(h),v=g?t():null;super(l,!1,m,v),this._Q=e(this,g,m.Q,Vi,ls),this._detune=e(this,g,m.detune,1200*Math.log2(Vi),-1200*Math.log2(Vi)),this._frequency=e(this,g,m.frequency,l.sampleRate/2,0),this._gain=e(this,g,m.gain,40*Math.log10(Vi),ls),this._nativeBiquadFilterNode=m,a(this,1)}get detune(){return this._detune}get frequency(){return this._frequency}get gain(){return this._gain}get Q(){return this._Q}get type(){return this._nativeBiquadFilterNode.type}set type(l){this._nativeBiquadFilterNode.type=l}getFrequencyResponse(l,u,h){try{this._nativeBiquadFilterNode.getFrequencyResponse(l,u,h)}catch(d){throw d.code===11?r():d}if(l.length!==u.length||u.length!==h.length)throw r()}},qne=(n,e,t,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=t(a);const u=ki(l,c);if(!u){const h={Q:l.Q.value,channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,detune:l.detune.value,frequency:l.frequency.value,gain:l.gain.value,type:l.type};l=e(c,h)}return s.set(c,l),u?(await n(c,a.Q,l.Q),await n(c,a.detune,l.detune),await n(c,a.frequency,l.frequency),await n(c,a.gain,l.gain)):(await r(c,a.Q,l.Q),await r(c,a.detune,l.detune),await r(c,a.frequency,l.frequency),await r(c,a.gain,l.gain)),await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},Xne=(n,e)=>(t,r)=>{const i=e.get(t);if(i!==void 0)return i;const s=n.get(t);if(s!==void 0)return s;try{const o=r();return o instanceof Promise?(n.set(t,o),o.catch(()=>!1).then(a=>(n.delete(t),e.set(t,a),a))):(e.set(t,o),o)}catch{return e.set(t,!1),!1}},Kne={channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6},Yne=(n,e,t,r,i)=>class extends n{constructor(o,a){const c=r(o),l={...Kne,...a},u=t(c,l),h=i(c)?e():null;super(o,!1,u,h)}},Zne=(n,e,t)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!ki(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,numberOfInputs:a.numberOfInputs};a=n(o,l)}return r.set(o,a),await t(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},Jne={channelCount:6,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:6},Qne=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=r(a),u=s({...Jne,...c}),h=t(l,u),d=i(l)?e():null;super(a,!1,h,d)}},ere=(n,e,t)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!ki(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,numberOfOutputs:a.numberOfOutputs};a=n(o,l)}return r.set(o,a),await t(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},tre=n=>(e,t,r)=>n(t,e,r),nre=n=>(e,t,r=0,i=0)=>{const s=e[r];if(s===void 0)throw n();return _v(t)?s.connect(t,0,i):s.connect(t,0)},rre=n=>(e,t)=>{const r=n(e,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),i=e.createBuffer(1,2,44100);return r.buffer=i,r.loop=!0,r.connect(t),r.start(),()=>{r.stop(),r.disconnect(t)}},ire={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",offset:1},sre=(n,e,t,r,i,s,o)=>class extends n{constructor(c,l){const u=i(c),h={...ire,...l},d=r(u,h),m=s(u),g=m?t():null;super(c,!1,d,g),this._constantSourceNodeRenderer=g,this._nativeConstantSourceNode=d,this._offset=e(this,m,d.offset,Vi,ls),this._onended=null}get offset(){return this._offset}get onended(){return this._onended}set onended(c){const l=typeof c=="function"?o(this,c):null;this._nativeConstantSourceNode.onended=l;const u=this._nativeConstantSourceNode.onended;this._onended=u!==null&&u===l?c:u}start(c=0){if(this._nativeConstantSourceNode.start(c),this._constantSourceNodeRenderer!==null&&(this._constantSourceNodeRenderer.start=c),this.context.state!=="closed"){ad(this);const l=()=>{this._nativeConstantSourceNode.removeEventListener("ended",l),Dc(this)&&Rm(this)};this._nativeConstantSourceNode.addEventListener("ended",l)}}stop(c=0){this._nativeConstantSourceNode.stop(c),this._constantSourceNodeRenderer!==null&&(this._constantSourceNodeRenderer.stop=c)}},ore=(n,e,t,r,i)=>()=>{const s=new WeakMap;let o=null,a=null;const c=async(l,u)=>{let h=t(l);const d=ki(h,u);if(!d){const m={channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,offset:h.offset.value};h=e(u,m),o!==null&&h.start(o),a!==null&&h.stop(a)}return s.set(u,h),d?await n(u,l.offset,h.offset):await r(u,l.offset,h.offset),await i(l,u,h),h};return{set start(l){o=l},set stop(l){a=l},render(l,u){const h=s.get(u);return h!==void 0?Promise.resolve(h):c(l,u)}}},are=n=>e=>(n[0]=e,n[0]),cre={buffer:null,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",disableNormalization:!1},lre=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=r(a),u={...cre,...c},h=t(l,u),m=i(l)?e():null;super(a,!1,h,m),this._isBufferNullified=!1,this._nativeConvolverNode=h,u.buffer!==null&&s(this,u.buffer.duration)}get buffer(){return this._isBufferNullified?null:this._nativeConvolverNode.buffer}set buffer(a){if(this._nativeConvolverNode.buffer=a,a===null&&this._nativeConvolverNode.buffer!==null){const c=this._nativeConvolverNode.context;this._nativeConvolverNode.buffer=c.createBuffer(1,1,c.sampleRate),this._isBufferNullified=!0,s(this,0)}else this._isBufferNullified=!1,s(this,this._nativeConvolverNode.buffer===null?0:this._nativeConvolverNode.buffer.duration)}get normalize(){return this._nativeConvolverNode.normalize}set normalize(a){this._nativeConvolverNode.normalize=a}},ure=(n,e,t)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!ki(a,o)){const l={buffer:a.buffer,channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,disableNormalization:!a.normalize};a=n(o,l)}return r.set(o,a),bd(a)?await t(s,o,a.inputs[0]):await t(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},hre=(n,e)=>(t,r,i)=>{if(e===null)throw new Error("Missing the native OfflineAudioContext constructor.");try{return new e(t,r,i)}catch(s){throw s.name==="SyntaxError"?n():s}},fre=()=>new DOMException("","DataCloneError"),xN=n=>{const{port1:e,port2:t}=new MessageChannel;return new Promise(r=>{const i=()=>{t.onmessage=null,e.close(),t.close(),r()};t.onmessage=()=>i();try{e.postMessage(n,[n])}catch{}finally{i()}})},dre=(n,e,t,r,i,s,o,a,c,l,u)=>(h,d)=>{const m=o(h)?h:s(h);if(i.has(d)){const g=t();return Promise.reject(g)}try{i.add(d)}catch{}return e(c,()=>c(m))?m.decodeAudioData(d).then(g=>(xN(d).catch(()=>{}),e(a,()=>a(g))||u(g),n.add(g),g)):new Promise((g,v)=>{const y=async()=>{try{await xN(d)}catch{}},_=S=>{v(S),y()};try{m.decodeAudioData(d,S=>{typeof S.copyFromChannel!="function"&&(l(S),iA(S)),n.add(S),y().then(()=>g(S))},S=>{_(S===null?r():S)})}catch(S){_(S)}})},pre=(n,e,t,r,i,s,o,a)=>(c,l)=>{const u=e.get(c);if(u===void 0)throw new Error("Missing the expected cycle count.");const h=s(c.context),d=a(h);if(u===l){if(e.delete(c),!d&&o(c)){const m=r(c),{outputs:g}=t(c);for(const v of g)if(Nm(v)){const y=r(v[0]);n(m,y,v[1],v[2])}else{const y=i(v[0]);m.connect(y,v[1])}}}else e.set(c,u-l)},mre={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",delayTime:0,maxDelayTime:1},gre=(n,e,t,r,i,s,o)=>class extends n{constructor(c,l){const u=i(c),h={...mre,...l},d=r(u,h),m=s(u),g=m?t(h.maxDelayTime):null;super(c,!1,d,g),this._delayTime=e(this,m,d.delayTime),o(this,h.maxDelayTime)}get delayTime(){return this._delayTime}},_re=(n,e,t,r,i)=>s=>{const o=new WeakMap,a=async(c,l)=>{let u=t(c);const h=ki(u,l);if(!h){const d={channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,delayTime:u.delayTime.value,maxDelayTime:s};u=e(l,d)}return o.set(l,u),h?await n(l,c.delayTime,u.delayTime):await r(l,c.delayTime,u.delayTime),await i(c,l,u),u};return{render(c,l){const u=o.get(l);return u!==void 0?Promise.resolve(u):a(c,l)}}},vre=n=>(e,t,r,i)=>n(e[i],s=>s[0]===t&&s[1]===r),yre=n=>(e,t)=>{n(e).delete(t)},xre=n=>"delayTime"in n,Sre=(n,e,t)=>function r(i,s){const o=pv(s)?s:t(n,s);if(xre(o))return[];if(i[0]===o)return[i];if(i.includes(o))return[];const{outputs:a}=e(o);return Array.from(a).map(c=>r([...i,o],c[0])).reduce((c,l)=>c.concat(l),[])},H0=(n,e,t)=>{const r=e[t];if(r===void 0)throw n();return r},Ere=n=>(e,t=void 0,r=void 0,i=0)=>t===void 0?e.forEach(s=>s.disconnect()):typeof t=="number"?H0(n,e,t).disconnect():_v(t)?r===void 0?e.forEach(s=>s.disconnect(t)):i===void 0?H0(n,e,r).disconnect(t,0):H0(n,e,r).disconnect(t,0,i):r===void 0?e.forEach(s=>s.disconnect(t)):H0(n,e,r).disconnect(t,0),bre={attack:.003,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",knee:30,ratio:12,release:.25,threshold:-24},Tre=(n,e,t,r,i,s,o,a)=>class extends n{constructor(l,u){const h=s(l),d={...bre,...u},m=r(h,d),g=o(h),v=g?t():null;super(l,!1,m,v),this._attack=e(this,g,m.attack),this._knee=e(this,g,m.knee),this._nativeDynamicsCompressorNode=m,this._ratio=e(this,g,m.ratio),this._release=e(this,g,m.release),this._threshold=e(this,g,m.threshold),a(this,.006)}get attack(){return this._attack}get channelCount(){return this._nativeDynamicsCompressorNode.channelCount}set channelCount(l){const u=this._nativeDynamicsCompressorNode.channelCount;if(this._nativeDynamicsCompressorNode.channelCount=l,l>2)throw this._nativeDynamicsCompressorNode.channelCount=u,i()}get channelCountMode(){return this._nativeDynamicsCompressorNode.channelCountMode}set channelCountMode(l){const u=this._nativeDynamicsCompressorNode.channelCountMode;if(this._nativeDynamicsCompressorNode.channelCountMode=l,l==="max")throw this._nativeDynamicsCompressorNode.channelCountMode=u,i()}get knee(){return this._knee}get ratio(){return this._ratio}get reduction(){return typeof this._nativeDynamicsCompressorNode.reduction.value=="number"?this._nativeDynamicsCompressorNode.reduction.value:this._nativeDynamicsCompressorNode.reduction}get release(){return this._release}get threshold(){return this._threshold}},wre=(n,e,t,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=t(a);const u=ki(l,c);if(!u){const h={attack:l.attack.value,channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,knee:l.knee.value,ratio:l.ratio.value,release:l.release.value,threshold:l.threshold.value};l=e(c,h)}return s.set(c,l),u?(await n(c,a.attack,l.attack),await n(c,a.knee,l.knee),await n(c,a.ratio,l.ratio),await n(c,a.release,l.release),await n(c,a.threshold,l.threshold)):(await r(c,a.attack,l.attack),await r(c,a.knee,l.knee),await r(c,a.ratio,l.ratio),await r(c,a.release,l.release),await r(c,a.threshold,l.threshold)),await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},Are=()=>new DOMException("","EncodingError"),Mre=n=>e=>new Promise((t,r)=>{if(n===null){r(new SyntaxError);return}const i=n.document.head;if(i===null)r(new SyntaxError);else{const s=n.document.createElement("script"),o=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(o),c=n.onerror,l=()=>{n.onerror=c,URL.revokeObjectURL(a)};n.onerror=(u,h,d,m,g)=>{if(h===a||h===n.location.href&&d===1&&m===1)return l(),r(g),!1;if(c!==null)return c(u,h,d,m,g)},s.onerror=()=>{l(),r(new SyntaxError)},s.onload=()=>{l(),t()},s.src=a,s.type="module",i.appendChild(s)}}),Cre=n=>class{constructor(t){this._nativeEventTarget=t,this._listeners=new WeakMap}addEventListener(t,r,i){if(r!==null){let s=this._listeners.get(r);s===void 0&&(s=n(this,r),typeof r=="function"&&this._listeners.set(r,s)),this._nativeEventTarget.addEventListener(t,s,i)}}dispatchEvent(t){return this._nativeEventTarget.dispatchEvent(t)}removeEventListener(t,r,i){const s=r===null?void 0:this._listeners.get(r);this._nativeEventTarget.removeEventListener(t,s===void 0?null:s,i)}},Rre=n=>(e,t,r)=>{Object.defineProperties(n,{currentFrame:{configurable:!0,get(){return Math.round(e*t)}},currentTime:{configurable:!0,get(){return e}}});try{return r()}finally{n!==null&&(delete n.currentFrame,delete n.currentTime)}},kre=n=>async e=>{try{const t=await fetch(e);if(t.ok)return[await t.text(),t.url]}catch{}throw n()},Nre={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",gain:1},Ire=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=i(a),u={...Nre,...c},h=r(l,u),d=s(l),m=d?t():null;super(a,!1,h,m),this._gain=e(this,d,h.gain,Vi,ls)}get gain(){return this._gain}},Ore=(n,e,t,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=t(a);const u=ki(l,c);if(!u){const h={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,gain:l.gain.value};l=e(c,h)}return s.set(c,l),u?await n(c,a.gain,l.gain):await r(c,a.gain,l.gain),await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},Lre=(n,e)=>t=>e(n,t),Pre=n=>e=>{const t=n(e);if(t.renderer===null)throw new Error("Missing the renderer of the given AudioNode in the audio graph.");return t.renderer},Dre=n=>e=>{var t;return(t=n.get(e))!==null&&t!==void 0?t:0},Ure=n=>e=>{const t=n(e);if(t.renderer===null)throw new Error("Missing the renderer of the given AudioParam in the audio graph.");return t.renderer},Fre=n=>e=>n.get(e),ui=()=>new DOMException("","InvalidStateError"),Bre=n=>e=>{const t=n.get(e);if(t===void 0)throw ui();return t},zre=(n,e)=>t=>{let r=n.get(t);if(r!==void 0)return r;if(e===null)throw new Error("Missing the native OfflineAudioContext constructor.");return r=new e(1,1,44100),n.set(t,r),r},Vre=n=>e=>{const t=n.get(e);if(t===void 0)throw new Error("The context has no set of AudioWorkletNodes.");return t},Iy=()=>new DOMException("","InvalidAccessError"),Hre=n=>{n.getFrequencyResponse=(e=>(t,r,i)=>{if(t.length!==r.length||r.length!==i.length)throw Iy();return e.call(n,t,r,i)})(n.getFrequencyResponse)},Gre={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers"},Wre=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=r(a),u=i(l),h={...Gre,...c},d=e(l,u?null:a.baseLatency,h),m=u?t(h.feedback,h.feedforward):null;super(a,!1,d,m),Hre(d),this._nativeIIRFilterNode=d,s(this,1)}getFrequencyResponse(a,c,l){return this._nativeIIRFilterNode.getFrequencyResponse(a,c,l)}},UU=(n,e,t,r,i,s,o,a,c,l,u)=>{const h=l.length;let d=a;for(let m=0;m{const i=t instanceof Float64Array?t:new Float64Array(t),s=r instanceof Float64Array?r:new Float64Array(r),o=i.length,a=s.length,c=Math.min(o,a);if(i[0]!==1){for(let g=0;g(s,o)=>{const a=new WeakMap;let c=null;const l=async(u,h)=>{let d=null,m=e(u);const g=ki(m,h);if(h.createIIRFilter===void 0?d=n(h,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}):g||(m=h.createIIRFilter(o,s)),a.set(h,d===null?m:d),d!==null){if(c===null){if(t===null)throw new Error("Missing the native OfflineAudioContext constructor.");const y=new t(u.context.destination.channelCount,u.context.length,h.sampleRate);c=(async()=>{await r(u,y,y.destination);const _=await i(y);return jre(_,h,s,o)})()}const v=await c;return d.buffer=v,d.start(0),d}return await r(u,h,m),m};return{render(u,h){const d=a.get(h);return d!==void 0?Promise.resolve(d):l(u,h)}}},qre=(n,e,t,r,i,s)=>o=>(a,c)=>{const l=n.get(a);if(l===void 0){if(!o&&s(a)){const u=r(a),{outputs:h}=t(a);for(const d of h)if(Nm(d)){const m=r(d[0]);e(u,m,d[1],d[2])}else{const m=i(d[0]);u.disconnect(m,d[1])}}n.set(a,c)}else n.set(a,l+c)},Xre=(n,e)=>t=>{const r=n.get(t);return e(r)||e(t)},Kre=(n,e)=>t=>n.has(t)||e(t),Yre=(n,e)=>t=>n.has(t)||e(t),Zre=(n,e)=>t=>{const r=n.get(t);return e(r)||e(t)},Jre=n=>e=>n!==null&&e instanceof n,Qre=n=>e=>n!==null&&typeof n.AudioNode=="function"&&e instanceof n.AudioNode,eie=n=>e=>n!==null&&typeof n.AudioParam=="function"&&e instanceof n.AudioParam,tie=(n,e)=>t=>n(t)||e(t),nie=n=>e=>n!==null&&e instanceof n,rie=n=>n!==null&&n.isSecureContext,iie=(n,e,t,r)=>class extends n{constructor(s,o){const a=t(s),c=e(a,o);if(r(a))throw TypeError();super(s,!0,c,null),this._nativeMediaElementAudioSourceNode=c}get mediaElement(){return this._nativeMediaElementAudioSourceNode.mediaElement}},sie={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers"},oie=(n,e,t,r)=>class extends n{constructor(s,o){const a=t(s);if(r(a))throw new TypeError;const c={...sie,...o},l=e(a,c);super(s,!1,l,null),this._nativeMediaStreamAudioDestinationNode=l}get stream(){return this._nativeMediaStreamAudioDestinationNode.stream}},aie=(n,e,t,r)=>class extends n{constructor(s,o){const a=t(s),c=e(a,o);if(r(a))throw new TypeError;super(s,!0,c,null),this._nativeMediaStreamAudioSourceNode=c}get mediaStream(){return this._nativeMediaStreamAudioSourceNode.mediaStream}},cie=(n,e,t)=>class extends n{constructor(i,s){const o=t(i),a=e(o,s);super(i,!0,a,null)}},lie=(n,e,t,r,i,s)=>class extends t{constructor(a,c){super(a),this._nativeContext=a,ky.set(this,a),r(a)&&i.set(a,new Set),this._destination=new n(this,c),this._listener=e(this,a),this._onstatechange=null}get currentTime(){return this._nativeContext.currentTime}get destination(){return this._destination}get listener(){return this._listener}get onstatechange(){return this._onstatechange}set onstatechange(a){const c=typeof a=="function"?s(this,a):null;this._nativeContext.onstatechange=c;const l=this._nativeContext.onstatechange;this._onstatechange=l!==null&&l===c?a:l}get sampleRate(){return this._nativeContext.sampleRate}get state(){return this._nativeContext.state}},Qp=n=>{const e=new Uint32Array([1179011410,40,1163280727,544501094,16,131073,44100,176400,1048580,1635017060,4,0]);try{const t=n.decodeAudioData(e.buffer,()=>{});return t===void 0?!1:(t.catch(()=>{}),!0)}catch{}return!1},uie=(n,e)=>(t,r,i)=>{const s=new Set;return t.connect=(o=>(a,c=0,l=0)=>{const u=s.size===0;if(e(a))return o.call(t,a,c,l),n(s,[a,c,l],h=>h[0]===a&&h[1]===c&&h[2]===l,!0),u&&r(),a;o.call(t,a,c),n(s,[a,c],h=>h[0]===a&&h[1]===c,!0),u&&r()})(t.connect),t.disconnect=(o=>(a,c,l)=>{const u=s.size>0;if(a===void 0)o.apply(t),s.clear();else if(typeof a=="number"){o.call(t,a);for(const d of s)d[1]===a&&s.delete(d)}else{e(a)?o.call(t,a,c,l):o.call(t,a,c);for(const d of s)d[0]===a&&(c===void 0||d[1]===c)&&(l===void 0||d[2]===l)&&s.delete(d)}const h=s.size===0;u&&h&&i()})(t.disconnect),t},Yn=(n,e,t)=>{const r=e[t];r!==void 0&&r!==n[t]&&(n[t]=r)},Xr=(n,e)=>{Yn(n,e,"channelCount"),Yn(n,e,"channelCountMode"),Yn(n,e,"channelInterpretation")},SN=n=>typeof n.getFloatTimeDomainData=="function",hie=n=>{n.getFloatTimeDomainData=e=>{const t=new Uint8Array(e.length);n.getByteTimeDomainData(t);const r=Math.max(t.length,n.fftSize);for(let i=0;i(t,r)=>{const i=t.createAnalyser();if(Xr(i,r),!(r.maxDecibels>r.minDecibels))throw e();return Yn(i,r,"fftSize"),Yn(i,r,"maxDecibels"),Yn(i,r,"minDecibels"),Yn(i,r,"smoothingTimeConstant"),n(SN,()=>SN(i))||hie(i),i},die=n=>n===null?null:n.hasOwnProperty("AudioBuffer")?n.AudioBuffer:null,or=(n,e,t)=>{const r=e[t];r!==void 0&&r!==n[t].value&&(n[t].value=r)},pie=n=>{n.start=(e=>{let t=!1;return(r=0,i=0,s)=>{if(t)throw ui();e.call(n,r,i,s),t=!0}})(n.start)},aA=n=>{n.start=(e=>(t=0,r=0,i)=>{if(typeof i=="number"&&i<0||r<0||t<0)throw new RangeError("The parameters can't be negative.");e.call(n,t,r,i)})(n.start)},cA=n=>{n.stop=(e=>(t=0)=>{if(t<0)throw new RangeError("The parameter can't be negative.");e.call(n,t)})(n.stop)},mie=(n,e,t,r,i,s,o,a,c,l,u)=>(h,d)=>{const m=h.createBufferSource();return Xr(m,d),or(m,d,"playbackRate"),Yn(m,d,"buffer"),Yn(m,d,"loop"),Yn(m,d,"loopEnd"),Yn(m,d,"loopStart"),e(t,()=>t(h))||pie(m),e(r,()=>r(h))||c(m),e(i,()=>i(h))||l(m,h),e(s,()=>s(h))||aA(m),e(o,()=>o(h))||u(m,h),e(a,()=>a(h))||cA(m),n(h,m),m},gie=n=>n===null?null:n.hasOwnProperty("AudioContext")?n.AudioContext:n.hasOwnProperty("webkitAudioContext")?n.webkitAudioContext:null,_ie=(n,e)=>(t,r,i)=>{const s=t.destination;if(s.channelCount!==r)try{s.channelCount=r}catch{}i&&s.channelCountMode!=="explicit"&&(s.channelCountMode="explicit"),s.maxChannelCount===0&&Object.defineProperty(s,"maxChannelCount",{value:r});const o=n(t,{channelCount:r,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,gain:1});return e(o,"channelCount",a=>()=>a.call(o),a=>c=>{a.call(o,c);try{s.channelCount=c}catch(l){if(c>s.maxChannelCount)throw l}}),e(o,"channelCountMode",a=>()=>a.call(o),a=>c=>{a.call(o,c),s.channelCountMode=c}),e(o,"channelInterpretation",a=>()=>a.call(o),a=>c=>{a.call(o,c),s.channelInterpretation=c}),Object.defineProperty(o,"maxChannelCount",{get:()=>s.maxChannelCount}),o.connect(s),o},vie=n=>n===null?null:n.hasOwnProperty("AudioWorkletNode")?n.AudioWorkletNode:null,yie=n=>{const{port1:e}=new MessageChannel;try{e.postMessage(n)}finally{e.close()}},xie=(n,e,t,r,i)=>(s,o,a,c,l,u)=>{if(a!==null)try{const h=new a(s,c,u),d=new Map;let m=null;if(Object.defineProperties(h,{channelCount:{get:()=>u.channelCount,set:()=>{throw n()}},channelCountMode:{get:()=>"explicit",set:()=>{throw n()}},onprocessorerror:{get:()=>m,set:g=>{typeof m=="function"&&h.removeEventListener("processorerror",m),m=typeof g=="function"?g:null,typeof m=="function"&&h.addEventListener("processorerror",m)}}}),h.addEventListener=(g=>(...v)=>{if(v[0]==="processorerror"){const y=typeof v[1]=="function"?v[1]:typeof v[1]=="object"&&v[1]!==null&&typeof v[1].handleEvent=="function"?v[1].handleEvent:null;if(y!==null){const _=d.get(v[1]);_!==void 0?v[1]=_:(v[1]=S=>{S.type==="error"?(Object.defineProperties(S,{type:{value:"processorerror"}}),y(S)):y(new ErrorEvent(v[0],{...S}))},d.set(y,v[1]))}}return g.call(h,"error",v[1],v[2]),g.call(h,...v)})(h.addEventListener),h.removeEventListener=(g=>(...v)=>{if(v[0]==="processorerror"){const y=d.get(v[1]);y!==void 0&&(d.delete(v[1]),v[1]=y)}return g.call(h,"error",v[1],v[2]),g.call(h,v[0],v[1],v[2])})(h.removeEventListener),u.numberOfOutputs!==0){const g=t(s,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return h.connect(g).connect(s.destination),i(h,()=>g.disconnect(),()=>g.connect(s.destination))}return h}catch(h){throw h.code===11?r():h}if(l===void 0)throw r();return yie(u),e(s,o,l,u)},FU=(n,e)=>n===null?512:Math.max(512,Math.min(16384,Math.pow(2,Math.round(Math.log2(n*e))))),Sie=n=>new Promise((e,t)=>{const{port1:r,port2:i}=new MessageChannel;r.onmessage=({data:s})=>{r.close(),i.close(),e(s)},r.onmessageerror=({data:s})=>{r.close(),i.close(),t(s)},i.postMessage(n)}),Eie=async(n,e)=>{const t=await Sie(e);return new n(t)},bie=(n,e,t,r)=>{let i=Ob.get(n);i===void 0&&(i=new WeakMap,Ob.set(n,i));const s=Eie(t,r);return i.set(e,s),s},Tie=(n,e,t,r,i,s,o,a,c,l,u,h,d)=>(m,g,v,y)=>{if(y.numberOfInputs===0&&y.numberOfOutputs===0)throw c();const _=Array.isArray(y.outputChannelCount)?y.outputChannelCount:Array.from(y.outputChannelCount);if(_.some(ie=>ie<1))throw c();if(_.length!==y.numberOfOutputs)throw e();if(y.channelCountMode!=="explicit")throw c();const S=y.channelCount*y.numberOfInputs,E=_.reduce((ie,te)=>ie+te,0),T=v.parameterDescriptors===void 0?0:v.parameterDescriptors.length;if(S+T>6||E>6)throw c();const k=new MessageChannel,R=[],M=[];for(let ie=0;ieie===void 0?0:ie},maxValue:{get:()=>te===void 0?Vi:te},minValue:{get:()=>X===void 0?ls:X}}),O.push(ne)}const C=r(m,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,S+T)}),I=FU(g,m.sampleRate),U=a(m,I,S+T,Math.max(1,E)),L=i(m,{channelCount:Math.max(1,E),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,E)}),P=[];for(let ie=0;ie{const X=O[te];return X.connect(C,0,S+te),X.start(0),[ie,X.offset]}));C.connect(U);let H=y.channelInterpretation,V=null;const B=y.numberOfOutputs===0?[U]:P,z={get bufferSize(){return I},get channelCount(){return y.channelCount},set channelCount(ie){throw t()},get channelCountMode(){return y.channelCountMode},set channelCountMode(ie){throw t()},get channelInterpretation(){return H},set channelInterpretation(ie){for(const te of R)te.channelInterpretation=ie;H=ie},get context(){return U.context},get inputs(){return R},get numberOfInputs(){return y.numberOfInputs},get numberOfOutputs(){return y.numberOfOutputs},get onprocessorerror(){return V},set onprocessorerror(ie){typeof V=="function"&&z.removeEventListener("processorerror",V),V=typeof ie=="function"?ie:null,typeof V=="function"&&z.addEventListener("processorerror",V)},get parameters(){return w},get port(){return k.port2},addEventListener(...ie){return U.addEventListener(ie[0],ie[1],ie[2])},connect:n.bind(null,B),disconnect:l.bind(null,B),dispatchEvent(...ie){return U.dispatchEvent(ie[0])},removeEventListener(...ie){return U.removeEventListener(ie[0],ie[1],ie[2])}},W=new Map;k.port1.addEventListener=(ie=>(...te)=>{if(te[0]==="message"){const X=typeof te[1]=="function"?te[1]:typeof te[1]=="object"&&te[1]!==null&&typeof te[1].handleEvent=="function"?te[1].handleEvent:null;if(X!==null){const $=W.get(te[1]);$!==void 0?te[1]=$:(te[1]=ne=>{u(m.currentTime,m.sampleRate,()=>X(ne))},W.set(X,te[1]))}}return ie.call(k.port1,te[0],te[1],te[2])})(k.port1.addEventListener),k.port1.removeEventListener=(ie=>(...te)=>{if(te[0]==="message"){const X=W.get(te[1]);X!==void 0&&(W.delete(te[1]),te[1]=X)}return ie.call(k.port1,te[0],te[1],te[2])})(k.port1.removeEventListener);let K=null;Object.defineProperty(k.port1,"onmessage",{get:()=>K,set:ie=>{typeof K=="function"&&k.port1.removeEventListener("message",K),K=typeof ie=="function"?ie:null,typeof K=="function"&&(k.port1.addEventListener("message",K),k.port1.start())}}),v.prototype.port=k.port1;let j=null;bie(m,z,v,y).then(ie=>j=ie);const ge=yv(y.numberOfInputs,y.channelCount),Q=yv(y.numberOfOutputs,_),re=v.parameterDescriptors===void 0?[]:v.parameterDescriptors.reduce((ie,{name:te})=>({...ie,[te]:new Float32Array(128)}),{});let be=!0;const Ae=()=>{y.numberOfOutputs>0&&U.disconnect(L);for(let ie=0,te=0;ie{if(j!==null){const X=h(z);for(let $=0;${vv(ie,re,ne,S+ae,$)});for(let ne=0;ne{if(X[D].size>0)return Ee.set(D,I/128),G;const he=Ee.get(D);return he===void 0?[]:(G.every(ce=>ce.every(_e=>_e===0))&&(he===1?Ee.delete(D):Ee.set(D,he-1)),G)});be=u(m.currentTime+$/m.sampleRate,m.sampleRate,()=>j.process(ne,Q,re));for(let G=0,D=0;GU.connect(He).connect(m.destination),it=()=>{U.disconnect(He),He.disconnect()},De=()=>{if(be){it(),y.numberOfOutputs>0&&U.connect(L);for(let ie=0,te=0;ie{be&&(qe(),Ae()),Le=!1};return qe(),d(z,De,A)},BU=(n,e)=>{const t=n.createBiquadFilter();return Xr(t,e),or(t,e,"Q"),or(t,e,"detune"),or(t,e,"frequency"),or(t,e,"gain"),Yn(t,e,"type"),t},wie=(n,e)=>(t,r)=>{const i=t.createChannelMerger(r.numberOfInputs);return n!==null&&n.name==="webkitAudioContext"&&e(t,i),Xr(i,r),i},Aie=n=>{const e=n.numberOfOutputs;Object.defineProperty(n,"channelCount",{get:()=>e,set:t=>{if(t!==e)throw ui()}}),Object.defineProperty(n,"channelCountMode",{get:()=>"explicit",set:t=>{if(t!=="explicit")throw ui()}}),Object.defineProperty(n,"channelInterpretation",{get:()=>"discrete",set:t=>{if(t!=="discrete")throw ui()}})},Im=(n,e)=>{const t=n.createChannelSplitter(e.numberOfOutputs);return Xr(t,e),Aie(t),t},Mie=(n,e,t,r,i)=>(s,o)=>{if(s.createConstantSource===void 0)return t(s,o);const a=s.createConstantSource();return Xr(a,o),or(a,o,"offset"),e(r,()=>r(s))||aA(a),e(i,()=>i(s))||cA(a),n(s,a),a},Td=(n,e)=>(n.connect=e.connect.bind(e),n.disconnect=e.disconnect.bind(e),n),Cie=(n,e,t,r)=>(i,{offset:s,...o})=>{const a=i.createBuffer(1,2,44100),c=e(i,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),l=t(i,{...o,gain:s}),u=a.getChannelData(0);u[0]=1,u[1]=1,c.buffer=a,c.loop=!0;const h={get bufferSize(){},get channelCount(){return l.channelCount},set channelCount(g){l.channelCount=g},get channelCountMode(){return l.channelCountMode},set channelCountMode(g){l.channelCountMode=g},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(g){l.channelInterpretation=g},get context(){return l.context},get inputs(){return[]},get numberOfInputs(){return c.numberOfInputs},get numberOfOutputs(){return l.numberOfOutputs},get offset(){return l.gain},get onended(){return c.onended},set onended(g){c.onended=g},addEventListener(...g){return c.addEventListener(g[0],g[1],g[2])},dispatchEvent(...g){return c.dispatchEvent(g[0])},removeEventListener(...g){return c.removeEventListener(g[0],g[1],g[2])},start(g=0){c.start.call(c,g)},stop(g=0){c.stop.call(c,g)}},d=()=>c.connect(l),m=()=>c.disconnect(l);return n(i,c),r(Td(h,l),d,m)},Rie=(n,e)=>(t,r)=>{const i=t.createConvolver();if(Xr(i,r),r.disableNormalization===i.normalize&&(i.normalize=!r.disableNormalization),Yn(i,r,"buffer"),r.channelCount>2||(e(i,"channelCount",s=>()=>s.call(i),s=>o=>{if(o>2)throw n();return s.call(i,o)}),r.channelCountMode==="max"))throw n();return e(i,"channelCountMode",s=>()=>s.call(i),s=>o=>{if(o==="max")throw n();return s.call(i,o)}),i},zU=(n,e)=>{const t=n.createDelay(e.maxDelayTime);return Xr(t,e),or(t,e,"delayTime"),t},kie=n=>(e,t)=>{const r=e.createDynamicsCompressor();if(Xr(r,t),t.channelCount>2||t.channelCountMode==="max")throw n();return or(r,t,"attack"),or(r,t,"knee"),or(r,t,"ratio"),or(r,t,"release"),or(r,t,"threshold"),r},Es=(n,e)=>{const t=n.createGain();return Xr(t,e),or(t,e,"gain"),t},Nie=n=>(e,t,r)=>{if(e.createIIRFilter===void 0)return n(e,t,r);const i=e.createIIRFilter(r.feedforward,r.feedback);return Xr(i,r),i};function Iie(n,e){const t=e[0]*e[0]+e[1]*e[1];return[(n[0]*e[0]+n[1]*e[1])/t,(n[1]*e[0]-n[0]*e[1])/t]}function Oie(n,e){return[n[0]*e[0]-n[1]*e[1],n[0]*e[1]+n[1]*e[0]]}function EN(n,e){let t=[0,0];for(let r=n.length-1;r>=0;r-=1)t=Oie(t,e),t[0]+=n[r];return t}const Lie=(n,e,t,r)=>(i,s,{channelCount:o,channelCountMode:a,channelInterpretation:c,feedback:l,feedforward:u})=>{const h=FU(s,i.sampleRate),d=l instanceof Float64Array?l:new Float64Array(l),m=u instanceof Float64Array?u:new Float64Array(u),g=d.length,v=m.length,y=Math.min(g,v);if(g===0||g>20)throw r();if(d[0]===0)throw e();if(v===0||v>20)throw r();if(m[0]===0)throw e();if(d[0]!==1){for(let O=0;O{const C=O.inputBuffer,I=O.outputBuffer,U=C.numberOfChannels;for(let L=0;Ln.createMediaElementSource(e.mediaElement),Die=(n,e)=>{const t=n.createMediaStreamDestination();return Xr(t,e),t.numberOfOutputs===1&&Object.defineProperty(t,"numberOfOutputs",{get:()=>0}),t},Uie=(n,{mediaStream:e})=>{const t=e.getAudioTracks();t.sort((s,o)=>s.ido.id?1:0);const r=t.slice(0,1),i=n.createMediaStreamSource(new MediaStream(r));return Object.defineProperty(i,"mediaStream",{value:e}),i},Fie=(n,e)=>(t,{mediaStreamTrack:r})=>{if(typeof t.createMediaStreamTrackSource=="function")return t.createMediaStreamTrackSource(r);const i=new MediaStream([r]),s=t.createMediaStreamSource(i);if(r.kind!=="audio")throw n();if(e(t))throw new TypeError;return s},Bie=n=>n===null?null:n.hasOwnProperty("OfflineAudioContext")?n.OfflineAudioContext:n.hasOwnProperty("webkitOfflineAudioContext")?n.webkitOfflineAudioContext:null,zie=(n,e,t,r,i,s)=>(o,a)=>{const c=o.createOscillator();return Xr(c,a),or(c,a,"detune"),or(c,a,"frequency"),a.periodicWave!==void 0?c.setPeriodicWave(a.periodicWave):Yn(c,a,"type"),e(t,()=>t(o))||aA(c),e(r,()=>r(o))||s(c,o),e(i,()=>i(o))||cA(c),n(o,c),c},Vie=n=>(e,t)=>{const r=e.createPanner();return r.orientationX===void 0?n(e,t):(Xr(r,t),or(r,t,"orientationX"),or(r,t,"orientationY"),or(r,t,"orientationZ"),or(r,t,"positionX"),or(r,t,"positionY"),or(r,t,"positionZ"),Yn(r,t,"coneInnerAngle"),Yn(r,t,"coneOuterAngle"),Yn(r,t,"coneOuterGain"),Yn(r,t,"distanceModel"),Yn(r,t,"maxDistance"),Yn(r,t,"panningModel"),Yn(r,t,"refDistance"),Yn(r,t,"rolloffFactor"),r)},Hie=(n,e,t,r,i,s,o,a,c,l)=>(u,{coneInnerAngle:h,coneOuterAngle:d,coneOuterGain:m,distanceModel:g,maxDistance:v,orientationX:y,orientationY:_,orientationZ:S,panningModel:E,positionX:T,positionY:k,positionZ:R,refDistance:M,rolloffFactor:O,...C})=>{const I=u.createPanner();if(C.channelCount>2||C.channelCountMode==="max")throw o();Xr(I,C);const U={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},L=t(u,{...U,channelInterpretation:"speakers",numberOfInputs:6}),P=r(u,{...C,gain:1}),w=r(u,{...U,gain:1}),H=r(u,{...U,gain:0}),V=r(u,{...U,gain:0}),B=r(u,{...U,gain:0}),z=r(u,{...U,gain:0}),W=r(u,{...U,gain:0}),K=i(u,256,6,1),j=s(u,{...U,curve:new Float32Array([1,1]),oversample:"none"});let Y=[y,_,S],ge=[T,k,R];const Q=new Float32Array(1);K.onaudioprocess=({inputBuffer:Ee})=>{const Le=[c(Ee,Q,0),c(Ee,Q,1),c(Ee,Q,2)];Le.some((qe,it)=>qe!==Y[it])&&(I.setOrientation(...Le),Y=Le);const He=[c(Ee,Q,3),c(Ee,Q,4),c(Ee,Q,5)];He.some((qe,it)=>qe!==ge[it])&&(I.setPosition(...He),ge=He)},Object.defineProperty(H.gain,"defaultValue",{get:()=>0}),Object.defineProperty(V.gain,"defaultValue",{get:()=>0}),Object.defineProperty(B.gain,"defaultValue",{get:()=>0}),Object.defineProperty(z.gain,"defaultValue",{get:()=>0}),Object.defineProperty(W.gain,"defaultValue",{get:()=>0});const re={get bufferSize(){},get channelCount(){return I.channelCount},set channelCount(Ee){if(Ee>2)throw o();P.channelCount=Ee,I.channelCount=Ee},get channelCountMode(){return I.channelCountMode},set channelCountMode(Ee){if(Ee==="max")throw o();P.channelCountMode=Ee,I.channelCountMode=Ee},get channelInterpretation(){return I.channelInterpretation},set channelInterpretation(Ee){P.channelInterpretation=Ee,I.channelInterpretation=Ee},get coneInnerAngle(){return I.coneInnerAngle},set coneInnerAngle(Ee){I.coneInnerAngle=Ee},get coneOuterAngle(){return I.coneOuterAngle},set coneOuterAngle(Ee){I.coneOuterAngle=Ee},get coneOuterGain(){return I.coneOuterGain},set coneOuterGain(Ee){if(Ee<0||Ee>1)throw e();I.coneOuterGain=Ee},get context(){return I.context},get distanceModel(){return I.distanceModel},set distanceModel(Ee){I.distanceModel=Ee},get inputs(){return[P]},get maxDistance(){return I.maxDistance},set maxDistance(Ee){if(Ee<0)throw new RangeError;I.maxDistance=Ee},get numberOfInputs(){return I.numberOfInputs},get numberOfOutputs(){return I.numberOfOutputs},get orientationX(){return w.gain},get orientationY(){return H.gain},get orientationZ(){return V.gain},get panningModel(){return I.panningModel},set panningModel(Ee){I.panningModel=Ee},get positionX(){return B.gain},get positionY(){return z.gain},get positionZ(){return W.gain},get refDistance(){return I.refDistance},set refDistance(Ee){if(Ee<0)throw new RangeError;I.refDistance=Ee},get rolloffFactor(){return I.rolloffFactor},set rolloffFactor(Ee){if(Ee<0)throw new RangeError;I.rolloffFactor=Ee},addEventListener(...Ee){return P.addEventListener(Ee[0],Ee[1],Ee[2])},dispatchEvent(...Ee){return P.dispatchEvent(Ee[0])},removeEventListener(...Ee){return P.removeEventListener(Ee[0],Ee[1],Ee[2])}};h!==re.coneInnerAngle&&(re.coneInnerAngle=h),d!==re.coneOuterAngle&&(re.coneOuterAngle=d),m!==re.coneOuterGain&&(re.coneOuterGain=m),g!==re.distanceModel&&(re.distanceModel=g),v!==re.maxDistance&&(re.maxDistance=v),y!==re.orientationX.value&&(re.orientationX.value=y),_!==re.orientationY.value&&(re.orientationY.value=_),S!==re.orientationZ.value&&(re.orientationZ.value=S),E!==re.panningModel&&(re.panningModel=E),T!==re.positionX.value&&(re.positionX.value=T),k!==re.positionY.value&&(re.positionY.value=k),R!==re.positionZ.value&&(re.positionZ.value=R),M!==re.refDistance&&(re.refDistance=M),O!==re.rolloffFactor&&(re.rolloffFactor=O),(Y[0]!==1||Y[1]!==0||Y[2]!==0)&&I.setOrientation(...Y),(ge[0]!==0||ge[1]!==0||ge[2]!==0)&&I.setPosition(...ge);const be=()=>{P.connect(I),n(P,j,0,0),j.connect(w).connect(L,0,0),j.connect(H).connect(L,0,1),j.connect(V).connect(L,0,2),j.connect(B).connect(L,0,3),j.connect(z).connect(L,0,4),j.connect(W).connect(L,0,5),L.connect(K).connect(u.destination)},Ae=()=>{P.disconnect(I),a(P,j,0,0),j.disconnect(w),w.disconnect(L),j.disconnect(H),H.disconnect(L),j.disconnect(V),V.disconnect(L),j.disconnect(B),B.disconnect(L),j.disconnect(z),z.disconnect(L),j.disconnect(W),W.disconnect(L),L.disconnect(K),K.disconnect(u.destination)};return l(Td(re,I),be,Ae)},Gie=n=>(e,{disableNormalization:t,imag:r,real:i})=>{const s=r instanceof Float32Array?r:new Float32Array(r),o=i instanceof Float32Array?i:new Float32Array(i),a=e.createPeriodicWave(o,s,{disableNormalization:t});if(Array.from(r).length<2)throw n();return a},Om=(n,e,t,r)=>n.createScriptProcessor(e,t,r),Wie=(n,e)=>(t,r)=>{const i=r.channelCountMode;if(i==="clamped-max")throw e();if(t.createStereoPanner===void 0)return n(t,r);const s=t.createStereoPanner();return Xr(s,r),or(s,r,"pan"),Object.defineProperty(s,"channelCountMode",{get:()=>i,set:o=>{if(o!==i)throw e()}}),s},jie=(n,e,t,r,i,s)=>{const a=new Float32Array([1,1]),c=Math.PI/2,l={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},u={...l,oversample:"none"},h=(g,v,y,_)=>{const S=new Float32Array(16385),E=new Float32Array(16385);for(let C=0;C<16385;C+=1){const I=C/16384*c;S[C]=Math.cos(I),E[C]=Math.sin(I)}const T=t(g,{...l,gain:0}),k=r(g,{...u,curve:S}),R=r(g,{...u,curve:a}),M=t(g,{...l,gain:0}),O=r(g,{...u,curve:E});return{connectGraph(){v.connect(T),v.connect(R.inputs===void 0?R:R.inputs[0]),v.connect(M),R.connect(y),y.connect(k.inputs===void 0?k:k.inputs[0]),y.connect(O.inputs===void 0?O:O.inputs[0]),k.connect(T.gain),O.connect(M.gain),T.connect(_,0,0),M.connect(_,0,1)},disconnectGraph(){v.disconnect(T),v.disconnect(R.inputs===void 0?R:R.inputs[0]),v.disconnect(M),R.disconnect(y),y.disconnect(k.inputs===void 0?k:k.inputs[0]),y.disconnect(O.inputs===void 0?O:O.inputs[0]),k.disconnect(T.gain),O.disconnect(M.gain),T.disconnect(_,0,0),M.disconnect(_,0,1)}}},d=(g,v,y,_)=>{const S=new Float32Array(16385),E=new Float32Array(16385),T=new Float32Array(16385),k=new Float32Array(16385),R=Math.floor(16385/2);for(let B=0;B<16385;B+=1)if(B>R){const z=(B-R)/(16384-R)*c;S[B]=Math.cos(z),E[B]=Math.sin(z),T[B]=0,k[B]=1}else{const z=B/(16384-R)*c;S[B]=1,E[B]=0,T[B]=Math.cos(z),k[B]=Math.sin(z)}const M=e(g,{channelCount:2,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:2}),O=t(g,{...l,gain:0}),C=r(g,{...u,curve:S}),I=t(g,{...l,gain:0}),U=r(g,{...u,curve:E}),L=r(g,{...u,curve:a}),P=t(g,{...l,gain:0}),w=r(g,{...u,curve:T}),H=t(g,{...l,gain:0}),V=r(g,{...u,curve:k});return{connectGraph(){v.connect(M),v.connect(L.inputs===void 0?L:L.inputs[0]),M.connect(O,0),M.connect(I,0),M.connect(P,1),M.connect(H,1),L.connect(y),y.connect(C.inputs===void 0?C:C.inputs[0]),y.connect(U.inputs===void 0?U:U.inputs[0]),y.connect(w.inputs===void 0?w:w.inputs[0]),y.connect(V.inputs===void 0?V:V.inputs[0]),C.connect(O.gain),U.connect(I.gain),w.connect(P.gain),V.connect(H.gain),O.connect(_,0,0),P.connect(_,0,0),I.connect(_,0,1),H.connect(_,0,1)},disconnectGraph(){v.disconnect(M),v.disconnect(L.inputs===void 0?L:L.inputs[0]),M.disconnect(O,0),M.disconnect(I,0),M.disconnect(P,1),M.disconnect(H,1),L.disconnect(y),y.disconnect(C.inputs===void 0?C:C.inputs[0]),y.disconnect(U.inputs===void 0?U:U.inputs[0]),y.disconnect(w.inputs===void 0?w:w.inputs[0]),y.disconnect(V.inputs===void 0?V:V.inputs[0]),C.disconnect(O.gain),U.disconnect(I.gain),w.disconnect(P.gain),V.disconnect(H.gain),O.disconnect(_,0,0),P.disconnect(_,0,0),I.disconnect(_,0,1),H.disconnect(_,0,1)}}},m=(g,v,y,_,S)=>{if(v===1)return h(g,y,_,S);if(v===2)return d(g,y,_,S);throw i()};return(g,{channelCount:v,channelCountMode:y,pan:_,...S})=>{if(y==="max")throw i();const E=n(g,{...S,channelCount:1,channelCountMode:y,numberOfInputs:2}),T=t(g,{...S,channelCount:v,channelCountMode:y,gain:1}),k=t(g,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:_});let{connectGraph:R,disconnectGraph:M}=m(g,v,T,k,E);Object.defineProperty(k.gain,"defaultValue",{get:()=>0}),Object.defineProperty(k.gain,"maxValue",{get:()=>1}),Object.defineProperty(k.gain,"minValue",{get:()=>-1});const O={get bufferSize(){},get channelCount(){return T.channelCount},set channelCount(L){T.channelCount!==L&&(C&&M(),{connectGraph:R,disconnectGraph:M}=m(g,L,T,k,E),C&&R()),T.channelCount=L},get channelCountMode(){return T.channelCountMode},set channelCountMode(L){if(L==="clamped-max"||L==="max")throw i();T.channelCountMode=L},get channelInterpretation(){return T.channelInterpretation},set channelInterpretation(L){T.channelInterpretation=L},get context(){return T.context},get inputs(){return[T]},get numberOfInputs(){return T.numberOfInputs},get numberOfOutputs(){return T.numberOfOutputs},get pan(){return k.gain},addEventListener(...L){return T.addEventListener(L[0],L[1],L[2])},dispatchEvent(...L){return T.dispatchEvent(L[0])},removeEventListener(...L){return T.removeEventListener(L[0],L[1],L[2])}};let C=!1;const I=()=>{R(),C=!0},U=()=>{M(),C=!1};return s(Td(O,E),I,U)}},$ie=(n,e,t,r,i,s,o)=>(a,c)=>{const l=a.createWaveShaper();if(s!==null&&s.name==="webkitAudioContext"&&a.createGain().gain.automationRate===void 0)return t(a,c);Xr(l,c);const u=c.curve===null||c.curve instanceof Float32Array?c.curve:new Float32Array(c.curve);if(u!==null&&u.length<2)throw e();Yn(l,{curve:u},"curve"),Yn(l,c,"oversample");let h=null,d=!1;return o(l,"curve",v=>()=>v.call(l),v=>y=>(v.call(l,y),d&&(r(y)&&h===null?h=n(a,l):!r(y)&&h!==null&&(h(),h=null)),y)),i(l,()=>{d=!0,r(l.curve)&&(h=n(a,l))},()=>{d=!1,h!==null&&(h(),h=null)})},qie=(n,e,t,r,i)=>(s,{curve:o,oversample:a,...c})=>{const l=s.createWaveShaper(),u=s.createWaveShaper();Xr(l,c),Xr(u,c);const h=t(s,{...c,gain:1}),d=t(s,{...c,gain:-1}),m=t(s,{...c,gain:1}),g=t(s,{...c,gain:-1});let v=null,y=!1,_=null;const S={get bufferSize(){},get channelCount(){return l.channelCount},set channelCount(k){h.channelCount=k,d.channelCount=k,l.channelCount=k,m.channelCount=k,u.channelCount=k,g.channelCount=k},get channelCountMode(){return l.channelCountMode},set channelCountMode(k){h.channelCountMode=k,d.channelCountMode=k,l.channelCountMode=k,m.channelCountMode=k,u.channelCountMode=k,g.channelCountMode=k},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(k){h.channelInterpretation=k,d.channelInterpretation=k,l.channelInterpretation=k,m.channelInterpretation=k,u.channelInterpretation=k,g.channelInterpretation=k},get context(){return l.context},get curve(){return _},set curve(k){if(k!==null&&k.length<2)throw e();if(k===null)l.curve=k,u.curve=k;else{const R=k.length,M=new Float32Array(R+2-R%2),O=new Float32Array(R+2-R%2);M[0]=k[0],O[0]=-k[R-1];const C=Math.ceil((R+1)/2),I=(R+1)/2-1;for(let U=1;U{h.connect(l).connect(m),h.connect(d).connect(u).connect(g).connect(m),y=!0,r(_)&&(v=n(s,h))},T=()=>{h.disconnect(l),l.disconnect(m),h.disconnect(d),d.disconnect(u),u.disconnect(g),g.disconnect(m),y=!1,v!==null&&(v(),v=null)};return i(Td(S,m),E,T)},es=()=>new DOMException("","NotSupportedError"),Xie={numberOfChannels:1},Kie=(n,e,t,r,i)=>class extends n{constructor(o,a,c){let l;if(typeof o=="number"&&a!==void 0&&c!==void 0)l={length:a,numberOfChannels:o,sampleRate:c};else if(typeof o=="object")l=o;else throw new Error("The given parameters are not valid.");const{length:u,numberOfChannels:h,sampleRate:d}={...Xie,...l},m=r(h,u,d);e(Qp,()=>Qp(m))||m.addEventListener("statechange",(()=>{let g=0;const v=y=>{this._state==="running"&&(g>0?(m.removeEventListener("statechange",v),y.stopImmediatePropagation(),this._waitForThePromiseToSettle(y)):g+=1)};return v})()),super(m,h),this._length=u,this._nativeOfflineAudioContext=m,this._state=null}get length(){return this._nativeOfflineAudioContext.length===void 0?this._length:this._nativeOfflineAudioContext.length}get state(){return this._state===null?this._nativeOfflineAudioContext.state:this._state}startRendering(){return this._state==="running"?Promise.reject(t()):(this._state="running",i(this.destination,this._nativeOfflineAudioContext).finally(()=>{this._state=null,NU(this)}))}_waitForThePromiseToSettle(o){this._state===null?this._nativeOfflineAudioContext.dispatchEvent(o):setTimeout(()=>this._waitForThePromiseToSettle(o))}},Yie={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:440,periodicWave:void 0,type:"sine"},Zie=(n,e,t,r,i,s,o)=>class extends n{constructor(c,l){const u=i(c),h={...Yie,...l},d=t(u,h),m=s(u),g=m?r():null,v=c.sampleRate/2;super(c,!1,d,g),this._detune=e(this,m,d.detune,153600,-153600),this._frequency=e(this,m,d.frequency,v,-v),this._nativeOscillatorNode=d,this._onended=null,this._oscillatorNodeRenderer=g,this._oscillatorNodeRenderer!==null&&h.periodicWave!==void 0&&(this._oscillatorNodeRenderer.periodicWave=h.periodicWave)}get detune(){return this._detune}get frequency(){return this._frequency}get onended(){return this._onended}set onended(c){const l=typeof c=="function"?o(this,c):null;this._nativeOscillatorNode.onended=l;const u=this._nativeOscillatorNode.onended;this._onended=u!==null&&u===l?c:u}get type(){return this._nativeOscillatorNode.type}set type(c){this._nativeOscillatorNode.type=c,this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.periodicWave=null)}setPeriodicWave(c){this._nativeOscillatorNode.setPeriodicWave(c),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.periodicWave=c)}start(c=0){if(this._nativeOscillatorNode.start(c),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.start=c),this.context.state!=="closed"){ad(this);const l=()=>{this._nativeOscillatorNode.removeEventListener("ended",l),Dc(this)&&Rm(this)};this._nativeOscillatorNode.addEventListener("ended",l)}}stop(c=0){this._nativeOscillatorNode.stop(c),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.stop=c)}},Jie=(n,e,t,r,i)=>()=>{const s=new WeakMap;let o=null,a=null,c=null;const l=async(u,h)=>{let d=t(u);const m=ki(d,h);if(!m){const g={channelCount:d.channelCount,channelCountMode:d.channelCountMode,channelInterpretation:d.channelInterpretation,detune:d.detune.value,frequency:d.frequency.value,periodicWave:o===null?void 0:o,type:d.type};d=e(h,g),a!==null&&d.start(a),c!==null&&d.stop(c)}return s.set(h,d),m?(await n(h,u.detune,d.detune),await n(h,u.frequency,d.frequency)):(await r(h,u.detune,d.detune),await r(h,u.frequency,d.frequency)),await i(u,h,d),d};return{set periodicWave(u){o=u},set start(u){a=u},set stop(u){c=u},render(u,h){const d=s.get(h);return d!==void 0?Promise.resolve(d):l(u,h)}}},Qie={channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:1,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1},ese=(n,e,t,r,i,s,o)=>class extends n{constructor(c,l){const u=i(c),h={...Qie,...l},d=t(u,h),m=s(u),g=m?r():null;super(c,!1,d,g),this._nativePannerNode=d,this._orientationX=e(this,m,d.orientationX,Vi,ls),this._orientationY=e(this,m,d.orientationY,Vi,ls),this._orientationZ=e(this,m,d.orientationZ,Vi,ls),this._positionX=e(this,m,d.positionX,Vi,ls),this._positionY=e(this,m,d.positionY,Vi,ls),this._positionZ=e(this,m,d.positionZ,Vi,ls),o(this,1)}get coneInnerAngle(){return this._nativePannerNode.coneInnerAngle}set coneInnerAngle(c){this._nativePannerNode.coneInnerAngle=c}get coneOuterAngle(){return this._nativePannerNode.coneOuterAngle}set coneOuterAngle(c){this._nativePannerNode.coneOuterAngle=c}get coneOuterGain(){return this._nativePannerNode.coneOuterGain}set coneOuterGain(c){this._nativePannerNode.coneOuterGain=c}get distanceModel(){return this._nativePannerNode.distanceModel}set distanceModel(c){this._nativePannerNode.distanceModel=c}get maxDistance(){return this._nativePannerNode.maxDistance}set maxDistance(c){this._nativePannerNode.maxDistance=c}get orientationX(){return this._orientationX}get orientationY(){return this._orientationY}get orientationZ(){return this._orientationZ}get panningModel(){return this._nativePannerNode.panningModel}set panningModel(c){this._nativePannerNode.panningModel=c}get positionX(){return this._positionX}get positionY(){return this._positionY}get positionZ(){return this._positionZ}get refDistance(){return this._nativePannerNode.refDistance}set refDistance(c){this._nativePannerNode.refDistance=c}get rolloffFactor(){return this._nativePannerNode.rolloffFactor}set rolloffFactor(c){this._nativePannerNode.rolloffFactor=c}},tse=(n,e,t,r,i,s,o,a,c,l)=>()=>{const u=new WeakMap;let h=null;const d=async(m,g)=>{let v=null,y=s(m);const _={channelCount:y.channelCount,channelCountMode:y.channelCountMode,channelInterpretation:y.channelInterpretation},S={..._,coneInnerAngle:y.coneInnerAngle,coneOuterAngle:y.coneOuterAngle,coneOuterGain:y.coneOuterGain,distanceModel:y.distanceModel,maxDistance:y.maxDistance,panningModel:y.panningModel,refDistance:y.refDistance,rolloffFactor:y.rolloffFactor},E=ki(y,g);if("bufferSize"in y)v=r(g,{..._,gain:1});else if(!E){const T={...S,orientationX:y.orientationX.value,orientationY:y.orientationY.value,orientationZ:y.orientationZ.value,positionX:y.positionX.value,positionY:y.positionY.value,positionZ:y.positionZ.value};y=i(g,T)}if(u.set(g,v===null?y:v),v!==null){if(h===null){if(o===null)throw new Error("Missing the native OfflineAudioContext constructor.");const U=new o(6,m.context.length,g.sampleRate),L=e(U,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6});L.connect(U.destination),h=(async()=>{const P=await Promise.all([m.orientationX,m.orientationY,m.orientationZ,m.positionX,m.positionY,m.positionZ].map(async(w,H)=>{const V=t(U,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:H===0?1:0});return await a(U,w,V.offset),V}));for(let w=0;w<6;w+=1)P[w].connect(L,0,w),P[w].start(0);return l(U)})()}const T=await h,k=r(g,{..._,gain:1});await c(m,g,k);const R=[];for(let U=0;Uw!==M[H])||P.some((w,H)=>w!==O[H])){M=L,O=P;const w=U/g.sampleRate;C.gain.setValueAtTime(0,w),C=r(g,{..._,gain:0}),I=i(g,{...S,orientationX:M[0],orientationY:M[1],orientationZ:M[2],positionX:O[0],positionY:O[1],positionZ:O[2]}),C.gain.setValueAtTime(1,w),k.connect(C).connect(I.inputs[0]),I.connect(v)}}return v}return E?(await n(g,m.orientationX,y.orientationX),await n(g,m.orientationY,y.orientationY),await n(g,m.orientationZ,y.orientationZ),await n(g,m.positionX,y.positionX),await n(g,m.positionY,y.positionY),await n(g,m.positionZ,y.positionZ)):(await a(g,m.orientationX,y.orientationX),await a(g,m.orientationY,y.orientationY),await a(g,m.orientationZ,y.orientationZ),await a(g,m.positionX,y.positionX),await a(g,m.positionY,y.positionY),await a(g,m.positionZ,y.positionZ)),bd(y)?await c(m,g,y.inputs[0]):await c(m,g,y),y};return{render(m,g){const v=u.get(g);return v!==void 0?Promise.resolve(v):d(m,g)}}},nse={disableNormalization:!1},rse=(n,e,t,r)=>class VU{constructor(s,o){const a=e(s),c=r({...nse,...o}),l=n(a,c);return t.add(l),l}static[Symbol.hasInstance](s){return s!==null&&typeof s=="object"&&Object.getPrototypeOf(s)===VU.prototype||t.has(s)}},ise=(n,e)=>(t,r,i)=>(n(r).replay(i),e(r,t,i)),sse=(n,e,t)=>async(r,i,s)=>{const o=n(r);await Promise.all(o.activeInputs.map((a,c)=>Array.from(a).map(async([l,u])=>{const d=await e(l).render(l,i),m=r.context.destination;!t(l)&&(r!==m||!t(r))&&d.connect(s,u,c)})).reduce((a,c)=>[...a,...c],[]))},ose=(n,e,t)=>async(r,i,s)=>{const o=e(r);await Promise.all(Array.from(o.activeInputs).map(async([a,c])=>{const u=await n(a).render(a,i);t(a)||u.connect(s,c)}))},ase=(n,e,t,r)=>i=>n(Qp,()=>Qp(i))?Promise.resolve(n(r,r)).then(s=>{if(!s){const o=t(i,512,0,1);i.oncomplete=()=>{o.onaudioprocess=null,o.disconnect()},o.onaudioprocess=()=>i.currentTime,o.connect(i.destination)}return i.startRendering()}):new Promise(s=>{const o=e(i,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});i.oncomplete=a=>{o.disconnect(),s(a.renderedBuffer)},o.connect(i.destination),i.startRendering()}),cse=n=>(e,t)=>{n.set(e,t)},lse=n=>(e,t)=>n.set(e,t),use=(n,e,t,r,i,s,o,a)=>(c,l)=>t(c).render(c,l).then(()=>Promise.all(Array.from(r(l)).map(u=>t(u).render(u,l)))).then(()=>i(l)).then(u=>(typeof u.copyFromChannel!="function"?(o(u),iA(u)):e(s,()=>s(u))||a(u),n.add(u),u)),hse={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",pan:0},fse=(n,e,t,r,i,s)=>class extends n{constructor(a,c){const l=i(a),u={...hse,...c},h=t(l,u),d=s(l),m=d?r():null;super(a,!1,h,m),this._pan=e(this,d,h.pan)}get pan(){return this._pan}},dse=(n,e,t,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=t(a);const u=ki(l,c);if(!u){const h={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,pan:l.pan.value};l=e(c,h)}return s.set(c,l),u?await n(c,a.pan,l.pan):await r(c,a.pan,l.pan),bd(l)?await i(a,c,l.inputs[0]):await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},pse=n=>()=>{if(n===null)return!1;try{new n({length:1,sampleRate:44100})}catch{return!1}return!0},mse=(n,e)=>async()=>{if(n===null)return!0;if(e===null)return!1;const t=new Blob(['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),r=new e(1,128,44100),i=URL.createObjectURL(t);let s=!1,o=!1;try{await r.audioWorklet.addModule(i);const a=new n(r,"a",{numberOfOutputs:0}),c=r.createOscillator();a.port.onmessage=()=>s=!0,a.onprocessorerror=()=>o=!0,c.connect(a),c.start(0),await r.startRendering(),await new Promise(l=>setTimeout(l))}catch{}finally{URL.revokeObjectURL(i)}return s&&!o},gse=(n,e)=>()=>{if(e===null)return Promise.resolve(!1);const t=new e(1,1,44100),r=n(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return new Promise(i=>{t.oncomplete=()=>{r.disconnect(),i(t.currentTime!==0)},t.startRendering()})},_se=()=>new DOMException("","UnknownError"),vse={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",curve:null,oversample:"none"},yse=(n,e,t,r,i,s,o)=>class extends n{constructor(c,l){const u=i(c),h={...vse,...l},d=t(u,h),g=s(u)?r():null;super(c,!0,d,g),this._isCurveNullified=!1,this._nativeWaveShaperNode=d,o(this,1)}get curve(){return this._isCurveNullified?null:this._nativeWaveShaperNode.curve}set curve(c){if(c===null)this._isCurveNullified=!0,this._nativeWaveShaperNode.curve=new Float32Array([0,0]);else{if(c.length<2)throw e();this._isCurveNullified=!1,this._nativeWaveShaperNode.curve=c}}get oversample(){return this._nativeWaveShaperNode.oversample}set oversample(c){this._nativeWaveShaperNode.oversample=c}},xse=(n,e,t)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!ki(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,curve:a.curve,oversample:a.oversample};a=n(o,l)}return r.set(o,a),bd(a)?await t(s,o,a.inputs[0]):await t(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},Sse=()=>typeof window>"u"?null:window,Ese=(n,e)=>t=>{t.copyFromChannel=(r,i,s=0)=>{const o=n(s),a=n(i);if(a>=t.numberOfChannels)throw e();const c=t.length,l=t.getChannelData(a),u=r.length;for(let h=o<0?-o:0;h+o{const o=n(s),a=n(i);if(a>=t.numberOfChannels)throw e();const c=t.length,l=t.getChannelData(a),u=r.length;for(let h=o<0?-o:0;h+oe=>{e.copyFromChannel=(t=>(r,i,s=0)=>{const o=n(s),a=n(i);if(o(r,i,s=0)=>{const o=n(s),a=n(i);if(o(e,t)=>{const r=t.createBuffer(1,1,44100);e.buffer===null&&(e.buffer=r),n(e,"buffer",i=>()=>{const s=i.call(e);return s===r?null:s},i=>s=>i.call(e,s===null?r:s))},wse=(n,e)=>(t,r)=>{r.channelCount=1,r.channelCountMode="explicit",Object.defineProperty(r,"channelCount",{get:()=>1,set:()=>{throw n()}}),Object.defineProperty(r,"channelCountMode",{get:()=>"explicit",set:()=>{throw n()}});const i=t.createBufferSource();e(r,()=>{const a=r.numberOfInputs;for(let c=0;ci.disconnect(r))},HU=(n,e,t)=>n.copyFromChannel===void 0?n.getChannelData(t)[0]:(n.copyFromChannel(e,t),e[0]),GU=n=>{if(n===null)return!1;const e=n.length;return e%2!==0?n[Math.floor(e/2)]!==0:n[e/2-1]+n[e/2]!==0},Lm=(n,e,t,r)=>{let i=n;for(;!i.hasOwnProperty(e);)i=Object.getPrototypeOf(i);const{get:s,set:o}=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(n,e,{get:t(s),set:r(o)})},Ase=n=>({...n,outputChannelCount:n.outputChannelCount!==void 0?n.outputChannelCount:n.numberOfInputs===1&&n.numberOfOutputs===1?[n.channelCount]:Array.from({length:n.numberOfOutputs},()=>1)}),Mse=n=>({...n,channelCount:n.numberOfOutputs}),Cse=n=>{const{imag:e,real:t}=n;return e===void 0?t===void 0?{...n,imag:[0,0],real:[0,0]}:{...n,imag:Array.from(t,()=>0),real:t}:t===void 0?{...n,imag:e,real:Array.from(e,()=>0)}:{...n,imag:e,real:t}},WU=(n,e,t)=>{try{n.setValueAtTime(e,t)}catch(r){if(r.code!==9)throw r;WU(n,e,t+1e-7)}},Rse=n=>{const e=n.createBufferSource();e.start();try{e.start()}catch{return!0}return!1},kse=n=>{const e=n.createBufferSource(),t=n.createBuffer(1,1,44100);e.buffer=t;try{e.start(0,1)}catch{return!1}return!0},Nse=n=>{const e=n.createBufferSource();e.start();try{e.stop()}catch{return!1}return!0},lA=n=>{const e=n.createOscillator();try{e.start(-1)}catch(t){return t instanceof RangeError}return!1},jU=n=>{const e=n.createBuffer(1,1,44100),t=n.createBufferSource();t.buffer=e,t.start(),t.stop();try{return t.stop(),!0}catch{return!1}},uA=n=>{const e=n.createOscillator();try{e.stop(-1)}catch(t){return t instanceof RangeError}return!1},Ise=n=>{const{port1:e,port2:t}=new MessageChannel;try{e.postMessage(n)}finally{e.close(),t.close()}},Ose=n=>{n.start=(e=>(t=0,r=0,i)=>{const s=n.buffer,o=s===null?r:Math.min(s.duration,r);s!==null&&o>s.duration-.5/n.context.sampleRate?e.call(n,t,0,0):e.call(n,t,o,i)})(n.start)},$U=(n,e)=>{const t=e.createGain();n.connect(t);const r=(i=>()=>{i.call(n,t),n.removeEventListener("ended",r)})(n.disconnect);n.addEventListener("ended",r),Td(n,t),n.stop=(i=>{let s=!1;return(o=0)=>{if(s)try{i.call(n,o)}catch{t.gain.setValueAtTime(0,o)}else i.call(n,o),s=!0}})(n.stop)},wd=(n,e)=>t=>{const r={value:n};return Object.defineProperties(t,{currentTarget:r,target:r}),typeof e=="function"?e.call(n,t):e.handleEvent.call(n,t)},Lse=ene(Eh),Pse=one(Eh),Dse=vre(Ny),qU=new WeakMap,Use=Dre(qU),qo=Xne(new Map,new WeakMap),Va=Sse(),XU=fie(qo,Ya),hA=Pre(Wi),gi=sse(Wi,hA,sh),Fse=hne(XU,jn,gi),Vn=Bre(ky),nl=Bie(Va),In=nie(nl),KU=new WeakMap,YU=Cre(wd),Pm=gie(Va),fA=Jre(Pm),dA=Qre(Va),ZU=eie(Va),em=vie(Va),br=Dne(tne(TU),sne(Lse,Pse,mv,Dse,gv,Wi,Use,Cm,jn,Eh,Dc,sh,C_),qo,qre(Nb,gv,Wi,jn,Jp,Dc),Ya,Iy,es,pre(mv,Nb,Wi,jn,Jp,Vn,Dc,In),Sre(KU,Wi,Ho),YU,Vn,fA,dA,ZU,In,em),Bse=une(br,Fse,Ya,XU,Vn,In),pA=new WeakSet,bN=die(Va),JU=are(new Uint32Array(1)),mA=Ese(JU,Ya),gA=bse(JU),QU=dne(pA,qo,es,bN,nl,pse(bN),mA,gA),Oy=ane(Es),e3=ose(hA,km,sh),Za=tre(e3),Ad=mie(Oy,qo,Rse,kse,Nse,lA,jU,uA,Ose,Tse(Lm),$U),Ja=ise(Ure(km),e3),zse=gne(Za,Ad,jn,Ja,gi),Xo=Une(nne(wU),KU,rA,Fne,Xte,Kte,Yte,Zte,Jte,Cb,EU,Pm,WU),Vse=mne(br,zse,Xo,ui,Ad,Vn,In,wd),Hse=wne(br,Ane,Ya,ui,_ie(Es,Lm),Vn,In,gi),Gse=qne(Za,BU,jn,Ja,gi),bh=lse(qU),Wse=$ne(br,Xo,Gse,Iy,BU,Vn,In,bh),nu=uie(Eh,dA),jse=wse(ui,nu),ru=wie(Pm,jse),$se=Zne(ru,jn,gi),qse=Yne(br,$se,ru,Vn,In),Xse=ere(Im,jn,gi),Kse=Qne(br,Xse,Im,Vn,In,Mse),Yse=Cie(Oy,Ad,Es,nu),Md=Mie(Oy,qo,Yse,lA,uA),Zse=ore(Za,Md,jn,Ja,gi),Jse=sre(br,Xo,Zse,Md,Vn,In,wd),t3=Rie(es,Lm),Qse=ure(t3,jn,gi),eoe=lre(br,Qse,t3,Vn,In,bh),toe=_re(Za,zU,jn,Ja,gi),noe=gre(br,Xo,toe,zU,Vn,In,bh),n3=kie(es),roe=wre(Za,n3,jn,Ja,gi),ioe=Tre(br,Xo,roe,n3,es,Vn,In,bh),soe=Ore(Za,Es,jn,Ja,gi),ooe=Ire(br,Xo,soe,Es,Vn,In),aoe=Lie(Iy,ui,Om,es),Ly=ase(qo,Es,Om,gse(Es,nl)),coe=$re(Ad,jn,nl,gi,Ly),loe=Nie(aoe),uoe=Wre(br,loe,coe,Vn,In,bh),hoe=Mne(Xo,ru,Md,Om,es,HU,In,Lm),r3=new WeakMap,foe=lie(Hse,hoe,YU,In,r3,wd),i3=zie(Oy,qo,lA,jU,uA,$U),doe=Jie(Za,i3,jn,Ja,gi),poe=Zie(br,Xo,i3,doe,Vn,In,wd),s3=rre(Ad),moe=qie(s3,ui,Es,GU,nu),Py=$ie(s3,ui,moe,GU,nu,Pm,Lm),goe=Hie(mv,ui,ru,Es,Om,Py,es,gv,HU,nu),o3=Vie(goe),_oe=tse(Za,ru,Md,Es,o3,jn,nl,Ja,gi,Ly),voe=ese(br,Xo,o3,_oe,Vn,In,bh),yoe=Gie(Ya),xoe=rse(yoe,Vn,new WeakSet,Cse),Soe=jie(ru,Im,Es,Py,es,nu),a3=Wie(Soe,es),Eoe=dse(Za,a3,jn,Ja,gi),boe=fse(br,Xo,a3,Eoe,Vn,In),Toe=xse(Py,jn,gi),woe=yse(br,ui,Py,Toe,Vn,In,bh),c3=rie(Va),_A=Rre(Va),l3=new WeakMap,Aoe=zre(l3,nl),Moe=c3?ine(qo,es,Mre(Va),_A,kre(Qte),Vn,Aoe,In,em,new WeakMap,new WeakMap,mse(em,nl),Va):void 0,Coe=tie(fA,In),Roe=dre(pA,qo,fre,Are,new WeakSet,Vn,Coe,dv,Qp,mA,gA),u3=Wne(Moe,Bse,QU,Vse,Wse,qse,Kse,Jse,eoe,Roe,noe,ioe,ooe,uoe,foe,poe,voe,xoe,boe,woe),koe=iie(br,Pie,Vn,In),Noe=oie(br,Die,Vn,In),Ioe=aie(br,Uie,Vn,In),Ooe=Fie(ui,In),Loe=cie(br,Ooe,Vn),Poe=Tne(u3,ui,es,_se,koe,Noe,Ioe,Loe,Pm),vA=Vre(r3),Doe=cne(vA),h3=nre(Ya),Uoe=yre(vA),f3=Ere(Ya),d3=new WeakMap,Foe=Lre(d3,Ho),Boe=Tie(h3,Ya,ui,ru,Im,Md,Es,Om,es,f3,_A,Foe,nu),zoe=xie(ui,Boe,Es,es,nu),Voe=Gne(Za,h3,Ad,ru,Im,Md,Es,Uoe,f3,_A,jn,em,nl,Ja,gi,Ly),Hoe=Fre(l3),Goe=cse(d3),TN=c3?zne(Doe,br,Xo,Voe,zoe,Wi,Hoe,Vn,In,em,Ase,Goe,Ise,wd):void 0,Woe=hre(es,nl),joe=use(pA,qo,hA,vA,Ly,dv,mA,gA),$oe=Kie(u3,qo,ui,Woe,joe),qoe=Xre(ky,fA),Xoe=Kre(nA,dA),Koe=Yre(rA,ZU),Yoe=Zre(ky,In);function Hs(n){return n===void 0}function qt(n){return n!==void 0}function Zoe(n){return typeof n=="function"}function Go(n){return typeof n=="number"}function Dl(n){return Object.prototype.toString.call(n)==="[object Object]"&&n.constructor===Object}function p3(n){return typeof n=="boolean"}function _s(n){return Array.isArray(n)}function jc(n){return typeof n=="string"}function G0(n){return jc(n)&&/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i.test(n)}function wt(n,e){if(!n)throw new Error(e)}function Ha(n,e,t=1/0){if(!(e<=n&&n<=t))throw new RangeError(`Value must be within [${e}, ${t}], got: ${n}`)}function m3(n){!n.isOffline&&n.state!=="running"&&Dy('The AudioContext is "suspended". Invoke Tone.start() from a user action to start the audio.')}let g3=!1,wN=!1;function AN(n){g3=n}function Joe(n){Hs(n)&&g3&&!wN&&(wN=!0,Dy("Events scheduled inside of scheduled callbacks should use the passed in scheduling time. See https://github.com/Tonejs/Tone.js/wiki/Accurate-Timing"))}let _3=console;function Qoe(...n){_3.log(...n)}function Dy(...n){_3.warn(...n)}function eae(n){return new Poe(n)}function tae(n,e,t){return new $oe(n,e,t)}const Ds=typeof self=="object"?self:null,nae=Ds&&(Ds.hasOwnProperty("AudioContext")||Ds.hasOwnProperty("webkitAudioContext"));function rae(n,e,t){return wt(qt(TN),"AudioWorkletNode only works in a secure context (https or localhost)"),new(n instanceof(Ds==null?void 0:Ds.BaseAudioContext)?Ds==null?void 0:Ds.AudioWorkletNode:TN)(n,e,t)}function Ko(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(o=n[a])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s}function Sr(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(r.next(u))}catch(h){o(h)}}function c(u){try{l(r.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((r=r.apply(n,e||[])).next())})}class iae{constructor(e,t,r,i){this._callback=e,this._type=t,this._minimumUpdateInterval=Math.max(128/(i||44100),.001),this.updateInterval=r,this._createClock()}_createWorker(){const e=new Blob([` + // the initial timeout time + let timeoutTime = ${(this._updateInterval*1e3).toFixed(1)}; + // onmessage callback + self.onmessage = function(msg){ + timeoutTime = parseInt(msg.data); + }; + // the tick function which posts a message + // and schedules a new tick + function tick(){ + setTimeout(tick, timeoutTime); + self.postMessage('tick'); + } + // call tick initially + tick(); + `],{type:"text/javascript"}),t=URL.createObjectURL(e),r=new Worker(t);r.onmessage=this._callback.bind(this),this._worker=r}_createTimeout(){this._timeout=setTimeout(()=>{this._createTimeout(),this._callback()},this._updateInterval*1e3)}_createClock(){if(this._type==="worker")try{this._createWorker()}catch{this._type="timeout",this._createClock()}else this._type==="timeout"&&this._createTimeout()}_disposeClock(){this._timeout&&clearTimeout(this._timeout),this._worker&&(this._worker.terminate(),this._worker.onmessage=null)}get updateInterval(){return this._updateInterval}set updateInterval(e){var t;this._updateInterval=Math.max(e,this._minimumUpdateInterval),this._type==="worker"&&((t=this._worker)===null||t===void 0||t.postMessage(this._updateInterval*1e3))}get type(){return this._type}set type(e){this._disposeClock(),this._type=e,this._createClock()}dispose(){this._disposeClock()}}function oh(n){return Koe(n)}function Ul(n){return Xoe(n)}function R_(n){return Yoe(n)}function vf(n){return qoe(n)}function sae(n){return n instanceof QU}function oae(n,e){return n==="value"||oh(e)||Ul(e)||sae(e)}function Ku(n,...e){if(!e.length)return n;const t=e.shift();if(Dl(n)&&Dl(t))for(const r in t)oae(r,t[r])?n[r]=t[r]:Dl(t[r])?(n[r]||Object.assign(n,{[r]:{}}),Ku(n[r],t[r])):Object.assign(n,{[r]:t[r]});return Ku(n,...e)}function aae(n,e){return n.length===e.length&&n.every((t,r)=>e[r]===t)}function ct(n,e,t=[],r){const i={},s=Array.from(e);if(Dl(s[0])&&r&&!Reflect.has(s[0],r)&&(Object.keys(s[0]).some(a=>Reflect.has(n,a))||(Ku(i,{[r]:s[0]}),t.splice(t.indexOf(r),1),s.shift())),s.length===1&&Dl(s[0]))Ku(i,s[0]);else for(let o=0;o{Reflect.has(n,t)&&delete n[t]}),n}/** + * Tone.js + * @author Yotam Mann + * @license http://opensource.org/licenses/MIT MIT License + * @copyright 2014-2024 Yotam Mann + */class rl{constructor(){this.debug=!1,this._wasDisposed=!1}static getDefaults(){return{}}log(...e){(this.debug||Ds&&this.toString()===Ds.TONE_DEBUG_CLASS)&&Qoe(this,...e)}dispose(){return this._wasDisposed=!0,this}get disposed(){return this._wasDisposed}toString(){return this.name}}rl.version=SU;const yA=1e-6;function cd(n,e){return n>e+yA}function Db(n,e){return cd(n,e)||Ro(n,e)}function xv(n,e){return n+yAthis.memory){const t=this.length-this.memory;this._timeline.splice(0,t)}return this}remove(e){const t=this._timeline.indexOf(e);return t!==-1&&this._timeline.splice(t,1),this}get(e,t="time"){const r=this._search(e,t);return r!==-1?this._timeline[r]:null}peek(){return this._timeline[0]}shift(){return this._timeline.shift()}getAfter(e,t="time"){const r=this._search(e,t);return r+10&&this._timeline[t-1].time=0?this._timeline[r-1]:null}cancel(e){if(this._timeline.length>1){let t=this._search(e);if(t>=0)if(Ro(this._timeline[t].time,e)){for(let r=t;r>=0&&Ro(this._timeline[r].time,e);r--)t=r;this._timeline=this._timeline.slice(0,t)}else this._timeline=this._timeline.slice(0,t+1);else this._timeline=[]}else this._timeline.length===1&&Db(this._timeline[0].time,e)&&(this._timeline=[]);return this}cancelBefore(e){const t=this._search(e);return t>=0&&(this._timeline=this._timeline.slice(t+1)),this}previousEvent(e){const t=this._timeline.indexOf(e);return t>0?this._timeline[t-1]:null}_search(e,t="time"){if(this._timeline.length===0)return-1;let r=0;const i=this._timeline.length;let s=i;if(i>0&&this._timeline[i-1][t]<=e)return i-1;for(;r=0&&this._timeline[r].time>=e;)r--;return this._iterate(t,r+1),this}forEachAtTime(e,t){const r=this._search(e);if(r!==-1&&Ro(this._timeline[r].time,e)){let i=r;for(let s=r;s>=0&&Ro(this._timeline[s].time,e);s--)i=s;this._iterate(s=>{t(s)},i,r)}return this}dispose(){return super.dispose(),this._timeline=[],this}}const v3=[];function Uy(n){v3.push(n)}function uae(n){v3.forEach(e=>e(n))}const y3=[];function Fy(n){y3.push(n)}function hae(n){y3.forEach(e=>e(n))}class Dm extends rl{constructor(){super(...arguments),this.name="Emitter"}on(e,t){return e.split(/\W+/).forEach(i=>{Hs(this._events)&&(this._events={}),this._events.hasOwnProperty(i)||(this._events[i]=[]),this._events[i].push(t)}),this}once(e,t){const r=(...i)=>{t(...i),this.off(e,r)};return this.on(e,r),this}off(e,t){return e.split(/\W+/).forEach(i=>{if(Hs(this._events)&&(this._events={}),this._events.hasOwnProperty(i))if(Hs(t))this._events[i]=[];else{const s=this._events[i];for(let o=s.length-1;o>=0;o--)s[o]===t&&s.splice(o,1)}}),this}emit(e,...t){if(this._events&&this._events.hasOwnProperty(e)){const r=this._events[e].slice(0);for(let i=0,s=r.length;i{const r=Object.getOwnPropertyDescriptor(Dm.prototype,t);Object.defineProperty(e.prototype,t,r)})}dispose(){return super.dispose(),this._events=void 0,this}}class x3 extends Dm{constructor(){super(...arguments),this.isOffline=!1}toJSON(){return{}}}class Um extends x3{constructor(){var e,t;super(),this.name="Context",this._constants=new Map,this._timeouts=new ho,this._timeoutIds=0,this._initialized=!1,this._closeStarted=!1,this.isOffline=!1,this._workletPromise=null;const r=ct(Um.getDefaults(),arguments,["context"]);r.context?(this._context=r.context,this._latencyHint=((e=arguments[0])===null||e===void 0?void 0:e.latencyHint)||""):(this._context=eae({latencyHint:r.latencyHint}),this._latencyHint=r.latencyHint),this._ticker=new iae(this.emit.bind(this,"tick"),r.clockSource,r.updateInterval,this._context.sampleRate),this.on("tick",this._timeoutLoop.bind(this)),this._context.onstatechange=()=>{this.emit("statechange",this.state)},this[!((t=arguments[0])===null||t===void 0)&&t.hasOwnProperty("updateInterval")?"_lookAhead":"lookAhead"]=r.lookAhead}static getDefaults(){return{clockSource:"worker",latencyHint:"interactive",lookAhead:.1,updateInterval:.05}}initialize(){return this._initialized||(uae(this),this._initialized=!0),this}createAnalyser(){return this._context.createAnalyser()}createOscillator(){return this._context.createOscillator()}createBufferSource(){return this._context.createBufferSource()}createBiquadFilter(){return this._context.createBiquadFilter()}createBuffer(e,t,r){return this._context.createBuffer(e,t,r)}createChannelMerger(e){return this._context.createChannelMerger(e)}createChannelSplitter(e){return this._context.createChannelSplitter(e)}createConstantSource(){return this._context.createConstantSource()}createConvolver(){return this._context.createConvolver()}createDelay(e){return this._context.createDelay(e)}createDynamicsCompressor(){return this._context.createDynamicsCompressor()}createGain(){return this._context.createGain()}createIIRFilter(e,t){return this._context.createIIRFilter(e,t)}createPanner(){return this._context.createPanner()}createPeriodicWave(e,t,r){return this._context.createPeriodicWave(e,t,r)}createStereoPanner(){return this._context.createStereoPanner()}createWaveShaper(){return this._context.createWaveShaper()}createMediaStreamSource(e){return wt(vf(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamSource(e)}createMediaElementSource(e){return wt(vf(this._context),"Not available if OfflineAudioContext"),this._context.createMediaElementSource(e)}createMediaStreamDestination(){return wt(vf(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamDestination()}decodeAudioData(e){return this._context.decodeAudioData(e)}get currentTime(){return this._context.currentTime}get state(){return this._context.state}get sampleRate(){return this._context.sampleRate}get listener(){return this.initialize(),this._listener}set listener(e){wt(!this._initialized,"The listener cannot be set after initialization."),this._listener=e}get transport(){return this.initialize(),this._transport}set transport(e){wt(!this._initialized,"The transport cannot be set after initialization."),this._transport=e}get draw(){return this.initialize(),this._draw}set draw(e){wt(!this._initialized,"Draw cannot be set after initialization."),this._draw=e}get destination(){return this.initialize(),this._destination}set destination(e){wt(!this._initialized,"The destination cannot be set after initialization."),this._destination=e}createAudioWorkletNode(e,t){return rae(this.rawContext,e,t)}addAudioWorkletModule(e){return Sr(this,void 0,void 0,function*(){wt(qt(this.rawContext.audioWorklet),"AudioWorkletNode is only available in a secure context (https or localhost)"),this._workletPromise||(this._workletPromise=this.rawContext.audioWorklet.addModule(e)),yield this._workletPromise})}workletsAreReady(){return Sr(this,void 0,void 0,function*(){(yield this._workletPromise)?this._workletPromise:Promise.resolve()})}get updateInterval(){return this._ticker.updateInterval}set updateInterval(e){this._ticker.updateInterval=e}get clockSource(){return this._ticker.type}set clockSource(e){this._ticker.type=e}get lookAhead(){return this._lookAhead}set lookAhead(e){this._lookAhead=e,this.updateInterval=e?e/2:.01}get latencyHint(){return this._latencyHint}get rawContext(){return this._context}now(){return this._context.currentTime+this._lookAhead}immediate(){return this._context.currentTime}resume(){return vf(this._context)?this._context.resume():Promise.resolve()}close(){return Sr(this,void 0,void 0,function*(){vf(this._context)&&this.state!=="closed"&&!this._closeStarted&&(this._closeStarted=!0,yield this._context.close()),this._initialized&&hae(this)})}getConstant(e){if(this._constants.has(e))return this._constants.get(e);{const t=this._context.createBuffer(1,128,this._context.sampleRate),r=t.getChannelData(0);for(let s=0;sthis._constants[e].disconnect()),this.close(),this}_timeoutLoop(){const e=this.now();let t=this._timeouts.peek();for(;this._timeouts.length&&t&&t.time<=e;)t.callback(),this._timeouts.shift(),t=this._timeouts.peek()}setTimeout(e,t){this._timeoutIds++;const r=this.now();return this._timeouts.add({callback:e,id:this._timeoutIds,time:r+t}),this._timeoutIds}clearTimeout(e){return this._timeouts.forEach(t=>{t.id===e&&this._timeouts.remove(t)}),this}clearInterval(e){return this.clearTimeout(e)}setInterval(e,t){const r=++this._timeoutIds,i=()=>{const s=this.now();this._timeouts.add({callback:()=>{e(),i()},id:r,time:s+t})};return i(),r}}class fae extends x3{constructor(){super(...arguments),this.lookAhead=0,this.latencyHint=0,this.isOffline=!1}createAnalyser(){return{}}createOscillator(){return{}}createBufferSource(){return{}}createBiquadFilter(){return{}}createBuffer(e,t,r){return{}}createChannelMerger(e){return{}}createChannelSplitter(e){return{}}createConstantSource(){return{}}createConvolver(){return{}}createDelay(e){return{}}createDynamicsCompressor(){return{}}createGain(){return{}}createIIRFilter(e,t){return{}}createPanner(){return{}}createPeriodicWave(e,t,r){return{}}createStereoPanner(){return{}}createWaveShaper(){return{}}createMediaStreamSource(e){return{}}createMediaElementSource(e){return{}}createMediaStreamDestination(){return{}}decodeAudioData(e){return Promise.resolve({})}createAudioWorkletNode(e,t){return{}}get rawContext(){return{}}addAudioWorkletModule(e){return Sr(this,void 0,void 0,function*(){return Promise.resolve()})}resume(){return Promise.resolve()}setTimeout(e,t){return 0}clearTimeout(e){return this}setInterval(e,t){return 0}clearInterval(e){return this}getConstant(e){return{}}get currentTime(){return 0}get state(){return{}}get sampleRate(){return 0}get listener(){return{}}get transport(){return{}}get draw(){return{}}set draw(e){}get destination(){return{}}set destination(e){}now(){return 0}immediate(){return 0}}function Jt(n,e){_s(e)?e.forEach(t=>Jt(n,t)):Object.defineProperty(n,e,{enumerable:!0,writable:!1})}function Fm(n,e){_s(e)?e.forEach(t=>Fm(n,t)):Object.defineProperty(n,e,{writable:!0})}const Tn=()=>{};class Rn extends rl{constructor(){super(),this.name="ToneAudioBuffer",this.onload=Tn;const e=ct(Rn.getDefaults(),arguments,["url","onload","onerror"]);this.reverse=e.reverse,this.onload=e.onload,jc(e.url)?this.load(e.url).catch(e.onerror):e.url&&this.set(e.url)}static getDefaults(){return{onerror:Tn,onload:Tn,reverse:!1}}get sampleRate(){return this._buffer?this._buffer.sampleRate:ji().sampleRate}set(e){return e instanceof Rn?e.loaded?this._buffer=e.get():e.onload=()=>{this.set(e),this.onload(this)}:this._buffer=e,this._reversed&&this._reverse(),this}get(){return this._buffer}load(e){return Sr(this,void 0,void 0,function*(){const t=Rn.load(e).then(r=>{this.set(r),this.onload(this)});Rn.downloads.push(t);try{yield t}finally{const r=Rn.downloads.indexOf(t);Rn.downloads.splice(r,1)}return this})}dispose(){return super.dispose(),this._buffer=void 0,this}fromArray(e){const t=_s(e)&&e[0].length>0,r=t?e.length:1,i=t?e[0].length:e.length,s=ji(),o=s.createBuffer(r,i,s.sampleRate),a=!t&&r===1?[e]:e;for(let c=0;ci/r),this.fromArray(t)}return this}toArray(e){if(Go(e))return this.getChannelData(e);if(this.numberOfChannels===1)return this.toArray(0);{const t=[];for(let r=0;r0}get duration(){return this._buffer?this._buffer.duration:0}get length(){return this._buffer?this._buffer.length:0}get numberOfChannels(){return this._buffer?this._buffer.numberOfChannels:0}get reverse(){return this._reversed}set reverse(e){this._reversed!==e&&(this._reversed=e,this._reverse())}static fromArray(e){return new Rn().fromArray(e)}static fromUrl(e){return Sr(this,void 0,void 0,function*(){return yield new Rn().load(e)})}static load(e){return Sr(this,void 0,void 0,function*(){const t=e.match(/\[([^\]\[]+\|.+)\]$/);if(t){const c=t[1].split("|");let l=c[0];for(const u of c)if(Rn.supportsType(u)){l=u;break}e=e.replace(t[0],l)}const r=Rn.baseUrl===""||Rn.baseUrl.endsWith("/")?Rn.baseUrl:Rn.baseUrl+"/",i=document.createElement("a");i.href=r+e,i.pathname=(i.pathname+i.hash).split("/").map(encodeURIComponent).join("/");const s=yield fetch(i.href);if(!s.ok)throw new Error(`could not load url: ${e}`);const o=yield s.arrayBuffer();return yield ji().decodeAudioData(o)})}static supportsType(e){const t=e.split("."),r=t[t.length-1];return document.createElement("audio").canPlayType("audio/"+r)!==""}static loaded(){return Sr(this,void 0,void 0,function*(){for(yield Promise.resolve();Rn.downloads.length;)yield Rn.downloads[0]})}}Rn.baseUrl="";Rn.downloads=[];class By extends Um{constructor(){super({clockSource:"offline",context:R_(arguments[0])?arguments[0]:tae(arguments[0],arguments[1]*arguments[2],arguments[2]),lookAhead:0,updateInterval:R_(arguments[0])?128/arguments[0].sampleRate:128/arguments[2]}),this.name="OfflineContext",this._currentTime=0,this.isOffline=!0,this._duration=R_(arguments[0])?arguments[0].length/arguments[0].sampleRate:arguments[1]}now(){return this._currentTime}get currentTime(){return this._currentTime}_renderClock(e){return Sr(this,void 0,void 0,function*(){let t=0;for(;this._duration-this._currentTime>=0;){this.emit("tick"),this._currentTime+=128/this.sampleRate,t++;const r=Math.floor(this.sampleRate/128);e&&t%r===0&&(yield new Promise(i=>setTimeout(i,1)))}})}render(){return Sr(this,arguments,void 0,function*(e=!0){yield this.workletsAreReady(),yield this._renderClock(e);const t=yield this._context.startRendering();return new Rn(t)})}close(){return Promise.resolve()}}const S3=new fae;let Hu=S3;function ji(){return Hu===S3&&nae&&dae(new Um),Hu}function dae(n,e=!1){e&&Hu.dispose(),vf(n)?Hu=new Um(n):R_(n)?Hu=new By(n):Hu=n}function pae(){return Hu.resume()}if(Ds&&!Ds.TONE_SILENCE_LOGGING){const e=` * Tone.js v${SU} * `;console.log(`%c${e}`,"background: #000; color: #fff")}function mae(n){return Math.pow(10,n/20)}function gae(n){return 20*(Math.log(n)/Math.LN10)}function E3(n){return Math.pow(2,n/12)}let zy=440;function _ae(){return zy}function vae(n){zy=n}function Gu(n){return Math.round(b3(n))}function b3(n){return 69+12*Math.log2(n/zy)}function T3(n){return zy*Math.pow(2,(n-69)/12)}class xA extends rl{constructor(e,t,r){super(),this.defaultUnits="s",this._val=t,this._units=r,this.context=e,this._expressions=this._getExpressions()}_getExpressions(){return{hz:{method:e=>this._frequencyToUnits(parseFloat(e)),regexp:/^(\d+(?:\.\d+)?)hz$/i},i:{method:e=>this._ticksToUnits(parseInt(e,10)),regexp:/^(\d+)i$/i},m:{method:e=>this._beatsToUnits(parseInt(e,10)*this._getTimeSignature()),regexp:/^(\d+)m$/i},n:{method:(e,t)=>{const r=parseInt(e,10),i=t==="."?1.5:1;return r===1?this._beatsToUnits(this._getTimeSignature())*i:this._beatsToUnits(4/r)*i},regexp:/^(\d+)n(\.?)$/i},number:{method:e=>this._expressions[this.defaultUnits].method.call(this,e),regexp:/^(\d+(?:\.\d+)?)$/},s:{method:e=>this._secondsToUnits(parseFloat(e)),regexp:/^(\d+(?:\.\d+)?)s$/},samples:{method:e=>parseInt(e,10)/this.context.sampleRate,regexp:/^(\d+)samples$/},t:{method:e=>{const t=parseInt(e,10);return this._beatsToUnits(8/(Math.floor(t)*3))},regexp:/^(\d+)t$/i},tr:{method:(e,t,r)=>{let i=0;return e&&e!=="0"&&(i+=this._beatsToUnits(this._getTimeSignature()*parseFloat(e))),t&&t!=="0"&&(i+=this._beatsToUnits(parseFloat(t))),r&&r!=="0"&&(i+=this._beatsToUnits(parseFloat(r)/4)),i},regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?$/}}}valueOf(){if(this._val instanceof xA&&this.fromType(this._val),Hs(this._val))return this._noArg();if(jc(this._val)&&Hs(this._units)){for(const e in this._expressions)if(this._expressions[e].regexp.test(this._val.trim())){this._units=e;break}}else if(Dl(this._val)){let e=0;for(const t in this._val)if(qt(this._val[t])){const r=this._val[t],i=new this.constructor(this.context,t).valueOf()*r;e+=i}return e}if(qt(this._units)){const e=this._expressions[this._units],t=this._val.toString().trim().match(e.regexp);return t?e.method.apply(this,t.slice(1)):e.method.call(this,this._val)}else return jc(this._val)?parseFloat(this._val):this._val}_frequencyToUnits(e){return 1/e}_beatsToUnits(e){return 60/this._getBpm()*e}_secondsToUnits(e){return e}_ticksToUnits(e){return e*this._beatsToUnits(1)/this._getPPQ()}_noArg(){return this._now()}_getBpm(){return this.context.transport.bpm.value}_getTimeSignature(){return this.context.transport.timeSignature}_getPPQ(){return this.context.transport.PPQ}fromType(e){switch(this._units=void 0,this.defaultUnits){case"s":this._val=e.toSeconds();break;case"i":this._val=e.toTicks();break;case"hz":this._val=e.toFrequency();break;case"midi":this._val=e.toMidi();break}return this}toFrequency(){return 1/this.toSeconds()}toSamples(){return this.toSeconds()*this.context.sampleRate}toMilliseconds(){return this.toSeconds()*1e3}}class co extends xA{constructor(){super(...arguments),this.name="TimeClass"}_getExpressions(){return Object.assign(super._getExpressions(),{now:{method:e=>this._now()+new this.constructor(this.context,e).valueOf(),regexp:/^\+(.+)/},quantize:{method:e=>{const t=new co(this.context,e).valueOf();return this._secondsToUnits(this.context.transport.nextSubdivision(t))},regexp:/^@(.+)/}})}quantize(e,t=1){const r=new this.constructor(this.context,e).valueOf(),i=this.valueOf(),a=Math.round(i/r)*r-i;return i+a*t}toNotation(){const e=this.toSeconds(),t=["1m"];for(let s=1;s<9;s++){const o=Math.pow(2,s);t.push(o+"n."),t.push(o+"n"),t.push(o+"t")}t.push("0");let r=t[0],i=new co(this.context,t[0]).toSeconds();return t.forEach(s=>{const o=new co(this.context,s).toSeconds();Math.abs(o-e)3&&(i=parseFloat(parseFloat(s).toFixed(3))),[r,t,i].join(":")}toTicks(){const e=this._beatsToUnits(1);return this.valueOf()/e*this._getPPQ()}toSeconds(){return this.valueOf()}toMidi(){return Gu(this.toFrequency())}_now(){return this.context.now()}}function Ur(n,e){return new co(ji(),n,e)}class ds extends co{constructor(){super(...arguments),this.name="Frequency",this.defaultUnits="hz"}static get A4(){return _ae()}static set A4(e){vae(e)}_getExpressions(){return Object.assign({},super._getExpressions(),{midi:{regexp:/^(\d+(?:\.\d+)?midi)/,method(e){return this.defaultUnits==="midi"?e:ds.mtof(e)}},note:{regexp:/^([a-g]{1}(?:b|#|##|x|bb|###|#x|x#|bbb)?)(-?[0-9]+)/i,method(e,t){const i=yae[e.toLowerCase()]+(parseInt(t,10)+1)*12;return this.defaultUnits==="midi"?i:ds.mtof(i)}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method(e,t,r){let i=1;return e&&e!=="0"&&(i*=this._beatsToUnits(this._getTimeSignature()*parseFloat(e))),t&&t!=="0"&&(i*=this._beatsToUnits(parseFloat(t))),r&&r!=="0"&&(i*=this._beatsToUnits(parseFloat(r)/4)),i}}})}transpose(e){return new ds(this.context,this.valueOf()*E3(e))}harmonize(e){return e.map(t=>this.transpose(t))}toMidi(){return Gu(this.valueOf())}toNote(){const e=this.toFrequency(),t=Math.log2(e/ds.A4);let r=Math.round(12*t)+57;const i=Math.floor(r/12);return i<0&&(r+=-12*i),xae[r%12]+i.toString()}toSeconds(){return 1/super.toSeconds()}toTicks(){const e=this._beatsToUnits(1),t=this.valueOf()/e;return Math.floor(t*this._getPPQ())}_noArg(){return 0}_frequencyToUnits(e){return e}_ticksToUnits(e){return 1/(e*60/(this._getBpm()*this._getPPQ()))}_beatsToUnits(e){return 1/super._beatsToUnits(e)}_secondsToUnits(e){return 1/e}static mtof(e){return T3(e)}static ftom(e){return Gu(e)}}const yae={cbbb:-3,cbb:-2,cb:-1,c:0,"c#":1,cx:2,"c##":2,"c###":3,"cx#":3,"c#x":3,dbbb:-1,dbb:0,db:1,d:2,"d#":3,dx:4,"d##":4,"d###":5,"dx#":5,"d#x":5,ebbb:1,ebb:2,eb:3,e:4,"e#":5,ex:6,"e##":6,"e###":7,"ex#":7,"e#x":7,fbbb:2,fbb:3,fb:4,f:5,"f#":6,fx:7,"f##":7,"f###":8,"fx#":8,"f#x":8,gbbb:4,gbb:5,gb:6,g:7,"g#":8,gx:9,"g##":9,"g###":10,"gx#":10,"g#x":10,abbb:6,abb:7,ab:8,a:9,"a#":10,ax:11,"a##":11,"a###":12,"ax#":12,"a#x":12,bbbb:8,bbb:9,bb:10,b:11,"b#":12,bx:13,"b##":13,"b###":14,"bx#":14,"b#x":14},xae=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function MN(n,e){return new ds(ji(),n,e)}class Bf extends co{constructor(){super(...arguments),this.name="TransportTime"}_now(){return this.context.transport.seconds}}class Ai extends rl{constructor(){super();const e=ct(Ai.getDefaults(),arguments,["context"]);this.defaultContext?this.context=this.defaultContext:this.context=e.context}static getDefaults(){return{context:ji()}}now(){return this.context.currentTime+this.context.lookAhead}immediate(){return this.context.currentTime}get sampleTime(){return 1/this.context.sampleRate}get blockTime(){return 128/this.context.sampleRate}toSeconds(e){return Joe(e),new co(this.context,e).toSeconds()}toFrequency(e){return new ds(this.context,e).toFrequency()}toTicks(e){return new Bf(this.context,e).toTicks()}_getPartialProperties(e){const t=this.get();return Object.keys(t).forEach(r=>{Hs(e[r])&&delete t[r]}),t}get(){const e=cae(this);return Object.keys(e).forEach(t=>{if(Reflect.has(this,t)){const r=this[t];qt(r)&&qt(r.value)&&qt(r.setValueAtTime)?e[t]=r.value:r instanceof Ai?e[t]=r._getPartialProperties(e[t]):_s(r)||Go(r)||jc(r)||p3(r)?e[t]=r:delete e[t]}}),e}set(e){return Object.keys(e).forEach(t=>{Reflect.has(this,t)&&qt(this[t])&&(this[t]&&qt(this[t].value)&&qt(this[t].setValueAtTime)?this[t].value!==e[t]&&(this[t].value=e[t]):this[t]instanceof Ai?this[t].set(e[t]):this[t]=e[t])}),this}}class Bm extends ho{constructor(e="stopped"){super(),this.name="StateTimeline",this._initial=e,this.setStateAtTime(this._initial,0)}getValueAtTime(e){const t=this.get(e);return t!==null?t.state:this._initial}setStateAtTime(e,t,r){return Ha(t,0),this.add(Object.assign({},r,{state:e,time:t})),this}getLastState(e,t){const r=this._search(t);for(let i=r;i>=0;i--){const s=this._timeline[i];if(s.state===e)return s}}getNextState(e,t){const r=this._search(t);if(r!==-1)for(let i=r;i0,"timeConstant must be a number greater than 0");const s=this.toSeconds(t);return this._assertRange(i),wt(isFinite(i)&&isFinite(s),`Invalid argument(s) to setTargetAtTime: ${JSON.stringify(e)}, ${JSON.stringify(t)}`),this._events.add({constant:r,time:s,type:"setTargetAtTime",value:i}),this.log(this.units,"setTargetAtTime",e,s,r),this._param.setTargetAtTime(i,s,r),this}setValueCurveAtTime(e,t,r,i=1){r=this.toSeconds(r),t=this.toSeconds(t);const s=this._fromType(e[0])*i;this.setValueAtTime(this._toType(s),t);const o=r/(e.length-1);for(let a=1;a{i.type==="cancelScheduledValues"?e.cancelScheduledValues(i.time):i.type==="setTargetAtTime"?e.setTargetAtTime(i.value,i.time,i.constant):e[i.type](i.value,i.time)}),this}setParam(e){wt(this._swappable,"The Param must be assigned as 'swappable' in the constructor");const t=this.input;return t.disconnect(this._param),this.apply(e),this._param=e,t.connect(this._param),this}dispose(){return super.dispose(),this._events.dispose(),this}get defaultValue(){return this._toType(this._param.defaultValue)}_exponentialApproach(e,t,r,i,s){return r+(t-r)*Math.exp(-(s-e)/i)}_linearInterpolate(e,t,r,i,s){return t+(i-t)*((s-e)/(r-e))}_exponentialInterpolate(e,t,r,i,s){return t*Math.pow(i/t,(s-e)/(r-e))}}class dt extends Ai{constructor(){super(...arguments),this._internalChannels=[]}get numberOfInputs(){return qt(this.input)?oh(this.input)||this.input instanceof Zt?1:this.input.numberOfInputs:0}get numberOfOutputs(){return qt(this.output)?this.output.numberOfOutputs:0}_isAudioNode(e){return qt(e)&&(e instanceof dt||Ul(e))}_getInternalNodes(){const e=this._internalChannels.slice(0);return this._isAudioNode(this.input)&&e.push(this.input),this._isAudioNode(this.output)&&this.input!==this.output&&e.push(this.output),e}_setChannelProperties(e){this._getInternalNodes().forEach(r=>{r.channelCount=e.channelCount,r.channelCountMode=e.channelCountMode,r.channelInterpretation=e.channelInterpretation})}_getChannelProperties(){const e=this._getInternalNodes();wt(e.length>0,"ToneAudioNode does not have any internal nodes");const t=e[0];return{channelCount:t.channelCount,channelCountMode:t.channelCountMode,channelInterpretation:t.channelInterpretation}}get channelCount(){return this._getChannelProperties().channelCount}set channelCount(e){const t=this._getChannelProperties();this._setChannelProperties(Object.assign(t,{channelCount:e}))}get channelCountMode(){return this._getChannelProperties().channelCountMode}set channelCountMode(e){const t=this._getChannelProperties();this._setChannelProperties(Object.assign(t,{channelCountMode:e}))}get channelInterpretation(){return this._getChannelProperties().channelInterpretation}set channelInterpretation(e){const t=this._getChannelProperties();this._setChannelProperties(Object.assign(t,{channelInterpretation:e}))}connect(e,t=0,r=0){return Wo(this,e,t,r),this}toDestination(){return this.connect(this.context.destination),this}toMaster(){return Dy("toMaster() has been renamed toDestination()"),this.toDestination()}disconnect(e,t=0,r=0){return w3(this,e,t,r),this}chain(...e){return ah(this,...e),this}fan(...e){return e.forEach(t=>this.connect(t)),this}dispose(){return super.dispose(),qt(this.input)&&(this.input instanceof dt?this.input.dispose():Ul(this.input)&&this.input.disconnect()),qt(this.output)&&(this.output instanceof dt?this.output.dispose():Ul(this.output)&&this.output.disconnect()),this._internalChannels=[],this}}function ah(...n){const e=n.shift();n.reduce((t,r)=>(t instanceof dt?t.connect(r):Ul(t)&&Wo(t,r),r),e)}function Wo(n,e,t=0,r=0){for(wt(qt(n),"Cannot connect from undefined node"),wt(qt(e),"Cannot connect to undefined node"),(e instanceof dt||Ul(e))&&wt(e.numberOfInputs>0,"Cannot connect to node with no inputs"),wt(n.numberOfOutputs>0,"Cannot connect from node with no outputs");e instanceof dt||e instanceof Zt;)qt(e.input)&&(e=e.input);for(;n instanceof dt;)qt(n.output)&&(n=n.output);oh(e)?n.connect(e,t):n.connect(e,t,r)}function w3(n,e,t=0,r=0){if(qt(e))for(;e instanceof dt;)e=e.input;for(;!Ul(n);)qt(n.output)&&(n=n.output);oh(e)?n.disconnect(e,t):Ul(e)?n.disconnect(e,t,r):n.disconnect()}class Xt extends dt{constructor(){const e=ct(Xt.getDefaults(),arguments,["gain","units"]);super(e),this.name="Gain",this._gainNode=this.context.createGain(),this.input=this._gainNode,this.output=this._gainNode,this.gain=new Zt({context:this.context,convert:e.convert,param:this._gainNode.gain,units:e.units,value:e.gain,minValue:e.minValue,maxValue:e.maxValue}),Jt(this,"gain")}static getDefaults(){return Object.assign(dt.getDefaults(),{convert:!0,gain:1,units:"gain"})}dispose(){return super.dispose(),this._gainNode.disconnect(),this.gain.dispose(),this}}class ld extends dt{constructor(e){super(e),this.onended=Tn,this._startTime=-1,this._stopTime=-1,this._timeout=-1,this.output=new Xt({context:this.context,gain:0}),this._gainNode=this.output,this.getStateAtTime=function(t){const r=this.toSeconds(t);return this._startTime!==-1&&r>=this._startTime&&(this._stopTime===-1||r<=this._stopTime)?"started":"stopped"},this._fadeIn=e.fadeIn,this._fadeOut=e.fadeOut,this._curve=e.curve,this.onended=e.onended}static getDefaults(){return Object.assign(dt.getDefaults(),{curve:"linear",fadeIn:0,fadeOut:0,onended:Tn})}_startGain(e,t=1){wt(this._startTime===-1,"Source cannot be started more than once");const r=this.toSeconds(this._fadeIn);return this._startTime=e+r,this._startTime=Math.max(this._startTime,this.context.currentTime),r>0?(this._gainNode.gain.setValueAtTime(0,e),this._curve==="linear"?this._gainNode.gain.linearRampToValueAtTime(t,e+r):this._gainNode.gain.exponentialApproachValueAtTime(t,e,r)):this._gainNode.gain.setValueAtTime(t,e),this}stop(e){return this.log("stop",e),this._stopGain(this.toSeconds(e)),this}_stopGain(e){wt(this._startTime!==-1,"'start' must be called before 'stop'"),this.cancelStop();const t=this.toSeconds(this._fadeOut);return this._stopTime=this.toSeconds(e)+t,this._stopTime=Math.max(this._stopTime,this.now()),t>0?this._curve==="linear"?this._gainNode.gain.linearRampTo(0,t,e):this._gainNode.gain.targetRampTo(0,t,e):(this._gainNode.gain.cancelAndHoldAtTime(e),this._gainNode.gain.setValueAtTime(0,e)),this.context.clearTimeout(this._timeout),this._timeout=this.context.setTimeout(()=>{const r=this._curve==="exponential"?t*2:0;this._stopSource(this.now()+r),this._onended()},this._stopTime-this.context.currentTime),this}_onended(){if(this.onended!==Tn&&(this.onended(this),this.onended=Tn,!this.context.isOffline)){const e=()=>this.dispose();typeof window.requestIdleCallback<"u"?window.requestIdleCallback(e):setTimeout(e,1e3)}}get state(){return this.getStateAtTime(this.now())}cancelStop(){return this.log("cancelStop"),wt(this._startTime!==-1,"Source is not started"),this._gainNode.gain.cancelScheduledValues(this._startTime+this.sampleTime),this.context.clearTimeout(this._timeout),this._stopTime=-1,this}dispose(){return super.dispose(),this._gainNode.dispose(),this.onended=Tn,this}}class SA extends ld{constructor(){const e=ct(SA.getDefaults(),arguments,["offset"]);super(e),this.name="ToneConstantSource",this._source=this.context.createConstantSource(),Wo(this._source,this._gainNode),this.offset=new Zt({context:this.context,convert:e.convert,param:this._source.offset,units:e.units,value:e.offset,minValue:e.minValue,maxValue:e.maxValue})}static getDefaults(){return Object.assign(ld.getDefaults(),{convert:!0,offset:1,units:"number"})}start(e){const t=this.toSeconds(e);return this.log("start",t),this._startGain(t),this._source.start(t),this}_stopSource(e){this._source.stop(e)}dispose(){return super.dispose(),this.state==="started"&&this.stop(),this._source.disconnect(),this.offset.dispose(),this}}class Sn extends dt{constructor(){const e=ct(Sn.getDefaults(),arguments,["value","units"]);super(e),this.name="Signal",this.override=!0,this.output=this._constantSource=new SA({context:this.context,convert:e.convert,offset:e.value,units:e.units,minValue:e.minValue,maxValue:e.maxValue}),this._constantSource.start(0),this.input=this._param=this._constantSource.offset}static getDefaults(){return Object.assign(dt.getDefaults(),{convert:!0,units:"number",value:0})}connect(e,t=0,r=0){return Vy(this,e,t,r),this}dispose(){return super.dispose(),this._param.dispose(),this._constantSource.dispose(),this}setValueAtTime(e,t){return this._param.setValueAtTime(e,t),this}getValueAtTime(e){return this._param.getValueAtTime(e)}setRampPoint(e){return this._param.setRampPoint(e),this}linearRampToValueAtTime(e,t){return this._param.linearRampToValueAtTime(e,t),this}exponentialRampToValueAtTime(e,t){return this._param.exponentialRampToValueAtTime(e,t),this}exponentialRampTo(e,t,r){return this._param.exponentialRampTo(e,t,r),this}linearRampTo(e,t,r){return this._param.linearRampTo(e,t,r),this}targetRampTo(e,t,r){return this._param.targetRampTo(e,t,r),this}exponentialApproachValueAtTime(e,t,r){return this._param.exponentialApproachValueAtTime(e,t,r),this}setTargetAtTime(e,t,r){return this._param.setTargetAtTime(e,t,r),this}setValueCurveAtTime(e,t,r,i){return this._param.setValueCurveAtTime(e,t,r,i),this}cancelScheduledValues(e){return this._param.cancelScheduledValues(e),this}cancelAndHoldAtTime(e){return this._param.cancelAndHoldAtTime(e),this}rampTo(e,t,r){return this._param.rampTo(e,t,r),this}get value(){return this._param.value}set value(e){this._param.value=e}get convert(){return this._param.convert}set convert(e){this._param.convert=e}get units(){return this._param.units}get overridden(){return this._param.overridden}set overridden(e){this._param.overridden=e}get maxValue(){return this._param.maxValue}get minValue(){return this._param.minValue}apply(e){return this._param.apply(e),this}}function Vy(n,e,t,r){(e instanceof Zt||oh(e)||e instanceof Sn&&e.override)&&(e.cancelScheduledValues(0),e.setValueAtTime(0,0),e instanceof Sn&&(e.overridden=!0)),Wo(n,e,t,r)}class EA extends Zt{constructor(){const e=ct(EA.getDefaults(),arguments,["value"]);super(e),this.name="TickParam",this._events=new ho(1/0),this._multiplier=1,this._multiplier=e.multiplier,this._events.cancel(0),this._events.add({ticks:0,time:0,type:"setValueAtTime",value:this._fromType(e.value)}),this.setValueAtTime(e.value,0)}static getDefaults(){return Object.assign(Zt.getDefaults(),{multiplier:1,units:"hertz",value:1})}setTargetAtTime(e,t,r){t=this.toSeconds(t),this.setRampPoint(t);const i=this._fromType(e),s=this._events.get(t),o=Math.round(Math.max(1/r,1));for(let a=0;a<=o;a++){const c=r*a+t,l=this._exponentialApproach(s.time,s.value,i,r,c);this.linearRampToValueAtTime(this._toType(l),c)}return this}setValueAtTime(e,t){const r=this.toSeconds(t);super.setValueAtTime(e,t);const i=this._events.get(r),s=this._events.previousEvent(i),o=this._getTicksUntilEvent(s,r);return i.ticks=Math.max(o,0),this}linearRampToValueAtTime(e,t){const r=this.toSeconds(t);super.linearRampToValueAtTime(e,t);const i=this._events.get(r),s=this._events.previousEvent(i),o=this._getTicksUntilEvent(s,r);return i.ticks=Math.max(o,0),this}exponentialRampToValueAtTime(e,t){t=this.toSeconds(t);const r=this._fromType(e),i=this._events.get(t),s=Math.round(Math.max((t-i.time)*10,1)),o=(t-i.time)/s;for(let a=0;a<=s;a++){const c=o*a+i.time,l=this._exponentialInterpolate(i.time,i.value,t,r,c);this.linearRampToValueAtTime(this._toType(l),c)}return this}_getTicksUntilEvent(e,t){if(e===null)e={ticks:0,time:0,type:"setValueAtTime",value:0};else if(Hs(e.ticks)){const o=this._events.previousEvent(e);e.ticks=this._getTicksUntilEvent(o,e.time)}const r=this._fromType(this.getValueAtTime(e.time));let i=this._fromType(this.getValueAtTime(t));const s=this._events.get(t);return s&&s.time===t&&s.type==="setValueAtTime"&&(i=this._fromType(this.getValueAtTime(t-this.sampleTime))),.5*(t-e.time)*(r+i)+e.ticks}getTicksAtTime(e){const t=this.toSeconds(e),r=this._events.get(t);return Math.max(this._getTicksUntilEvent(r,t),0)}getDurationOfTicks(e,t){const r=this.toSeconds(t),i=this.getTicksAtTime(t);return this.getTimeOfTick(i+e)-r}getTimeOfTick(e){const t=this._events.get(e,"ticks"),r=this._events.getAfter(e,"ticks");if(t&&t.ticks===e)return t.time;if(t&&r&&r.type==="linearRampToValueAtTime"&&t.value!==r.value){const i=this._fromType(this.getValueAtTime(t.time)),o=(this._fromType(this.getValueAtTime(r.time))-i)/(r.time-t.time),a=Math.sqrt(Math.pow(i,2)-2*o*(t.ticks-e)),c=(-i+a)/o,l=(-i-a)/o;return(c>0?c:l)+t.time}else return t?t.value===0?1/0:t.time+(e-t.ticks)/t.value:e/this._initialValue}ticksToTime(e,t){return this.getDurationOfTicks(e,t)}timeToTicks(e,t){const r=this.toSeconds(t),i=this.toSeconds(e),s=this.getTicksAtTime(r);return this.getTicksAtTime(r+i)-s}_fromType(e){return this.units==="bpm"&&this.multiplier?1/(60/e/this.multiplier):super._fromType(e)}_toType(e){return this.units==="bpm"&&this.multiplier?e/this.multiplier*60:super._toType(e)}get multiplier(){return this._multiplier}set multiplier(e){const t=this.value;this._multiplier=e,this.cancelScheduledValues(0),this.setValueAtTime(t,0)}}class bA extends Sn{constructor(){const e=ct(bA.getDefaults(),arguments,["value"]);super(e),this.name="TickSignal",this.input=this._param=new EA({context:this.context,convert:e.convert,multiplier:e.multiplier,param:this._constantSource.offset,units:e.units,value:e.value})}static getDefaults(){return Object.assign(Sn.getDefaults(),{multiplier:1,units:"hertz",value:1})}ticksToTime(e,t){return this._param.ticksToTime(e,t)}timeToTicks(e,t){return this._param.timeToTicks(e,t)}getTimeOfTick(e){return this._param.getTimeOfTick(e)}getDurationOfTicks(e,t){return this._param.getDurationOfTicks(e,t)}getTicksAtTime(e){return this._param.getTicksAtTime(e)}get multiplier(){return this._param.multiplier}set multiplier(e){this._param.multiplier=e}dispose(){return super.dispose(),this._param.dispose(),this}}class TA extends Ai{constructor(){const e=ct(TA.getDefaults(),arguments,["frequency"]);super(e),this.name="TickSource",this._state=new Bm,this._tickOffset=new ho,this._ticksAtTime=new ho,this._secondsAtTime=new ho,this.frequency=new bA({context:this.context,units:e.units,value:e.frequency}),Jt(this,"frequency"),this._state.setStateAtTime("stopped",0),this.setTicksAtTime(0,0)}static getDefaults(){return Object.assign({frequency:1,units:"hertz"},Ai.getDefaults())}get state(){return this.getStateAtTime(this.now())}start(e,t){const r=this.toSeconds(e);return this._state.getValueAtTime(r)!=="started"&&(this._state.setStateAtTime("started",r),qt(t)&&this.setTicksAtTime(t,r),this._ticksAtTime.cancel(r),this._secondsAtTime.cancel(r)),this}stop(e){const t=this.toSeconds(e);if(this._state.getValueAtTime(t)==="stopped"){const r=this._state.get(t);r&&r.time>0&&(this._tickOffset.cancel(r.time),this._state.cancel(r.time))}return this._state.cancel(t),this._state.setStateAtTime("stopped",t),this.setTicksAtTime(0,t),this._ticksAtTime.cancel(t),this._secondsAtTime.cancel(t),this}pause(e){const t=this.toSeconds(e);return this._state.getValueAtTime(t)==="started"&&(this._state.setStateAtTime("paused",t),this._ticksAtTime.cancel(t),this._secondsAtTime.cancel(t)),this}cancel(e){return e=this.toSeconds(e),this._state.cancel(e),this._tickOffset.cancel(e),this._ticksAtTime.cancel(e),this._secondsAtTime.cancel(e),this}getTicksAtTime(e){const t=this.toSeconds(e),r=this._state.getLastState("stopped",t),i=this._ticksAtTime.get(t),s={state:"paused",time:t};this._state.add(s);let o=i||r,a=i?i.ticks:0,c=null;return this._state.forEachBetween(o.time,t+this.sampleTime,l=>{let u=o.time;const h=this._tickOffset.get(l.time);h&&h.time>=o.time&&(a=h.ticks,u=h.time),o.state==="started"&&l.state!=="started"&&(a+=this.frequency.getTicksAtTime(l.time)-this.frequency.getTicksAtTime(u),l.time!==s.time&&(c={state:l.state,time:l.time,ticks:a})),o=l}),this._state.remove(s),c&&this._ticksAtTime.add(c),a}get ticks(){return this.getTicksAtTime(this.now())}set ticks(e){this.setTicksAtTime(e,this.now())}get seconds(){return this.getSecondsAtTime(this.now())}set seconds(e){const t=this.now(),r=this.frequency.timeToTicks(e,t);this.setTicksAtTime(r,t)}getSecondsAtTime(e){e=this.toSeconds(e);const t=this._state.getLastState("stopped",e),r={state:"paused",time:e};this._state.add(r);const i=this._secondsAtTime.get(e);let s=i||t,o=i?i.seconds:0,a=null;return this._state.forEachBetween(s.time,e+this.sampleTime,c=>{let l=s.time;const u=this._tickOffset.get(c.time);u&&u.time>=s.time&&(o=u.seconds,l=u.time),s.state==="started"&&c.state!=="started"&&(o+=c.time-l,c.time!==r.time&&(a={state:c.state,time:c.time,seconds:o})),s=c}),this._state.remove(r),a&&this._secondsAtTime.add(a),o}setTicksAtTime(e,t){return t=this.toSeconds(t),this._tickOffset.cancel(t),this._tickOffset.add({seconds:this.frequency.getDurationOfTicks(e,t),ticks:e,time:t}),this._ticksAtTime.cancel(t),this._secondsAtTime.cancel(t),this}getStateAtTime(e){return e=this.toSeconds(e),this._state.getValueAtTime(e)}getTimeOfTick(e,t=this.now()){const r=this._tickOffset.get(t),i=this._state.get(t),s=Math.max(r.time,i.time),o=this.frequency.getTicksAtTime(s)+e-r.ticks;return this.frequency.getTimeOfTick(o)}forEachTickBetween(e,t,r){let i=this._state.get(e);this._state.forEachBetween(e,t,o=>{i&&i.state==="started"&&o.state!=="started"&&this.forEachTickBetween(Math.max(i.time,e),o.time-this.sampleTime,r),i=o});let s=null;if(i&&i.state==="started"){const o=Math.max(i.time,e),a=this.frequency.getTicksAtTime(o),c=this.frequency.getTicksAtTime(i.time),l=a-c;let u=Math.ceil(l)-l;u=Ro(u,1)?0:u;let h=this.frequency.getTimeOfTick(a+u);for(;h{switch(r.state){case"started":const i=this._tickSource.getTicksAtTime(r.time);this.emit("start",r.time,i);break;case"stopped":r.time!==0&&this.emit("stop",r.time);break;case"paused":this.emit("pause",r.time);break}}),this._tickSource.forEachTickBetween(e,t,(r,i)=>{this.callback(r,i)}))}getStateAtTime(e){const t=this.toSeconds(e);return this._state.getValueAtTime(t)}dispose(){return super.dispose(),this.context.off("tick",this._boundLoop),this._tickSource.dispose(),this._state.dispose(),this}}Dm.mixin(Hy);class ud extends dt{constructor(){const e=ct(ud.getDefaults(),arguments,["delayTime","maxDelay"]);super(e),this.name="Delay";const t=this.toSeconds(e.maxDelay);this._maxDelay=Math.max(t,this.toSeconds(e.delayTime)),this._delayNode=this.input=this.output=this.context.createDelay(t),this.delayTime=new Zt({context:this.context,param:this._delayNode.delayTime,units:"time",value:e.delayTime,minValue:0,maxValue:this.maxDelay}),Jt(this,"delayTime")}static getDefaults(){return Object.assign(dt.getDefaults(),{delayTime:0,maxDelay:1})}get maxDelay(){return this._maxDelay}dispose(){return super.dispose(),this._delayNode.disconnect(),this.delayTime.dispose(),this}}class Xl extends dt{constructor(){const e=ct(Xl.getDefaults(),arguments,["volume"]);super(e),this.name="Volume",this.input=this.output=new Xt({context:this.context,gain:e.volume,units:"decibels"}),this.volume=this.output.gain,Jt(this,"volume"),this._unmutedVolume=e.volume,this.mute=e.mute}static getDefaults(){return Object.assign(dt.getDefaults(),{mute:!1,volume:0})}get mute(){return this.volume.value===-1/0}set mute(e){!this.mute&&e?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!e&&(this.volume.value=this._unmutedVolume)}dispose(){return super.dispose(),this.input.dispose(),this.volume.dispose(),this}}class wA extends dt{constructor(){const e=ct(wA.getDefaults(),arguments);super(e),this.name="Destination",this.input=new Xl({context:this.context}),this.output=new Xt({context:this.context}),this.volume=this.input.volume,ah(this.input,this.output,this.context.rawContext.destination),this.mute=e.mute,this._internalChannels=[this.input,this.context.rawContext.destination,this.output]}static getDefaults(){return Object.assign(dt.getDefaults(),{mute:!1,volume:0})}get mute(){return this.input.mute}set mute(e){this.input.mute=e}chain(...e){return this.input.disconnect(),e.unshift(this.input),e.push(this.output),ah(...e),this}get maxChannelCount(){return this.context.rawContext.destination.maxChannelCount}dispose(){return super.dispose(),this.volume.dispose(),this}}Uy(n=>{n.destination=new wA({context:n})});Fy(n=>{n.destination.dispose()});class Sae extends dt{constructor(){super(...arguments),this.name="Listener",this.positionX=new Zt({context:this.context,param:this.context.rawContext.listener.positionX}),this.positionY=new Zt({context:this.context,param:this.context.rawContext.listener.positionY}),this.positionZ=new Zt({context:this.context,param:this.context.rawContext.listener.positionZ}),this.forwardX=new Zt({context:this.context,param:this.context.rawContext.listener.forwardX}),this.forwardY=new Zt({context:this.context,param:this.context.rawContext.listener.forwardY}),this.forwardZ=new Zt({context:this.context,param:this.context.rawContext.listener.forwardZ}),this.upX=new Zt({context:this.context,param:this.context.rawContext.listener.upX}),this.upY=new Zt({context:this.context,param:this.context.rawContext.listener.upY}),this.upZ=new Zt({context:this.context,param:this.context.rawContext.listener.upZ})}static getDefaults(){return Object.assign(dt.getDefaults(),{positionX:0,positionY:0,positionZ:0,forwardX:0,forwardY:0,forwardZ:-1,upX:0,upY:1,upZ:0})}dispose(){return super.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this.forwardX.dispose(),this.forwardY.dispose(),this.forwardZ.dispose(),this.upX.dispose(),this.upY.dispose(),this.upZ.dispose(),this}}Uy(n=>{n.listener=new Sae({context:n})});Fy(n=>{n.listener.dispose()});class AA extends rl{constructor(){super(),this.name="ToneAudioBuffers",this._buffers=new Map,this._loadingCount=0;const e=ct(AA.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");this.baseUrl=e.baseUrl,Object.keys(e.urls).forEach(t=>{this._loadingCount++;const r=e.urls[t];this.add(t,r,this._bufferLoaded.bind(this,e.onload),e.onerror)})}static getDefaults(){return{baseUrl:"",onerror:Tn,onload:Tn,urls:{}}}has(e){return this._buffers.has(e.toString())}get(e){return wt(this.has(e),`ToneAudioBuffers has no buffer named: ${e}`),this._buffers.get(e.toString())}_bufferLoaded(e){this._loadingCount--,this._loadingCount===0&&e&&e()}get loaded(){return Array.from(this._buffers).every(([e,t])=>t.loaded)}add(e,t,r=Tn,i=Tn){return jc(t)?(this.baseUrl&&t.trim().substring(0,11).toLowerCase()==="data:audio/"&&(this.baseUrl=""),this._buffers.set(e.toString(),new Rn(this.baseUrl+t,r,i))):this._buffers.set(e.toString(),new Rn(t,r,i)),this}dispose(){return super.dispose(),this._buffers.forEach(e=>e.dispose()),this._buffers.clear(),this}}class Sv extends ds{constructor(){super(...arguments),this.name="MidiClass",this.defaultUnits="midi"}_frequencyToUnits(e){return Gu(super._frequencyToUnits(e))}_ticksToUnits(e){return Gu(super._ticksToUnits(e))}_beatsToUnits(e){return Gu(super._beatsToUnits(e))}_secondsToUnits(e){return Gu(super._secondsToUnits(e))}toMidi(){return this.valueOf()}toFrequency(){return T3(this.toMidi())}transpose(e){return new Sv(this.context,this.toMidi()+e)}}class zr extends Bf{constructor(){super(...arguments),this.name="Ticks",this.defaultUnits="i"}_now(){return this.context.transport.ticks}_beatsToUnits(e){return this._getPPQ()*e}_secondsToUnits(e){return Math.floor(e/(60/this._getBpm())*this._getPPQ())}_ticksToUnits(e){return e}toTicks(){return this.valueOf()}toSeconds(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())}}class Eae extends Ai{constructor(){super(...arguments),this.name="Draw",this.expiration=.25,this.anticipation=.008,this._events=new ho,this._boundDrawLoop=this._drawLoop.bind(this),this._animationFrame=-1}schedule(e,t){return this._events.add({callback:e,time:this.toSeconds(t)}),this._events.length===1&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop)),this}cancel(e){return this._events.cancel(this.toSeconds(e)),this}_drawLoop(){const e=this.context.currentTime;for(;this._events.length&&this._events.peek().time-this.anticipation<=e;){const t=this._events.shift();t&&e-t.time<=this.expiration&&t.callback()}this._events.length>0&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop))}dispose(){return super.dispose(),this._events.dispose(),cancelAnimationFrame(this._animationFrame),this}}Uy(n=>{n.draw=new Eae({context:n})});Fy(n=>{n.draw.dispose()});class bae extends rl{constructor(){super(...arguments),this.name="IntervalTimeline",this._root=null,this._length=0}add(e){wt(qt(e.time),"Events must have a time property"),wt(qt(e.duration),"Events must have a duration parameter"),e.time=e.time.valueOf();let t=new Tae(e.time,e.time+e.duration,e);for(this._root===null?this._root=t:this._root.insert(t),this._length++;t!==null;)t.updateHeight(),t.updateMax(),this._rebalance(t),t=t.parent;return this}remove(e){if(this._root!==null){const t=[];this._root.search(e.time,t);for(const r of t)if(r.event===e){this._removeNode(r),this._length--;break}}return this}get length(){return this._length}cancel(e){return this.forEachFrom(e,t=>this.remove(t)),this}_setRoot(e){this._root=e,this._root!==null&&(this._root.parent=null)}_replaceNodeInParent(e,t){e.parent!==null?(e.isLeftChild()?e.parent.left=t:e.parent.right=t,this._rebalance(e.parent)):this._setRoot(t)}_removeNode(e){if(e.left===null&&e.right===null)this._replaceNodeInParent(e,null);else if(e.right===null)this._replaceNodeInParent(e,e.left);else if(e.left===null)this._replaceNodeInParent(e,e.right);else{const t=e.getBalance();let r,i=null;if(t>0)if(e.left.right===null)r=e.left,r.right=e.right,i=r;else{for(r=e.left.right;r.right!==null;)r=r.right;r.parent&&(r.parent.right=r.left,i=r.parent,r.left=e.left,r.right=e.right)}else if(e.right.left===null)r=e.right,r.left=e.left,i=r;else{for(r=e.right.left;r.left!==null;)r=r.left;r.parent&&(r.parent.left=r.right,i=r.parent,r.left=e.left,r.right=e.right)}e.parent!==null?e.isLeftChild()?e.parent.left=r:e.parent.right=r:this._setRoot(r),i&&this._rebalance(i)}e.dispose()}_rotateLeft(e){const t=e.parent,r=e.isLeftChild(),i=e.right;i&&(e.right=i.left,i.left=e),t!==null?r?t.left=i:t.right=i:this._setRoot(i)}_rotateRight(e){const t=e.parent,r=e.isLeftChild(),i=e.left;i&&(e.left=i.right,i.right=e),t!==null?r?t.left=i:t.right=i:this._setRoot(i)}_rebalance(e){const t=e.getBalance();t>1&&e.left?e.left.getBalance()<0?this._rotateLeft(e.left):this._rotateRight(e):t<-1&&e.right&&(e.right.getBalance()>0?this._rotateRight(e.right):this._rotateLeft(e))}get(e){if(this._root!==null){const t=[];if(this._root.search(e,t),t.length>0){let r=t[0];for(let i=1;ir.low&&(r=t[i]);return r.event}}return null}forEach(e){if(this._root!==null){const t=[];this._root.traverse(r=>t.push(r)),t.forEach(r=>{r.event&&e(r.event)})}return this}forEachAtTime(e,t){if(this._root!==null){const r=[];this._root.search(e,r),r.forEach(i=>{i.event&&t(i.event)})}return this}forEachFrom(e,t){if(this._root!==null){const r=[];this._root.searchAfter(e,r),r.forEach(i=>{i.event&&t(i.event)})}return this}dispose(){return super.dispose(),this._root!==null&&this._root.traverse(e=>e.dispose()),this._root=null,this}}class Tae{constructor(e,t,r){this._left=null,this._right=null,this.parent=null,this.height=0,this.event=r,this.low=e,this.high=t,this.max=this.high}insert(e){e.low<=this.low?this.left===null?this.left=e:this.left.insert(e):this.right===null?this.right=e:this.right.insert(e)}search(e,t){e>this.max||(this.left!==null&&this.left.search(e,t),this.low<=e&&this.high>e&&t.push(this),!(this.low>e)&&this.right!==null&&this.right.search(e,t))}searchAfter(e,t){this.low>=e&&(t.push(this),this.left!==null&&this.left.searchAfter(e,t)),this.right!==null&&this.right.searchAfter(e,t)}traverse(e){e(this),this.left!==null&&this.left.traverse(e),this.right!==null&&this.right.traverse(e)}updateHeight(){this.left!==null&&this.right!==null?this.height=Math.max(this.left.height,this.right.height)+1:this.right!==null?this.height=this.right.height+1:this.left!==null?this.height=this.left.height+1:this.height=0}updateMax(){this.max=this.high,this.left!==null&&(this.max=Math.max(this.max,this.left.max)),this.right!==null&&(this.max=Math.max(this.max,this.right.max))}getBalance(){let e=0;return this.left!==null&&this.right!==null?e=this.left.height-this.right.height:this.left!==null?e=this.left.height+1:this.right!==null&&(e=-(this.right.height+1)),e}isLeftChild(){return this.parent!==null&&this.parent.left===this}get left(){return this._left}set left(e){this._left=e,e!==null&&(e.parent=this),this.updateHeight(),this.updateMax()}get right(){return this._right}set right(e){this._right=e,e!==null&&(e.parent=this),this.updateHeight(),this.updateMax()}dispose(){this.parent=null,this._left=null,this._right=null,this.event=null}}class wae extends rl{constructor(e){super(),this.name="TimelineValue",this._timeline=new ho({memory:10}),this._initialValue=e}set(e,t){return this._timeline.add({value:e,time:t}),this}get(e){const t=this._timeline.get(e);return t?t.value:this._initialValue}}class Ga extends dt{constructor(){super(ct(Ga.getDefaults(),arguments,["context"]))}connect(e,t=0,r=0){return Vy(this,e,t,r),this}}class Th extends Ga{constructor(){const e=ct(Th.getDefaults(),arguments,["mapping","length"]);super(e),this.name="WaveShaper",this._shaper=this.context.createWaveShaper(),this.input=this._shaper,this.output=this._shaper,_s(e.mapping)||e.mapping instanceof Float32Array?this.curve=Float32Array.from(e.mapping):Zoe(e.mapping)&&this.setMap(e.mapping,e.length)}static getDefaults(){return Object.assign(Sn.getDefaults(),{length:1024})}setMap(e,t=1024){const r=new Float32Array(t);for(let i=0,s=t;ir.includes(e));wt(t,"oversampling must be either 'none', '2x', or '4x'"),this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.disconnect(),this}}class MA extends Ga{constructor(){const e=ct(MA.getDefaults(),arguments,["value"]);super(e),this.name="Pow",this._exponentScaler=this.input=this.output=new Th({context:this.context,mapping:this._expFunc(e.value),length:8192}),this._exponent=e.value}static getDefaults(){return Object.assign(Ga.getDefaults(),{value:1})}_expFunc(e){return t=>Math.pow(Math.abs(t),e)}get value(){return this._exponent}set value(e){this._exponent=e,this._exponentScaler.setMap(this._expFunc(this._exponent))}dispose(){return super.dispose(),this._exponentScaler.dispose(),this}}class Kl{constructor(e,t){this.id=Kl._eventId++,this._remainderTime=0;const r=Object.assign(Kl.getDefaults(),t);this.transport=e,this.callback=r.callback,this._once=r.once,this.time=Math.floor(r.time),this._remainderTime=r.time-this.time}static getDefaults(){return{callback:Tn,once:!1,time:0}}get floatTime(){return this.time+this._remainderTime}invoke(e){if(this.callback){const t=this.transport.bpm.getDurationOfTicks(1,e);this.callback(e+this._remainderTime*t),this._once&&this.transport.clear(this.id)}}dispose(){return this.callback=void 0,this}}Kl._eventId=0;class CA extends Kl{constructor(e,t){super(e,t),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this);const r=Object.assign(CA.getDefaults(),t);this.duration=r.duration,this._interval=r.interval,this._nextTick=r.time,this.transport.on("start",this._boundRestart),this.transport.on("loopStart",this._boundRestart),this.transport.on("ticks",this._boundRestart),this.context=this.transport.context,this._restart()}static getDefaults(){return Object.assign({},Kl.getDefaults(),{duration:1/0,interval:1,once:!1})}invoke(e){this._createEvents(e),super.invoke(e)}_createEvent(){return xv(this._nextTick,this.floatTime+this.duration)?this.transport.scheduleOnce(this.invoke.bind(this),new zr(this.context,this._nextTick).toSeconds()):-1}_createEvents(e){xv(this._nextTick+this._interval,this.floatTime+this.duration)&&(this._nextTick+=this._interval,this._currentId=this._nextId,this._nextId=this.transport.scheduleOnce(this.invoke.bind(this),new zr(this.context,this._nextTick).toSeconds()))}_restart(e){this.transport.clear(this._currentId),this.transport.clear(this._nextId),this._nextTick=this.floatTime;const t=this.transport.getTicksAtTime(e);cd(t,this.time)&&(this._nextTick=this.floatTime+Math.ceil((t-this.floatTime)/this._interval)*this._interval),this._currentId=this._createEvent(),this._nextTick+=this._interval,this._nextId=this._createEvent()}dispose(){return super.dispose(),this.transport.clear(this._currentId),this.transport.clear(this._nextId),this.transport.off("start",this._boundRestart),this.transport.off("loopStart",this._boundRestart),this.transport.off("ticks",this._boundRestart),this}}class Gy extends Ai{constructor(){const e=ct(Gy.getDefaults(),arguments);super(e),this.name="Transport",this._loop=new wae(!1),this._loopStart=0,this._loopEnd=0,this._scheduledEvents={},this._timeline=new ho,this._repeatedEvents=new bae,this._syncedSignals=[],this._swingAmount=0,this._ppq=e.ppq,this._clock=new Hy({callback:this._processTick.bind(this),context:this.context,frequency:0,units:"bpm"}),this._bindClockEvents(),this.bpm=this._clock.frequency,this._clock.frequency.multiplier=e.ppq,this.bpm.setValueAtTime(e.bpm,0),Jt(this,"bpm"),this._timeSignature=e.timeSignature,this._swingTicks=e.ppq/2}static getDefaults(){return Object.assign(Ai.getDefaults(),{bpm:120,loopEnd:"4m",loopStart:0,ppq:192,swing:0,swingSubdivision:"8n",timeSignature:4})}_processTick(e,t){if(this._loop.get(e)&&t>=this._loopEnd&&(this.emit("loopEnd",e),this._clock.setTicksAtTime(this._loopStart,e),t=this._loopStart,this.emit("loopStart",e,this._clock.getSecondsAtTime(e)),this.emit("loop",e)),this._swingAmount>0&&t%this._ppq!==0&&t%(this._swingTicks*2)!==0){const r=t%(this._swingTicks*2)/(this._swingTicks*2),i=Math.sin(r*Math.PI)*this._swingAmount;e+=new zr(this.context,this._swingTicks*2/3).toSeconds()*i}AN(!0),this._timeline.forEachAtTime(t,r=>r.invoke(e)),AN(!1)}schedule(e,t){const r=new Kl(this,{callback:e,time:new Bf(this.context,t).toTicks()});return this._addEvent(r,this._timeline)}scheduleRepeat(e,t,r,i=1/0){const s=new CA(this,{callback:e,duration:new co(this.context,i).toTicks(),interval:new co(this.context,t).toTicks(),time:new Bf(this.context,r).toTicks()});return this._addEvent(s,this._repeatedEvents)}scheduleOnce(e,t){const r=new Kl(this,{callback:e,once:!0,time:new Bf(this.context,t).toTicks()});return this._addEvent(r,this._timeline)}clear(e){if(this._scheduledEvents.hasOwnProperty(e)){const t=this._scheduledEvents[e.toString()];t.timeline.remove(t.event),t.event.dispose(),delete this._scheduledEvents[e.toString()]}return this}_addEvent(e,t){return this._scheduledEvents[e.id.toString()]={event:e,timeline:t},t.add(e),e.id}cancel(e=0){const t=this.toTicks(e);return this._timeline.forEachFrom(t,r=>this.clear(r.id)),this._repeatedEvents.forEachFrom(t,r=>this.clear(r.id)),this}_bindClockEvents(){this._clock.on("start",(e,t)=>{t=new zr(this.context,t).toSeconds(),this.emit("start",e,t)}),this._clock.on("stop",e=>{this.emit("stop",e)}),this._clock.on("pause",e=>{this.emit("pause",e)})}get state(){return this._clock.getStateAtTime(this.now())}start(e,t){this.context.resume();let r;return qt(t)&&(r=this.toTicks(t)),this._clock.start(e,r),this}stop(e){return this._clock.stop(e),this}pause(e){return this._clock.pause(e),this}toggle(e){return e=this.toSeconds(e),this._clock.getStateAtTime(e)!=="started"?this.start(e):this.stop(e),this}get timeSignature(){return this._timeSignature}set timeSignature(e){_s(e)&&(e=e[0]/e[1]*4),this._timeSignature=e}get loopStart(){return new co(this.context,this._loopStart,"i").toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e)}get loopEnd(){return new co(this.context,this._loopEnd,"i").toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e)}get loop(){return this._loop.get(this.now())}set loop(e){this._loop.set(e,this.now())}setLoopPoints(e,t){return this.loopStart=e,this.loopEnd=t,this}get swing(){return this._swingAmount}set swing(e){this._swingAmount=e}get swingSubdivision(){return new zr(this.context,this._swingTicks).toNotation()}set swingSubdivision(e){this._swingTicks=this.toTicks(e)}get position(){const e=this.now(),t=this._clock.getTicksAtTime(e);return new zr(this.context,t).toBarsBeatsSixteenths()}set position(e){const t=this.toTicks(e);this.ticks=t}get seconds(){return this._clock.seconds}set seconds(e){const t=this.now(),r=this._clock.frequency.timeToTicks(e,t);this.ticks=r}get progress(){if(this.loop){const e=this.now();return(this._clock.getTicksAtTime(e)-this._loopStart)/(this._loopEnd-this._loopStart)}else return 0}get ticks(){return this._clock.ticks}set ticks(e){if(this._clock.ticks!==e){const t=this.now();if(this.state==="started"){const r=this._clock.getTicksAtTime(t),i=this._clock.frequency.getDurationOfTicks(Math.ceil(r)-r,t),s=t+i;this.emit("stop",s),this._clock.setTicksAtTime(e,s),this.emit("start",s,this._clock.getSecondsAtTime(s))}else this.emit("ticks",t),this._clock.setTicksAtTime(e,t)}}getTicksAtTime(e){return this._clock.getTicksAtTime(e)}getSecondsAtTime(e){return this._clock.getSecondsAtTime(e)}get PPQ(){return this._clock.frequency.multiplier}set PPQ(e){this._clock.frequency.multiplier=e}nextSubdivision(e){if(e=this.toTicks(e),this.state!=="started")return 0;{const t=this.now(),r=this.getTicksAtTime(t),i=e-r%e;return this._clock.nextTickTime(i,t)}}syncSignal(e,t){const r=this.now();let i=this.bpm,s=1/(60/i.getValueAtTime(r)/this.PPQ),o=[];if(e.units==="time"){const c=.015625/s,l=new Xt(c),u=new MA(-1),h=new Xt(c);i.chain(l,u,h),i=h,s=1/s,o=[l,u,h]}t||(e.getValueAtTime(r)!==0?t=e.getValueAtTime(r)/s:t=0);const a=new Xt(t);return i.connect(a),a.connect(e._param),o.push(a),this._syncedSignals.push({initial:e.value,nodes:o,signal:e}),e.value=0,this}unsyncSignal(e){for(let t=this._syncedSignals.length-1;t>=0;t--){const r=this._syncedSignals[t];r.signal===e&&(r.nodes.forEach(i=>i.dispose()),r.signal.value=r.initial,this._syncedSignals.splice(t,1))}return this}dispose(){return super.dispose(),this._clock.dispose(),Fm(this,"bpm"),this._timeline.dispose(),this._repeatedEvents.dispose(),this}}Dm.mixin(Gy);Uy(n=>{n.transport=new Gy({context:n})});Fy(n=>{n.transport.dispose()});class Ci extends dt{constructor(e){super(e),this.input=void 0,this._state=new Bm("stopped"),this._synced=!1,this._scheduled=[],this._syncedStart=Tn,this._syncedStop=Tn,this._state.memory=100,this._state.increasing=!0,this._volume=this.output=new Xl({context:this.context,mute:e.mute,volume:e.volume}),this.volume=this._volume.volume,Jt(this,"volume"),this.onstop=e.onstop}static getDefaults(){return Object.assign(dt.getDefaults(),{mute:!1,onstop:Tn,volume:0})}get state(){return this._synced?this.context.transport.state==="started"?this._state.getValueAtTime(this.context.transport.seconds):"stopped":this._state.getValueAtTime(this.now())}get mute(){return this._volume.mute}set mute(e){this._volume.mute=e}_clampToCurrentTime(e){return this._synced?e:Math.max(e,this.context.currentTime)}start(e,t,r){let i=Hs(e)&&this._synced?this.context.transport.seconds:this.toSeconds(e);if(i=this._clampToCurrentTime(i),!this._synced&&this._state.getValueAtTime(i)==="started")wt(cd(i,this._state.get(i).time),"Start time must be strictly greater than previous start time"),this._state.cancel(i),this._state.setStateAtTime("started",i),this.log("restart",i),this.restart(i,t,r);else if(this.log("start",i),this._state.setStateAtTime("started",i),this._synced){const s=this._state.get(i);s&&(s.offset=this.toSeconds(Oa(t,0)),s.duration=r?this.toSeconds(r):void 0);const o=this.context.transport.schedule(a=>{this._start(a,t,r)},i);this._scheduled.push(o),this.context.transport.state==="started"&&this.context.transport.getSecondsAtTime(this.immediate())>i&&this._syncedStart(this.now(),this.context.transport.seconds)}else m3(this.context),this._start(i,t,r);return this}stop(e){let t=Hs(e)&&this._synced?this.context.transport.seconds:this.toSeconds(e);if(t=this._clampToCurrentTime(t),this._state.getValueAtTime(t)==="started"||qt(this._state.getNextState("started",t))){if(this.log("stop",t),!this._synced)this._stop(t);else{const r=this.context.transport.schedule(this._stop.bind(this),t);this._scheduled.push(r)}this._state.cancel(t),this._state.setStateAtTime("stopped",t)}return this}restart(e,t,r){return e=this.toSeconds(e),this._state.getValueAtTime(e)==="started"&&(this._state.cancel(e),this._restart(e,t,r)),this}sync(){return this._synced||(this._synced=!0,this._syncedStart=(e,t)=>{if(cd(t,0)){const r=this._state.get(t);if(r&&r.state==="started"&&r.time!==t){const i=t-this.toSeconds(r.time);let s;r.duration&&(s=this.toSeconds(r.duration)-i),this._start(e,this.toSeconds(r.offset)+i,s)}}},this._syncedStop=e=>{const t=this.context.transport.getSecondsAtTime(Math.max(e-this.sampleTime,0));this._state.getValueAtTime(t)==="started"&&this._stop(e)},this.context.transport.on("start",this._syncedStart),this.context.transport.on("loopStart",this._syncedStart),this.context.transport.on("stop",this._syncedStop),this.context.transport.on("pause",this._syncedStop),this.context.transport.on("loopEnd",this._syncedStop)),this}unsync(){return this._synced&&(this.context.transport.off("stop",this._syncedStop),this.context.transport.off("pause",this._syncedStop),this.context.transport.off("loopEnd",this._syncedStop),this.context.transport.off("start",this._syncedStart),this.context.transport.off("loopStart",this._syncedStart)),this._synced=!1,this._scheduled.forEach(e=>this.context.transport.clear(e)),this._scheduled=[],this._state.cancel(0),this._stop(0),this}dispose(){return super.dispose(),this.onstop=Tn,this.unsync(),this._volume.dispose(),this._state.dispose(),this}}class zm extends ld{constructor(){const e=ct(zm.getDefaults(),arguments,["url","onload"]);super(e),this.name="ToneBufferSource",this._source=this.context.createBufferSource(),this._internalChannels=[this._source],this._sourceStarted=!1,this._sourceStopped=!1,Wo(this._source,this._gainNode),this._source.onended=()=>this._stopSource(),this.playbackRate=new Zt({context:this.context,param:this._source.playbackRate,units:"positive",value:e.playbackRate}),this.loop=e.loop,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this._buffer=new Rn(e.url,e.onload,e.onerror),this._internalChannels.push(this._source)}static getDefaults(){return Object.assign(ld.getDefaults(),{url:new Rn,loop:!1,loopEnd:0,loopStart:0,onload:Tn,onerror:Tn,playbackRate:1})}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e}get curve(){return this._curve}set curve(e){this._curve=e}start(e,t,r,i=1){wt(this.buffer.loaded,"buffer is either not set or not loaded");const s=this.toSeconds(e);this._startGain(s,i),this.loop?t=Oa(t,this.loopStart):t=Oa(t,0);let o=Math.max(this.toSeconds(t),0);if(this.loop){const a=this.toSeconds(this.loopEnd)||this.buffer.duration,c=this.toSeconds(this.loopStart),l=a-c;Db(o,a)&&(o=(o-c)%l+c),Ro(o,this.buffer.duration)&&(o=0)}if(this._source.buffer=this.buffer.get(),this._source.loopEnd=this.toSeconds(this.loopEnd)||this.buffer.duration,xv(o,this.buffer.duration)&&(this._sourceStarted=!0,this._source.start(s,o)),qt(r)){let a=this.toSeconds(r);a=Math.max(a,0),this.stop(s+a)}return this}_stopSource(e){!this._sourceStopped&&this._sourceStarted&&(this._sourceStopped=!0,this._source.stop(this.toSeconds(e)),this._onended())}get loopStart(){return this._source.loopStart}set loopStart(e){this._source.loopStart=this.toSeconds(e)}get loopEnd(){return this._source.loopEnd}set loopEnd(e){this._source.loopEnd=this.toSeconds(e)}get buffer(){return this._buffer}set buffer(e){this._buffer.set(e)}get loop(){return this._source.loop}set loop(e){this._source.loop=e,this._sourceStarted&&this.cancelStop()}dispose(){return super.dispose(),this._source.onended=null,this._source.disconnect(),this._buffer.dispose(),this.playbackRate.dispose(),this}}class hd extends Ci{constructor(){const e=ct(hd.getDefaults(),arguments,["type"]);super(e),this.name="Noise",this._source=null,this._playbackRate=e.playbackRate,this.type=e.type,this._fadeIn=e.fadeIn,this._fadeOut=e.fadeOut}static getDefaults(){return Object.assign(Ci.getDefaults(),{fadeIn:0,fadeOut:0,playbackRate:1,type:"white"})}get type(){return this._type}set type(e){if(wt(e in CN,"Noise: invalid type: "+e),this._type!==e&&(this._type=e,this.state==="started")){const t=this.now();this._stop(t),this._start(t)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._source&&(this._source.playbackRate.value=e)}_start(e){const t=CN[this._type];this._source=new zm({url:t,context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,loop:!0,onended:()=>this.onstop(this),playbackRate:this._playbackRate}).connect(this.output),this._source.start(this.toSeconds(e),Math.random()*(t.duration-.001))}_stop(e){this._source&&(this._source.stop(this.toSeconds(e)),this._source=null)}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e,this._source&&(this._source.fadeIn=this._fadeIn)}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e,this._source&&(this._source.fadeOut=this._fadeOut)}_restart(e){this._stop(e),this._start(e)}dispose(){return super.dispose(),this._source&&this._source.disconnect(),this}}const cf=44100*5,R1=2,yc={brown:null,pink:null,white:null},CN={get brown(){if(!yc.brown){const n=[];for(let e=0;ethis.onstop(this)});this._oscillator=r,this._wave?this._oscillator.setPeriodicWave(this._wave):this._oscillator.type=this._type,this._oscillator.connect(this.output),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.start(t)}_stop(e){const t=this.toSeconds(e);this._oscillator&&this._oscillator.stop(t)}_restart(e){const t=this.toSeconds(e);return this.log("restart",t),this._oscillator&&this._oscillator.cancelStop(),this._state.cancel(t),this}syncFrequency(){return this.context.transport.syncSignal(this.frequency),this}unsyncFrequency(){return this.context.transport.unsyncSignal(this.frequency),this}_getCachedPeriodicWave(){if(this._type==="custom")return ar._periodicWaveCache.find(t=>t.phase===this._phase&&aae(t.partials,this._partials));{const e=ar._periodicWaveCache.find(t=>t.type===this._type&&t.phase===this._phase);return this._partialCount=e?e.partialCount:this._partialCount,e}}get type(){return this._type}set type(e){this._type=e;const t=["sine","square","sawtooth","triangle"].indexOf(e)!==-1;if(this._phase===0&&t)this._wave=void 0,this._partialCount=0,this._oscillator!==null&&(this._oscillator.type=e);else{const r=this._getCachedPeriodicWave();if(qt(r)){const{partials:i,wave:s}=r;this._wave=s,this._partials=i,this._oscillator!==null&&this._oscillator.setPeriodicWave(this._wave)}else{const[i,s]=this._getRealImaginary(e,this._phase),o=this.context.createPeriodicWave(i,s);this._wave=o,this._oscillator!==null&&this._oscillator.setPeriodicWave(this._wave),ar._periodicWaveCache.push({imag:s,partialCount:this._partialCount,partials:this._partials,phase:this._phase,real:i,type:this._type,wave:this._wave}),ar._periodicWaveCache.length>100&&ar._periodicWaveCache.shift()}}}get baseType(){return this._type.replace(this.partialCount.toString(),"")}set baseType(e){this.partialCount&&this._type!=="custom"&&e!=="custom"?this.type=e+this.partialCount:this.type=e}get partialCount(){return this._partialCount}set partialCount(e){Ha(e,0);let t=this._type;const r=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(this._type);if(r&&(t=r[1]),this._type!=="custom")e===0?this.type=t:this.type=t+e.toString();else{const i=new Float32Array(e);this._partials.forEach((s,o)=>i[o]=s),this._partials=Array.from(i),this.type=this._type}}_getRealImaginary(e,t){let i=2048;const s=new Float32Array(i),o=new Float32Array(i);let a=1;if(e==="custom"){if(a=this._partials.length+1,this._partialCount=this._partials.length,i=a,this._partials.length===0)return[s,o]}else{const c=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(e);c?(a=parseInt(c[2],10)+1,this._partialCount=parseInt(c[2],10),e=c[1],a=Math.max(a,2),i=a):this._partialCount=0,this._partials=[]}for(let c=1;c>1&1?-1:1):u=0,this._partials[c-1]=u;break;case"custom":u=this._partials[c-1];break;default:throw new TypeError("Oscillator: invalid type: "+e)}u!==0?(s[c]=-u*Math.sin(t*c),o[c]=u*Math.cos(t*c)):(s[c]=0,o[c]=0)}return[s,o]}_inverseFFT(e,t,r){let i=0;const s=e.length;for(let o=0;o(e+1)/2}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class ch extends Sn{constructor(){const e=ct(ch.getDefaults(),arguments,["value"]);super(e),this.name="Multiply",this.override=!1,this._mult=this.input=this.output=new Xt({context:this.context,minValue:e.minValue,maxValue:e.maxValue}),this.factor=this._param=this._mult.gain,this.factor.setValueAtTime(e.value,0)}static getDefaults(){return Object.assign(Sn.getDefaults(),{value:0})}dispose(){return super.dispose(),this._mult.dispose(),this}}class Wy extends Ci{constructor(){const e=ct(Wy.getDefaults(),arguments,["frequency","type","modulationType"]);super(e),this.name="AMOscillator",this._modulationScale=new A3({context:this.context}),this._modulationNode=new Xt({context:this.context}),this._carrier=new ar({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase,type:e.type}),this.frequency=this._carrier.frequency,this.detune=this._carrier.detune,this._modulator=new ar({context:this.context,phase:e.phase,type:e.modulationType}),this.harmonicity=new ch({context:this.context,units:"positive",value:e.harmonicity}),this.frequency.chain(this.harmonicity,this._modulator.frequency),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output),Jt(this,["frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(ar.getDefaults(),{harmonicity:1,modulationType:"square"})}_start(e){this._modulator.start(e),this._carrier.start(e)}_stop(e){this._modulator.stop(e),this._carrier.stop(e)}_restart(e){this._modulator.restart(e),this._carrier.restart(e)}get type(){return this._carrier.type}set type(e){this._carrier.type=e}get baseType(){return this._carrier.baseType}set baseType(e){this._carrier.baseType=e}get partialCount(){return this._carrier.partialCount}set partialCount(e){this._carrier.partialCount=e}get modulationType(){return this._modulator.type}set modulationType(e){this._modulator.type=e}get phase(){return this._carrier.phase}set phase(e){this._carrier.phase=e,this._modulator.phase=e}get partials(){return this._carrier.partials}set partials(e){this._carrier.partials=e}asArray(){return Sr(this,arguments,void 0,function*(e=1024){return wh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this._modulationScale.dispose(),this}}class jy extends Ci{constructor(){const e=ct(jy.getDefaults(),arguments,["frequency","type","modulationType"]);super(e),this.name="FMOscillator",this._modulationNode=new Xt({context:this.context,gain:0}),this._carrier=new ar({context:this.context,detune:e.detune,frequency:0,onstop:()=>this.onstop(this),phase:e.phase,type:e.type}),this.detune=this._carrier.detune,this.frequency=new Sn({context:this.context,units:"frequency",value:e.frequency}),this._modulator=new ar({context:this.context,phase:e.phase,type:e.modulationType}),this.harmonicity=new ch({context:this.context,units:"positive",value:e.harmonicity}),this.modulationIndex=new ch({context:this.context,units:"positive",value:e.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output),this.detune.connect(this._modulator.detune),Jt(this,["modulationIndex","frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(ar.getDefaults(),{harmonicity:1,modulationIndex:2,modulationType:"square"})}_start(e){this._modulator.start(e),this._carrier.start(e)}_stop(e){this._modulator.stop(e),this._carrier.stop(e)}_restart(e){return this._modulator.restart(e),this._carrier.restart(e),this}get type(){return this._carrier.type}set type(e){this._carrier.type=e}get baseType(){return this._carrier.baseType}set baseType(e){this._carrier.baseType=e}get partialCount(){return this._carrier.partialCount}set partialCount(e){this._carrier.partialCount=e}get modulationType(){return this._modulator.type}set modulationType(e){this._modulator.type=e}get phase(){return this._carrier.phase}set phase(e){this._carrier.phase=e,this._modulator.phase=e}get partials(){return this._carrier.partials}set partials(e){this._carrier.partials=e}asArray(){return Sr(this,arguments,void 0,function*(e=1024){return wh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this.modulationIndex.dispose(),this}}class Vm extends Ci{constructor(){const e=ct(Vm.getDefaults(),arguments,["frequency","width"]);super(e),this.name="PulseOscillator",this._widthGate=new Xt({context:this.context,gain:0}),this._thresh=new Th({context:this.context,mapping:t=>t<=0?-1:1}),this.width=new Sn({context:this.context,units:"audioRange",value:e.width}),this._triangle=new ar({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase,type:"triangle"}),this.frequency=this._triangle.frequency,this.detune=this._triangle.detune,this._triangle.chain(this._thresh,this.output),this.width.chain(this._widthGate,this._thresh),Jt(this,["width","frequency","detune"])}static getDefaults(){return Object.assign(Ci.getDefaults(),{detune:0,frequency:440,phase:0,type:"pulse",width:.2})}_start(e){e=this.toSeconds(e),this._triangle.start(e),this._widthGate.gain.setValueAtTime(1,e)}_stop(e){e=this.toSeconds(e),this._triangle.stop(e),this._widthGate.gain.cancelScheduledValues(e),this._widthGate.gain.setValueAtTime(0,e)}_restart(e){this._triangle.restart(e),this._widthGate.gain.cancelScheduledValues(e),this._widthGate.gain.setValueAtTime(1,e)}get phase(){return this._triangle.phase}set phase(e){this._triangle.phase=e}get type(){return"pulse"}get baseType(){return"pulse"}get partials(){return[]}get partialCount(){return 0}set carrierType(e){this._triangle.type=e}asArray(){return Sr(this,arguments,void 0,function*(e=1024){return wh(this,e)})}dispose(){return super.dispose(),this._triangle.dispose(),this.width.dispose(),this._widthGate.dispose(),this._thresh.dispose(),this}}class $y extends Ci{constructor(){const e=ct($y.getDefaults(),arguments,["frequency","type","spread"]);super(e),this.name="FatOscillator",this._oscillators=[],this.frequency=new Sn({context:this.context,units:"frequency",value:e.frequency}),this.detune=new Sn({context:this.context,units:"cents",value:e.detune}),this._spread=e.spread,this._type=e.type,this._phase=e.phase,this._partials=e.partials,this._partialCount=e.partialCount,this.count=e.count,Jt(this,["frequency","detune"])}static getDefaults(){return Object.assign(ar.getDefaults(),{count:3,spread:20,type:"sawtooth"})}_start(e){e=this.toSeconds(e),this._forEach(t=>t.start(e))}_stop(e){e=this.toSeconds(e),this._forEach(t=>t.stop(e))}_restart(e){this._forEach(t=>t.restart(e))}_forEach(e){for(let t=0;tt.type=e)}get spread(){return this._spread}set spread(e){if(this._spread=e,this._oscillators.length>1){const t=-e/2,r=e/(this._oscillators.length-1);this._forEach((i,s)=>i.detune.value=t+r*s)}}get count(){return this._oscillators.length}set count(e){if(Ha(e,1),this._oscillators.length!==e){this._forEach(t=>t.dispose()),this._oscillators=[];for(let t=0;tthis.onstop(this):Tn});this.type==="custom"&&(r.partials=this._partials),this.frequency.connect(r.frequency),this.detune.connect(r.detune),r.detune.overridden=!1,r.connect(this.output),this._oscillators[t]=r}this.spread=this._spread,this.state==="started"&&this._forEach(t=>t.start())}}get phase(){return this._phase}set phase(e){this._phase=e,this._forEach((t,r)=>t.phase=this._phase+r/this.count*360)}get baseType(){return this._oscillators[0].baseType}set baseType(e){this._forEach(t=>t.baseType=e),this._type=this._oscillators[0].type}get partials(){return this._oscillators[0].partials}set partials(e){this._partials=e,this._partialCount=this._partials.length,e.length&&(this._type="custom",this._forEach(t=>t.partials=e))}get partialCount(){return this._oscillators[0].partialCount}set partialCount(e){this._partialCount=e,this._forEach(t=>t.partialCount=e),this._type=this._oscillators[0].type}asArray(){return Sr(this,arguments,void 0,function*(e=1024){return wh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this._forEach(e=>e.dispose()),this}}class qy extends Ci{constructor(){const e=ct(qy.getDefaults(),arguments,["frequency","modulationFrequency"]);super(e),this.name="PWMOscillator",this.sourceType="pwm",this._scale=new ch({context:this.context,value:2}),this._pulse=new Vm({context:this.context,frequency:e.modulationFrequency}),this._pulse.carrierType="sine",this.modulationFrequency=this._pulse.frequency,this._modulator=new ar({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase}),this.frequency=this._modulator.frequency,this.detune=this._modulator.detune,this._modulator.chain(this._scale,this._pulse.width),this._pulse.connect(this.output),Jt(this,["modulationFrequency","frequency","detune"])}static getDefaults(){return Object.assign(Ci.getDefaults(),{detune:0,frequency:440,modulationFrequency:.4,phase:0,type:"pwm"})}_start(e){e=this.toSeconds(e),this._modulator.start(e),this._pulse.start(e)}_stop(e){e=this.toSeconds(e),this._modulator.stop(e),this._pulse.stop(e)}_restart(e){this._modulator.restart(e),this._pulse.restart(e)}get type(){return"pwm"}get baseType(){return"pwm"}get partials(){return[]}get partialCount(){return 0}get phase(){return this._modulator.phase}set phase(e){this._modulator.phase=e}asArray(){return Sr(this,arguments,void 0,function*(e=1024){return wh(this,e)})}dispose(){return super.dispose(),this._pulse.dispose(),this._scale.dispose(),this._modulator.dispose(),this}}const RN={am:Wy,fat:$y,fm:jy,oscillator:ar,pulse:Vm,pwm:qy};class Ev extends Ci{constructor(){const e=ct(Ev.getDefaults(),arguments,["frequency","type"]);super(e),this.name="OmniOscillator",this.frequency=new Sn({context:this.context,units:"frequency",value:e.frequency}),this.detune=new Sn({context:this.context,units:"cents",value:e.detune}),Jt(this,["frequency","detune"]),this.set(e)}static getDefaults(){return Object.assign(ar.getDefaults(),jy.getDefaults(),Wy.getDefaults(),$y.getDefaults(),Vm.getDefaults(),qy.getDefaults())}_start(e){this._oscillator.start(e)}_stop(e){this._oscillator.stop(e)}_restart(e){return this._oscillator.restart(e),this}get type(){let e="";return["am","fm","fat"].some(t=>this._sourceType===t)&&(e=this._sourceType),e+this._oscillator.type}set type(e){e.substr(0,2)==="fm"?(this._createNewOscillator("fm"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(2)):e.substr(0,2)==="am"?(this._createNewOscillator("am"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(2)):e.substr(0,3)==="fat"?(this._createNewOscillator("fat"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(3)):e==="pwm"?(this._createNewOscillator("pwm"),this._oscillator=this._oscillator):e==="pulse"?this._createNewOscillator("pulse"):(this._createNewOscillator("oscillator"),this._oscillator=this._oscillator,this._oscillator.type=e)}get partials(){return this._oscillator.partials}set partials(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&(this._oscillator.partials=e)}get partialCount(){return this._oscillator.partialCount}set partialCount(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&(this._oscillator.partialCount=e)}set(e){return Reflect.has(e,"type")&&e.type&&(this.type=e.type),super.set(e),this}_createNewOscillator(e){if(e!==this._sourceType){this._sourceType=e;const t=RN[e],r=this.now();if(this._oscillator){const i=this._oscillator;i.stop(r),this.context.setTimeout(()=>i.dispose(),this.blockTime)}this._oscillator=new t({context:this.context}),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.connect(this.output),this._oscillator.onstop=()=>this.onstop(this),this.state==="started"&&this._oscillator.start(r)}}get phase(){return this._oscillator.phase}set phase(e){this._oscillator.phase=e}get sourceType(){return this._sourceType}set sourceType(e){let t="sine";this._oscillator.type!=="pwm"&&this._oscillator.type!=="pulse"&&(t=this._oscillator.type),e==="fm"?this.type="fm"+t:e==="am"?this.type="am"+t:e==="fat"?this.type="fat"+t:e==="oscillator"?this.type=t:e==="pulse"?this.type="pulse":e==="pwm"&&(this.type="pwm")}_getOscType(e,t){return e instanceof RN[t]}get baseType(){return this._oscillator.baseType}set baseType(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&e!=="pulse"&&e!=="pwm"&&(this._oscillator.baseType=e)}get width(){if(this._getOscType(this._oscillator,"pulse"))return this._oscillator.width}get count(){if(this._getOscType(this._oscillator,"fat"))return this._oscillator.count}set count(e){this._getOscType(this._oscillator,"fat")&&Go(e)&&(this._oscillator.count=e)}get spread(){if(this._getOscType(this._oscillator,"fat"))return this._oscillator.spread}set spread(e){this._getOscType(this._oscillator,"fat")&&Go(e)&&(this._oscillator.spread=e)}get modulationType(){if(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))return this._oscillator.modulationType}set modulationType(e){(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))&&jc(e)&&(this._oscillator.modulationType=e)}get modulationIndex(){if(this._getOscType(this._oscillator,"fm"))return this._oscillator.modulationIndex}get harmonicity(){if(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))return this._oscillator.harmonicity}get modulationFrequency(){if(this._getOscType(this._oscillator,"pwm"))return this._oscillator.modulationFrequency}asArray(){return Sr(this,arguments,void 0,function*(e=1024){return wh(this,e)})}dispose(){return super.dispose(),this.detune.dispose(),this.frequency.dispose(),this._oscillator.dispose(),this}}class kA extends Sn{constructor(){super(ct(kA.getDefaults(),arguments,["value"])),this.override=!1,this.name="Add",this._sum=new Xt({context:this.context}),this.input=this._sum,this.output=this._sum,this.addend=this._param,ah(this._constantSource,this._sum)}static getDefaults(){return Object.assign(Sn.getDefaults(),{value:0})}dispose(){return super.dispose(),this._sum.dispose(),this}}class NA extends Ga{constructor(){const e=ct(NA.getDefaults(),arguments,["min","max"]);super(e),this.name="Scale",this._mult=this.input=new ch({context:this.context,value:e.max-e.min}),this._add=this.output=new kA({context:this.context,value:e.min}),this._min=e.min,this._max=e.max,this.input.connect(this.output)}static getDefaults(){return Object.assign(Ga.getDefaults(),{max:1,min:0})}get min(){return this._min}set min(e){this._min=e,this._setRange()}get max(){return this._max}set max(e){this._max=e,this._setRange()}_setRange(){this._add.value=this._min,this._mult.value=this._max-this._min}dispose(){return super.dispose(),this._add.dispose(),this._mult.dispose(),this}}class IA extends Ga{constructor(){super(ct(IA.getDefaults(),arguments)),this.name="Zero",this._gain=new Xt({context:this.context}),this.output=this._gain,this.input=void 0,Wo(this.context.getConstant(0),this._gain)}dispose(){return super.dispose(),w3(this.context.getConstant(0),this._gain),this}}class lh extends dt{constructor(){const e=ct(lh.getDefaults(),arguments,["frequency","min","max"]);super(e),this.name="LFO",this._stoppedValue=0,this._units="number",this.convert=!0,this._fromType=Zt.prototype._fromType,this._toType=Zt.prototype._toType,this._is=Zt.prototype._is,this._clampValue=Zt.prototype._clampValue,this._oscillator=new ar(e),this.frequency=this._oscillator.frequency,this._amplitudeGain=new Xt({context:this.context,gain:e.amplitude,units:"normalRange"}),this.amplitude=this._amplitudeGain.gain,this._stoppedSignal=new Sn({context:this.context,units:"audioRange",value:0}),this._zeros=new IA({context:this.context}),this._a2g=new A3({context:this.context}),this._scaler=this.output=new NA({context:this.context,max:e.max,min:e.min}),this.units=e.units,this.min=e.min,this.max=e.max,this._oscillator.chain(this._amplitudeGain,this._a2g,this._scaler),this._zeros.connect(this._a2g),this._stoppedSignal.connect(this._a2g),Jt(this,["amplitude","frequency"]),this.phase=e.phase}static getDefaults(){return Object.assign(ar.getDefaults(),{amplitude:1,frequency:"4n",max:1,min:0,type:"sine",units:"number"})}start(e){return e=this.toSeconds(e),this._stoppedSignal.setValueAtTime(0,e),this._oscillator.start(e),this}stop(e){return e=this.toSeconds(e),this._stoppedSignal.setValueAtTime(this._stoppedValue,e),this._oscillator.stop(e),this}sync(){return this._oscillator.sync(),this._oscillator.syncFrequency(),this}unsync(){return this._oscillator.unsync(),this._oscillator.unsyncFrequency(),this}_setStoppedValue(){this._stoppedValue=this._oscillator.getInitialValue(),this._stoppedSignal.value=this._stoppedValue}get min(){return this._toType(this._scaler.min)}set min(e){e=this._fromType(e),this._scaler.min=e}get max(){return this._toType(this._scaler.max)}set max(e){e=this._fromType(e),this._scaler.max=e}get type(){return this._oscillator.type}set type(e){this._oscillator.type=e,this._setStoppedValue()}get partials(){return this._oscillator.partials}set partials(e){this._oscillator.partials=e,this._setStoppedValue()}get phase(){return this._oscillator.phase}set phase(e){this._oscillator.phase=e,this._setStoppedValue()}get units(){return this._units}set units(e){const t=this.min,r=this.max;this._units=e,this.min=t,this.max=r}get state(){return this._oscillator.state}connect(e,t,r){return(e instanceof Zt||e instanceof Sn)&&(this.convert=e.convert,this.units=e.units),Vy(this,e,t,r),this}dispose(){return super.dispose(),this._oscillator.dispose(),this._stoppedSignal.dispose(),this._zeros.dispose(),this._scaler.dispose(),this._a2g.dispose(),this._amplitudeGain.dispose(),this.amplitude.dispose(),this}}function M3(n,e=1/0){const t=new WeakMap;return function(r,i){Reflect.defineProperty(r,i,{configurable:!0,enumerable:!0,get:function(){return t.get(this)},set:function(s){Ha(s,n,e),t.set(this,s)}})}}function il(n,e=1/0){const t=new WeakMap;return function(r,i){Reflect.defineProperty(r,i,{configurable:!0,enumerable:!0,get:function(){return t.get(this)},set:function(s){Ha(this.toSeconds(s),n,e),t.set(this,s)}})}}class Hm extends Ci{constructor(){const e=ct(Hm.getDefaults(),arguments,["url","onload"]);super(e),this.name="Player",this._activeSources=new Set,this._buffer=new Rn({onload:this._onload.bind(this,e.onload),onerror:e.onerror,reverse:e.reverse,url:e.url}),this.autostart=e.autostart,this._loop=e.loop,this._loopStart=e.loopStart,this._loopEnd=e.loopEnd,this._playbackRate=e.playbackRate,this.fadeIn=e.fadeIn,this.fadeOut=e.fadeOut}static getDefaults(){return Object.assign(Ci.getDefaults(),{autostart:!1,fadeIn:0,fadeOut:0,loop:!1,loopEnd:0,loopStart:0,onload:Tn,onerror:Tn,playbackRate:1,reverse:!1})}load(e){return Sr(this,void 0,void 0,function*(){return yield this._buffer.load(e),this._onload(),this})}_onload(e=Tn){e(),this.autostart&&this.start()}_onSourceEnd(e){this.onstop(this),this._activeSources.delete(e),this._activeSources.size===0&&!this._synced&&this._state.getValueAtTime(this.now())==="started"&&(this._state.cancel(this.now()),this._state.setStateAtTime("stopped",this.now()))}start(e,t,r){return super.start(e,t,r),this}_start(e,t,r){this._loop?t=Oa(t,this._loopStart):t=Oa(t,0);const i=this.toSeconds(t),s=r;r=Oa(r,Math.max(this._buffer.duration-i,0));let o=this.toSeconds(r);o=o/this._playbackRate,e=this.toSeconds(e);const a=new zm({url:this._buffer,context:this.context,fadeIn:this.fadeIn,fadeOut:this.fadeOut,loop:this._loop,loopEnd:this._loopEnd,loopStart:this._loopStart,onended:this._onSourceEnd.bind(this),playbackRate:this._playbackRate}).connect(this.output);!this._loop&&!this._synced&&(this._state.cancel(e+o),this._state.setStateAtTime("stopped",e+o,{implicitEnd:!0})),this._activeSources.add(a),this._loop&&Hs(s)?a.start(e,i):a.start(e,i,o-this.toSeconds(this.fadeOut))}_stop(e){const t=this.toSeconds(e);this._activeSources.forEach(r=>r.stop(t))}restart(e,t,r){return super.restart(e,t,r),this}_restart(e,t,r){var i;(i=[...this._activeSources].pop())===null||i===void 0||i.stop(e),this._start(e,t,r)}seek(e,t){const r=this.toSeconds(t);if(this._state.getValueAtTime(r)==="started"){const i=this.toSeconds(e);this._stop(r),this._start(r,i)}return this}setLoopPoints(e,t){return this.loopStart=e,this.loopEnd=t,this}get loopStart(){return this._loopStart}set loopStart(e){this._loopStart=e,this.buffer.loaded&&Ha(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(t=>{t.loopStart=e})}get loopEnd(){return this._loopEnd}set loopEnd(e){this._loopEnd=e,this.buffer.loaded&&Ha(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(t=>{t.loopEnd=e})}get buffer(){return this._buffer}set buffer(e){this._buffer.set(e)}get loop(){return this._loop}set loop(e){if(this._loop!==e&&(this._loop=e,this._activeSources.forEach(t=>{t.loop=e}),e)){const t=this._state.getNextState("stopped",this.now());t&&this._state.cancel(t.time)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e;const t=this.now(),r=this._state.getNextState("stopped",t);r&&r.implicitEnd&&(this._state.cancel(r.time),this._activeSources.forEach(i=>i.cancelStop())),this._activeSources.forEach(i=>{i.playbackRate.setValueAtTime(e,t)})}get reverse(){return this._buffer.reverse}set reverse(e){this._buffer.reverse=e}get loaded(){return this._buffer.loaded}dispose(){return super.dispose(),this._activeSources.forEach(e=>e.dispose()),this._activeSources.clear(),this._buffer.dispose(),this}}Ko([il(0)],Hm.prototype,"fadeIn",void 0);Ko([il(0)],Hm.prototype,"fadeOut",void 0);class Aae extends Ga{constructor(){super(...arguments),this.name="GainToAudio",this._norm=new Th({context:this.context,mapping:e=>Math.abs(e)*2-1}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class sl extends dt{constructor(){const e=ct(sl.getDefaults(),arguments,["attack","decay","sustain","release"]);super(e),this.name="Envelope",this._sig=new Sn({context:this.context,value:0}),this.output=this._sig,this.input=void 0,this.attack=e.attack,this.decay=e.decay,this.sustain=e.sustain,this.release=e.release,this.attackCurve=e.attackCurve,this.releaseCurve=e.releaseCurve,this.decayCurve=e.decayCurve}static getDefaults(){return Object.assign(dt.getDefaults(),{attack:.01,attackCurve:"linear",decay:.1,decayCurve:"exponential",release:1,releaseCurve:"exponential",sustain:.5})}get value(){return this.getValueAtTime(this.now())}_getCurve(e,t){if(jc(e))return e;{let r;for(r in W0)if(W0[r][t]===e)return r;return e}}_setCurve(e,t,r){if(jc(r)&&Reflect.has(W0,r)){const i=W0[r];Dl(i)?e!=="_decayCurve"&&(this[e]=i[t]):this[e]=i}else if(_s(r)&&e!=="_decayCurve")this[e]=r;else throw new Error("Envelope: invalid curve: "+r)}get attackCurve(){return this._getCurve(this._attackCurve,"In")}set attackCurve(e){this._setCurve("_attackCurve","In",e)}get releaseCurve(){return this._getCurve(this._releaseCurve,"Out")}set releaseCurve(e){this._setCurve("_releaseCurve","Out",e)}get decayCurve(){return this._getCurve(this._decayCurve,"Out")}set decayCurve(e){this._setCurve("_decayCurve","Out",e)}triggerAttack(e,t=1){this.log("triggerAttack",e,t),e=this.toSeconds(e);let i=this.toSeconds(this.attack);const s=this.toSeconds(this.decay),o=this.getValueAtTime(e);if(o>0){const a=1/i;i=(1-o)/a}if(i0){const r=this.toSeconds(this.release);r{let e,t;const r=[];for(e=0;e<128;e++)r[e]=Math.sin(e/127*(Math.PI/2));const i=[],s=6.4;for(e=0;e<127;e++){t=e/127;const d=Math.sin(t*(Math.PI*2)*s-Math.PI/2)+1;i[e]=d/10+t*.83}i[127]=1;const o=[],a=5;for(e=0;e<128;e++)o[e]=Math.ceil(e/127*a)/a;const c=[];for(e=0;e<128;e++)t=e/127,c[e]=.5*(1-Math.cos(Math.PI*t));const l=[];for(e=0;e<128;e++){t=e/127;const d=Math.pow(t,3)*4+.2,m=Math.cos(d*Math.PI*2*t);l[e]=Math.abs(m*(1-t))}function u(d){const m=new Array(d.length);for(let g=0;gthis._original_triggerRelease(t),this._volume=this.output=new Xl({context:this.context,volume:e.volume}),this.volume=this._volume.volume,Jt(this,"volume")}static getDefaults(){return Object.assign(dt.getDefaults(),{volume:0})}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",0),this.context.transport.on("stop",this._syncedRelease),this.context.transport.on("pause",this._syncedRelease),this.context.transport.on("loopEnd",this._syncedRelease)),this}_syncState(){let e=!1;return this._synced||(this._synced=!0,e=!0),e}_syncMethod(e,t){const r=this["_original_"+e]=this[e];this[e]=(...i)=>{const s=i[t],o=this.context.transport.schedule(a=>{i[t]=a,r.apply(this,i)},s);this._scheduledEvents.push(o)}}unsync(){return this._scheduledEvents.forEach(e=>this.context.transport.clear(e)),this._scheduledEvents=[],this._synced&&(this._synced=!1,this.triggerAttack=this._original_triggerAttack,this.triggerRelease=this._original_triggerRelease,this.context.transport.off("stop",this._syncedRelease),this.context.transport.off("pause",this._syncedRelease),this.context.transport.off("loopEnd",this._syncedRelease)),this}triggerAttackRelease(e,t,r,i){const s=this.toSeconds(r),o=this.toSeconds(t);return this.triggerAttack(e,s,i),this.triggerRelease(s+o),this}dispose(){return super.dispose(),this._volume.dispose(),this.unsync(),this._scheduledEvents=[],this}}class uh extends Wa{constructor(){const e=ct(uh.getDefaults(),arguments);super(e),this.portamento=e.portamento,this.onsilence=e.onsilence}static getDefaults(){return Object.assign(Wa.getDefaults(),{detune:0,onsilence:Tn,portamento:0})}triggerAttack(e,t,r=1){this.log("triggerAttack",e,t,r);const i=this.toSeconds(t);return this._triggerEnvelopeAttack(i,r),this.setNote(e,i),this}triggerRelease(e){this.log("triggerRelease",e);const t=this.toSeconds(e);return this._triggerEnvelopeRelease(t),this}setNote(e,t){const r=this.toSeconds(t),i=e instanceof ds?e.toFrequency():e;if(this.portamento>0&&this.getLevelAtTime(r)>.05){const s=this.toSeconds(this.portamento);this.frequency.exponentialRampTo(i,s,r)}else this.frequency.setValueAtTime(i,r);return this}}Ko([il(0)],uh.prototype,"portamento",void 0);class Xy extends sl{constructor(){super(ct(Xy.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="AmplitudeEnvelope",this._gainNode=new Xt({context:this.context,gain:0}),this.output=this._gainNode,this.input=this._gainNode,this._sig.connect(this._gainNode.gain),this.output=this._gainNode,this.input=this._gainNode}dispose(){return super.dispose(),this._gainNode.dispose(),this}}class Fi extends uh{constructor(){const e=ct(Fi.getDefaults(),arguments);super(e),this.name="Synth",this.oscillator=new Ev(Object.assign({context:this.context,detune:e.detune,onstop:()=>this.onsilence(this)},e.oscillator)),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.envelope=new Xy(Object.assign({context:this.context},e.envelope)),this.oscillator.chain(this.envelope,this.output),Jt(this,["oscillator","frequency","detune","envelope"])}static getDefaults(){return Object.assign(uh.getDefaults(),{envelope:Object.assign(tm(sl.getDefaults(),Object.keys(dt.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.3}),oscillator:Object.assign(tm(Ev.getDefaults(),[...Object.keys(Ci.getDefaults()),"frequency","detune"]),{type:"triangle"})})}_triggerEnvelopeAttack(e,t){if(this.envelope.triggerAttack(e,t),this.oscillator.start(e),this.envelope.sustain===0){const r=this.toSeconds(this.envelope.attack),i=this.toSeconds(this.envelope.decay);this.oscillator.stop(e+r+i)}}_triggerEnvelopeRelease(e){this.envelope.triggerRelease(e),this.oscillator.stop(e+this.toSeconds(this.envelope.release))}getLevelAtTime(e){return e=this.toSeconds(e),this.envelope.getValueAtTime(e)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this}}class bv extends dt{constructor(){const e=ct(bv.getDefaults(),arguments,["frequency","type"]);super(e),this.name="BiquadFilter",this._filter=this.context.createBiquadFilter(),this.input=this.output=this._filter,this.Q=new Zt({context:this.context,units:"number",value:e.Q,param:this._filter.Q}),this.frequency=new Zt({context:this.context,units:"frequency",value:e.frequency,param:this._filter.frequency}),this.detune=new Zt({context:this.context,units:"cents",value:e.detune,param:this._filter.detune}),this.gain=new Zt({context:this.context,units:"decibels",convert:!1,value:e.gain,param:this._filter.gain}),this.type=e.type}static getDefaults(){return Object.assign(dt.getDefaults(),{Q:1,type:"lowpass",frequency:350,detune:0,gain:0})}get type(){return this._filter.type}set type(e){wt(["lowpass","highpass","bandpass","lowshelf","highshelf","notch","allpass","peaking"].indexOf(e)!==-1,`Invalid filter type: ${e}`),this._filter.type=e}getFrequencyResponse(e=128){const t=new Float32Array(e);for(let o=0;or.type=e)}get rolloff(){return this._rolloff}set rolloff(e){const t=Go(e)?e:parseInt(e,10),r=[-12,-24,-48,-96];let i=r.indexOf(t);wt(i!==-1,`rolloff can only be ${r.join(", ")}`),i+=1,this._rolloff=t,this.input.disconnect(),this._filters.forEach(s=>s.disconnect()),this._filters=new Array(i);for(let s=0;s1);return this._filters.forEach(()=>{t.getFrequencyResponse(e).forEach((s,o)=>r[o]*=s)}),t.dispose(),r}dispose(){return super.dispose(),this._filters.forEach(e=>{e.dispose()}),Fm(this,["detune","frequency","gain","Q"]),this.frequency.dispose(),this.Q.dispose(),this.detune.dispose(),this.gain.dispose(),this}}class Gm extends Fi{constructor(){const e=ct(Gm.getDefaults(),arguments);super(e),this.name="MembraneSynth",this.portamento=0,this.pitchDecay=e.pitchDecay,this.octaves=e.octaves,Jt(this,["oscillator","envelope"])}static getDefaults(){return Ku(uh.getDefaults(),Fi.getDefaults(),{envelope:{attack:.001,attackCurve:"exponential",decay:.4,release:1.4,sustain:.01},octaves:10,oscillator:{type:"sine"},pitchDecay:.05})}setNote(e,t){const r=this.toSeconds(t),i=this.toFrequency(e instanceof ds?e.toFrequency():e),s=i*this.octaves;return this.oscillator.frequency.setValueAtTime(s,r),this.oscillator.frequency.exponentialRampToValueAtTime(i,r+this.toSeconds(this.pitchDecay)),this}dispose(){return super.dispose(),this}}Ko([M3(0)],Gm.prototype,"octaves",void 0);Ko([il(0)],Gm.prototype,"pitchDecay",void 0);class wf extends Wa{constructor(){const e=ct(wf.getDefaults(),arguments);super(e),this.name="NoiseSynth",this.noise=new hd(Object.assign({context:this.context},e.noise)),this.envelope=new Xy(Object.assign({context:this.context},e.envelope)),this.noise.chain(this.envelope,this.output)}static getDefaults(){return Object.assign(Wa.getDefaults(),{envelope:Object.assign(tm(sl.getDefaults(),Object.keys(dt.getDefaults())),{decay:.1,sustain:0}),noise:Object.assign(tm(hd.getDefaults(),Object.keys(Ci.getDefaults())),{type:"white"})})}triggerAttack(e,t=1){return e=this.toSeconds(e),this.envelope.triggerAttack(e,t),this.noise.start(e),this.envelope.sustain===0&&this.noise.stop(e+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay)),this}triggerRelease(e){return e=this.toSeconds(e),this.envelope.triggerRelease(e),this.noise.stop(e+this.toSeconds(this.envelope.release)),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",0),this._syncMethod("triggerRelease",0)),this}triggerAttackRelease(e,t,r=1){return t=this.toSeconds(t),e=this.toSeconds(e),this.triggerAttack(t,r),this.triggerRelease(t+e),this}dispose(){return super.dispose(),this.noise.dispose(),this.envelope.dispose(),this}}const C3=new Set;function OA(n){C3.add(n)}function R3(n,e){const t=`registerProcessor("${n}", ${e})`;C3.add(t)}const Mae=` + /** + * The base AudioWorkletProcessor for use in Tone.js. Works with the {@link ToneAudioWorklet}. + */ + class ToneAudioWorkletProcessor extends AudioWorkletProcessor { + + constructor(options) { + + super(options); + /** + * If the processor was disposed or not. Keep alive until it's disposed. + */ + this.disposed = false; + /** + * The number of samples in the processing block + */ + this.blockSize = 128; + /** + * the sample rate + */ + this.sampleRate = sampleRate; + + this.port.onmessage = (event) => { + // when it receives a dispose + if (event.data === "dispose") { + this.disposed = true; + } + }; + } + } +`;OA(Mae);const Cae=` + /** + * Abstract class for a single input/output processor. + * has a 'generate' function which processes one sample at a time + */ + class SingleIOProcessor extends ToneAudioWorkletProcessor { + + constructor(options) { + super(Object.assign(options, { + numberOfInputs: 1, + numberOfOutputs: 1 + })); + /** + * Holds the name of the parameter and a single value of that + * parameter at the current sample + * @type { [name: string]: number } + */ + this.params = {} + } + + /** + * Generate an output sample from the input sample and parameters + * @abstract + * @param input number + * @param channel number + * @param parameters { [name: string]: number } + * @returns number + */ + generate(){} + + /** + * Update the private params object with the + * values of the parameters at the given index + * @param parameters { [name: string]: Float32Array }, + * @param index number + */ + updateParams(parameters, index) { + for (const paramName in parameters) { + const param = parameters[paramName]; + if (param.length > 1) { + this.params[paramName] = parameters[paramName][index]; + } else { + this.params[paramName] = parameters[paramName][0]; + } + } + } + + /** + * Process a single frame of the audio + * @param inputs Float32Array[][] + * @param outputs Float32Array[][] + */ + process(inputs, outputs, parameters) { + const input = inputs[0]; + const output = outputs[0]; + // get the parameter values + const channelCount = Math.max(input && input.length || 0, output.length); + for (let sample = 0; sample < this.blockSize; sample++) { + this.updateParams(parameters, sample); + for (let channel = 0; channel < channelCount; channel++) { + const inputSample = input && input.length ? input[channel][sample] : 0; + output[channel][sample] = this.generate(inputSample, channel, this.params); + } + } + return !this.disposed; + } + }; +`;OA(Cae);const Rae=` + /** + * A multichannel buffer for use within an AudioWorkletProcessor as a delay line + */ + class DelayLine { + + constructor(size, channels) { + this.buffer = []; + this.writeHead = [] + this.size = size; + + // create the empty channels + for (let i = 0; i < channels; i++) { + this.buffer[i] = new Float32Array(this.size); + this.writeHead[i] = 0; + } + } + + /** + * Push a value onto the end + * @param channel number + * @param value number + */ + push(channel, value) { + this.writeHead[channel] += 1; + if (this.writeHead[channel] > this.size) { + this.writeHead[channel] = 0; + } + this.buffer[channel][this.writeHead[channel]] = value; + } + + /** + * Get the recorded value of the channel given the delay + * @param channel number + * @param delay number delay samples + */ + get(channel, delay) { + let readHead = this.writeHead[channel] - Math.floor(delay); + if (readHead < 0) { + readHead += this.size; + } + return this.buffer[channel][readHead]; + } + } +`;OA(Rae);const kae="feedback-comb-filter",Nae=` + class FeedbackCombFilterWorklet extends SingleIOProcessor { + + constructor(options) { + super(options); + this.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2); + } + + static get parameterDescriptors() { + return [{ + name: "delayTime", + defaultValue: 0.1, + minValue: 0, + maxValue: 1, + automationRate: "k-rate" + }, { + name: "feedback", + defaultValue: 0.5, + minValue: 0, + maxValue: 0.9999, + automationRate: "k-rate" + }]; + } + + generate(input, channel, parameters) { + const delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate); + this.delayLine.push(channel, input + delayedSample * parameters.feedback); + return delayedSample; + } + } +`;R3(kae,Nae);class Tv extends Wa{constructor(){const e=ct(Tv.getDefaults(),arguments,["voice","options"]);super(e),this.name="PolySynth",this._availableVoices=[],this._activeVoices=[],this._voices=[],this._gcTimeout=-1,this._averageActiveVoices=0,this._syncedRelease=i=>this.releaseAll(i),wt(!Go(e.voice),"DEPRECATED: The polyphony count is no longer the first argument.");const t=e.voice.getDefaults();this.options=Object.assign(t,e.options),this.voice=e.voice,this.maxPolyphony=e.maxPolyphony,this._dummyVoice=this._getNextAvailableVoice();const r=this._voices.indexOf(this._dummyVoice);this._voices.splice(r,1),this._gcTimeout=this.context.setInterval(this._collectGarbage.bind(this),1)}static getDefaults(){return Object.assign(Wa.getDefaults(),{maxPolyphony:32,options:{},voice:Fi})}get activeVoices(){return this._activeVoices.length}_makeVoiceAvailable(e){this._availableVoices.push(e);const t=this._activeVoices.findIndex(r=>r.voice===e);this._activeVoices.splice(t,1)}_getNextAvailableVoice(){if(this._availableVoices.length)return this._availableVoices.shift();if(this._voices.lengthMath.ceil(this._averageActiveVoices+1)){const e=this._availableVoices.shift(),t=this._voices.indexOf(e);this._voices.splice(t,1),this.context.isOffline||e.dispose()}}_triggerAttack(e,t,r){e.forEach(i=>{const s=new Sv(this.context,i).toMidi(),o=this._getNextAvailableVoice();o&&(o.triggerAttack(i,t,r),this._activeVoices.push({midi:s,voice:o,released:!1}),this.log("triggerAttack",i,t))})}_triggerRelease(e,t){e.forEach(r=>{const i=new Sv(this.context,r).toMidi(),s=this._activeVoices.find(({midi:o,released:a})=>o===i&&!a);s&&(s.voice.triggerRelease(t),s.released=!0,this.log("triggerRelease",r,t))})}_scheduleEvent(e,t,r,i){wt(!this.disposed,"Synth was already disposed"),r<=this.now()?e==="attack"?this._triggerAttack(t,r,i):this._triggerRelease(t,r):this.context.setTimeout(()=>{this.disposed||this._scheduleEvent(e,t,r,i)},r-this.now())}triggerAttack(e,t,r){Array.isArray(e)||(e=[e]);const i=this.toSeconds(t);return this._scheduleEvent("attack",e,i,r),this}triggerRelease(e,t){Array.isArray(e)||(e=[e]);const r=this.toSeconds(t);return this._scheduleEvent("release",e,r),this}triggerAttackRelease(e,t,r,i){const s=this.toSeconds(r);if(this.triggerAttack(e,s,i),_s(t)){wt(_s(e),"If the duration is an array, the notes must also be an array"),e=e;for(let o=0;o0,"The duration must be greater than 0"),this.triggerRelease(e[o],s+c)}}else{const o=this.toSeconds(t);wt(o>0,"The duration must be greater than 0"),this.triggerRelease(e,s+o)}return this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1),this.context.transport.on("stop",this._syncedRelease),this.context.transport.on("pause",this._syncedRelease),this.context.transport.on("loopEnd",this._syncedRelease)),this}set(e){const t=tm(e,["onsilence","context"]);return this.options=Ku(this.options,t),this._voices.forEach(r=>r.set(t)),this._dummyVoice.set(t),this}get(){return this._dummyVoice.get()}releaseAll(e){const t=this.toSeconds(e);return this._activeVoices.forEach(({voice:r})=>{r.triggerRelease(t)}),this}dispose(){return super.dispose(),this._dummyVoice.dispose(),this._voices.forEach(e=>e.dispose()),this._activeVoices=[],this._availableVoices=[],this.context.clearInterval(this._gcTimeout),this}}class Ky extends Wa{constructor(){const e=ct(Ky.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");super(e),this.name="Sampler",this._activeSources=new Map;const t={};Object.keys(e.urls).forEach(r=>{const i=parseInt(r,10);if(wt(G0(r)||Go(i)&&isFinite(i),`url key is neither a note or midi pitch: ${r}`),G0(r)){const s=new ds(this.context,r).toMidi();t[s]=e.urls[r]}else Go(i)&&isFinite(i)&&(t[i]=e.urls[i])}),this._buffers=new AA({urls:t,onload:e.onload,baseUrl:e.baseUrl,onerror:e.onerror}),this.attack=e.attack,this.release=e.release,this.curve=e.curve,this._buffers.loaded&&Promise.resolve().then(e.onload)}static getDefaults(){return Object.assign(Wa.getDefaults(),{attack:0,baseUrl:"",curve:"exponential",onload:Tn,onerror:Tn,release:.1,urls:{}})}_findClosest(e){let r=0;for(;r<96;){if(this._buffers.has(e+r))return-r;if(this._buffers.has(e-r))return r;r++}throw new Error(`No available buffers for note: ${e}`)}triggerAttack(e,t,r=1){return this.log("triggerAttack",e,t,r),Array.isArray(e)||(e=[e]),e.forEach(i=>{const s=b3(new ds(this.context,i).toFrequency()),o=Math.round(s),a=s-o,c=this._findClosest(o),l=o-c,u=this._buffers.get(l),h=E3(c+a),d=new zm({url:u,context:this.context,curve:this.curve,fadeIn:this.attack,fadeOut:this.release,playbackRate:h}).connect(this.output);d.start(t,0,u.duration/h,r),_s(this._activeSources.get(o))||this._activeSources.set(o,[]),this._activeSources.get(o).push(d),d.onended=()=>{if(this._activeSources&&this._activeSources.has(o)){const m=this._activeSources.get(o),g=m.indexOf(d);g!==-1&&m.splice(g,1)}}}),this}triggerRelease(e,t){return this.log("triggerRelease",e,t),Array.isArray(e)||(e=[e]),e.forEach(r=>{const i=new ds(this.context,r).toMidi();if(this._activeSources.has(i)&&this._activeSources.get(i).length){const s=this._activeSources.get(i);t=this.toSeconds(t),s.forEach(o=>{o.stop(t)}),this._activeSources.set(i,[])}}),this}releaseAll(e){const t=this.toSeconds(e);return this._activeSources.forEach(r=>{for(;r.length;)r.shift().stop(t)}),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1)),this}triggerAttackRelease(e,t,r,i=1){const s=this.toSeconds(r);return this.triggerAttack(e,s,i),_s(t)?(wt(_s(e),"notes must be an array when duration is array"),e.forEach((o,a)=>{const c=t[Math.min(a,t.length-1)];this.triggerRelease(o,s+this.toSeconds(c))})):this.triggerRelease(e,s+this.toSeconds(t)),this}add(e,t,r){if(wt(G0(e)||isFinite(e),`note must be a pitch or midi: ${e}`),G0(e)){const i=new ds(this.context,e).toMidi();this._buffers.add(i,t,r)}else this._buffers.add(e,t,r);return this}get loaded(){return this._buffers.loaded}dispose(){return super.dispose(),this._buffers.dispose(),this._activeSources.forEach(e=>{e.forEach(t=>t.dispose())}),this._activeSources.clear(),this}}Ko([il(0)],Ky.prototype,"attack",void 0);Ko([il(0)],Ky.prototype,"release",void 0);class Af extends Ai{constructor(){const e=ct(Af.getDefaults(),arguments,["callback","value"]);super(e),this.name="ToneEvent",this._state=new Bm("stopped"),this._startOffset=0,this._loop=e.loop,this.callback=e.callback,this.value=e.value,this._loopStart=this.toTicks(e.loopStart),this._loopEnd=this.toTicks(e.loopEnd),this._playbackRate=e.playbackRate,this._probability=e.probability,this._humanize=e.humanize,this.mute=e.mute,this._playbackRate=e.playbackRate,this._state.increasing=!0,this._rescheduleEvents()}static getDefaults(){return Object.assign(Ai.getDefaults(),{callback:Tn,humanize:!1,loop:!1,loopEnd:"1m",loopStart:0,mute:!1,playbackRate:1,probability:1,value:null})}_rescheduleEvents(e=-1){this._state.forEachFrom(e,t=>{let r;if(t.state==="started"){t.id!==-1&&this.context.transport.clear(t.id);const i=t.time+Math.round(this.startOffset/this._playbackRate);if(this._loop===!0||Go(this._loop)&&this._loop>1){r=1/0,Go(this._loop)&&(r=this._loop*this._getLoopDuration());const s=this._state.getAfter(i);s!==null&&(r=Math.min(r,s.time-i)),r!==1/0&&(r=new zr(this.context,r));const o=new zr(this.context,this._getLoopDuration());t.id=this.context.transport.scheduleRepeat(this._tick.bind(this),o,new zr(this.context,i),r)}else t.id=this.context.transport.schedule(this._tick.bind(this),new zr(this.context,i))}})}get state(){return this._state.getValueAtTime(this.context.transport.ticks)}get startOffset(){return this._startOffset}set startOffset(e){this._startOffset=e}get probability(){return this._probability}set probability(e){this._probability=e}get humanize(){return this._humanize}set humanize(e){this._humanize=e}start(e){const t=this.toTicks(e);return this._state.getValueAtTime(t)==="stopped"&&(this._state.add({id:-1,state:"started",time:t}),this._rescheduleEvents(t)),this}stop(e){this.cancel(e);const t=this.toTicks(e);if(this._state.getValueAtTime(t)==="started"){this._state.setStateAtTime("stopped",t,{id:-1});const r=this._state.getBefore(t);let i=t;r!==null&&(i=r.time),this._rescheduleEvents(i)}return this}cancel(e){e=Oa(e,-1/0);const t=this.toTicks(e);return this._state.forEachFrom(t,r=>{this.context.transport.clear(r.id)}),this._state.cancel(t),this}_tick(e){const t=this.context.transport.getTicksAtTime(e);if(!this.mute&&this._state.getValueAtTime(t)==="started"){if(this.probability<1&&Math.random()>this.probability)return;if(this.humanize){let r=.02;p3(this.humanize)||(r=this.toSeconds(this.humanize)),e+=(Math.random()*2-1)*r}this.callback(e,this.value)}}_getLoopDuration(){return(this._loopEnd-this._loopStart)/this._playbackRate}get loop(){return this._loop}set loop(e){this._loop=e,this._rescheduleEvents()}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._rescheduleEvents()}get loopEnd(){return new zr(this.context,this._loopEnd).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e),this._loop&&this._rescheduleEvents()}get loopStart(){return new zr(this.context,this._loopStart).toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e),this._loop&&this._rescheduleEvents()}get progress(){if(this._loop){const e=this.context.transport.ticks,t=this._state.get(e);if(t!==null&&t.state==="started"){const r=this._getLoopDuration();return(e-t.time)%r/r}else return 0}else return 0}dispose(){return super.dispose(),this.cancel(),this._state.dispose(),this}}class wv extends Af{constructor(){const e=ct(wv.getDefaults(),arguments,["callback","events"]);super(e),this.name="Part",this._state=new Bm("stopped"),this._events=new Set,this._state.increasing=!0,e.events.forEach(t=>{_s(t)?this.add(t[0],t[1]):this.add(t)})}static getDefaults(){return Object.assign(Af.getDefaults(),{events:[]})}start(e,t){const r=this.toTicks(e);if(this._state.getValueAtTime(r)!=="started"){t=Oa(t,this._loop?this._loopStart:0),this._loop?t=Oa(t,this._loopStart):t=Oa(t,0);const i=this.toTicks(t);this._state.add({id:-1,offset:i,state:"started",time:r}),this._forEach(s=>{this._startNote(s,r,i)})}return this}_startNote(e,t,r){t-=r,this._loop?e.startOffset>=this._loopStart&&e.startOffset=r&&(e.loop=!1,e.start(new zr(this.context,t))):e.startOffset>=r&&e.start(new zr(this.context,t))}get startOffset(){return this._startOffset}set startOffset(e){this._startOffset=e,this._forEach(t=>{t.startOffset+=this._startOffset})}stop(e){const t=this.toTicks(e);return this._state.cancel(t),this._state.setStateAtTime("stopped",t),this._forEach(r=>{r.stop(e)}),this}at(e,t){const r=new Bf(this.context,e).toTicks(),i=new zr(this.context,1).toSeconds(),s=this._events.values();let o=s.next();for(;!o.done;){const a=o.value;if(Math.abs(r-a.startOffset){t.state==="started"?this._startNote(e,t.time,t.offset):e.stop(new zr(this.context,t.time))})}remove(e,t){return Dl(e)&&e.hasOwnProperty("time")&&(t=e,e=t.time),e=this.toTicks(e),this._events.forEach(r=>{r.startOffset===e&&(Hs(t)||qt(t)&&r.value===t)&&(this._events.delete(r),r.dispose())}),this}clear(){return this._forEach(e=>e.dispose()),this._events.clear(),this}cancel(e){return this._forEach(t=>t.cancel(e)),this._state.cancel(this.toTicks(e)),this}_forEach(e){return this._events&&this._events.forEach(t=>{t instanceof wv?t._forEach(e):e(t)}),this}_setAll(e,t){this._forEach(r=>{r[e]=t})}_tick(e,t){this.mute||this.callback(e,t)}_testLoopBoundries(e){this._loop&&(e.startOffset=this._loopEnd)?e.cancel(0):e.state==="stopped"&&this._restartEvent(e)}get probability(){return this._probability}set probability(e){this._probability=e,this._setAll("probability",e)}get humanize(){return this._humanize}set humanize(e){this._humanize=e,this._setAll("humanize",e)}get loop(){return this._loop}set loop(e){this._loop=e,this._forEach(t=>{t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.loop=e,this._testLoopBoundries(t)})}get loopEnd(){return new zr(this.context,this._loopEnd).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e),this._loop&&this._forEach(t=>{t.loopEnd=e,this._testLoopBoundries(t)})}get loopStart(){return new zr(this.context,this._loopStart).toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e),this._loop&&this._forEach(t=>{t.loopStart=this.loopStart,this._testLoopBoundries(t)})}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._setAll("playbackRate",e)}get length(){return this._events.size}dispose(){return super.dispose(),this.clear(),this}}class Yy extends dt{constructor(){const e=ct(Yy.getDefaults(),arguments,["fade"]);super(e),this.name="CrossFade",this._panner=this.context.createStereoPanner(),this._split=this.context.createChannelSplitter(2),this._g2a=new Aae({context:this.context}),this.a=new Xt({context:this.context,gain:0}),this.b=new Xt({context:this.context,gain:0}),this.output=new Xt({context:this.context}),this._internalChannels=[this.a,this.b],this.fade=new Sn({context:this.context,units:"normalRange",value:e.fade}),Jt(this,"fade"),this.context.getConstant(1).connect(this._panner),this._panner.connect(this._split),this._panner.channelCount=1,this._panner.channelCountMode="explicit",Wo(this._split,this.a.gain,0),Wo(this._split,this.b.gain,1),this.fade.chain(this._g2a,this._panner.pan),this.a.connect(this.output),this.b.connect(this.output)}static getDefaults(){return Object.assign(dt.getDefaults(),{fade:.5})}dispose(){return super.dispose(),this.a.dispose(),this.b.dispose(),this.output.dispose(),this.fade.dispose(),this._g2a.dispose(),this._panner.disconnect(),this._split.disconnect(),this}}let Yl=class extends dt{constructor(e){super(e),this.name="Effect",this._dryWet=new Yy({context:this.context}),this.wet=this._dryWet.fade,this.effectSend=new Xt({context:this.context}),this.effectReturn=new Xt({context:this.context}),this.input=new Xt({context:this.context}),this.output=this._dryWet,this.input.fan(this._dryWet.a,this.effectSend),this.effectReturn.connect(this._dryWet.b),this.wet.setValueAtTime(e.wet,0),this._internalChannels=[this.effectReturn,this.effectSend],Jt(this,"wet")}static getDefaults(){return Object.assign(dt.getDefaults(),{wet:1})}connectEffect(e){return this._internalChannels.push(e),this.effectSend.chain(e,this.effectReturn),this}dispose(){return super.dispose(),this._dryWet.dispose(),this.effectSend.dispose(),this.effectReturn.dispose(),this.wet.dispose(),this}};class LA extends dt{constructor(){const e=ct(LA.getDefaults(),arguments,["pan"]);super(e),this.name="Panner",this._panner=this.context.createStereoPanner(),this.input=this._panner,this.output=this._panner,this.pan=new Zt({context:this.context,param:this._panner.pan,value:e.pan,minValue:-1,maxValue:1}),this._panner.channelCount=e.channelCount,this._panner.channelCountMode="explicit",Jt(this,"pan")}static getDefaults(){return Object.assign(dt.getDefaults(),{pan:0,channelCount:1})}dispose(){return super.dispose(),this._panner.disconnect(),this.pan.dispose(),this}}const Iae="bit-crusher",Oae=` + class BitCrusherWorklet extends SingleIOProcessor { + + static get parameterDescriptors() { + return [{ + name: "bits", + defaultValue: 12, + minValue: 1, + maxValue: 16, + automationRate: 'k-rate' + }]; + } + + generate(input, _channel, parameters) { + const step = Math.pow(0.5, parameters.bits - 1); + const val = step * Math.floor(input / step + 0.5); + return val; + } + } +`;R3(Iae,Oae);class Zy extends dt{constructor(){const e=ct(Zy.getDefaults(),arguments,["channels"]);super(e),this.name="Split",this._splitter=this.input=this.output=this.context.createChannelSplitter(e.channels),this._internalChannels=[this._splitter]}static getDefaults(){return Object.assign(dt.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._splitter.disconnect(),this}}class Wm extends dt{constructor(){const e=ct(Wm.getDefaults(),arguments,["channels"]);super(e),this.name="Merge",this._merger=this.output=this.input=this.context.createChannelMerger(e.channels)}static getDefaults(){return Object.assign(dt.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._merger.disconnect(),this}}class Av extends dt{constructor(e){super(e),this.name="StereoEffect",this.input=new Xt({context:this.context}),this.input.channelCount=2,this.input.channelCountMode="explicit",this._dryWet=this.output=new Yy({context:this.context,fade:e.wet}),this.wet=this._dryWet.fade,this._split=new Zy({context:this.context,channels:2}),this._merge=new Wm({context:this.context,channels:2}),this.input.connect(this._split),this.input.connect(this._dryWet.a),this._merge.connect(this._dryWet.b),Jt(this,["wet"])}connectEffectLeft(...e){this._split.connect(e[0],0,0),ah(...e),Wo(e[e.length-1],this._merge,0,0)}connectEffectRight(...e){this._split.connect(e[0],1,0),ah(...e),Wo(e[e.length-1],this._merge,0,1)}static getDefaults(){return Object.assign(dt.getDefaults(),{wet:1})}dispose(){return super.dispose(),this._dryWet.dispose(),this._split.dispose(),this._merge.dispose(),this}}class kN extends Av{constructor(e){super(e),this.feedback=new Sn({context:this.context,value:e.feedback,units:"normalRange"}),this._feedbackL=new Xt({context:this.context}),this._feedbackR=new Xt({context:this.context}),this._feedbackSplit=new Zy({context:this.context,channels:2}),this._feedbackMerge=new Wm({context:this.context,channels:2}),this._merge.connect(this._feedbackSplit),this._feedbackMerge.connect(this._split),this._feedbackSplit.connect(this._feedbackL,0,0),this._feedbackL.connect(this._feedbackMerge,0,0),this._feedbackSplit.connect(this._feedbackR,1,0),this._feedbackR.connect(this._feedbackMerge,0,1),this.feedback.fan(this._feedbackL.gain,this._feedbackR.gain),Jt(this,["feedback"])}static getDefaults(){return Object.assign(Av.getDefaults(),{feedback:.5})}dispose(){return super.dispose(),this.feedback.dispose(),this._feedbackL.dispose(),this._feedbackR.dispose(),this._feedbackSplit.dispose(),this._feedbackMerge.dispose(),this}}class PA extends kN{constructor(){const e=ct(PA.getDefaults(),arguments,["frequency","delayTime","depth"]);super(e),this.name="Chorus",this._depth=e.depth,this._delayTime=e.delayTime/1e3,this._lfoL=new lh({context:this.context,frequency:e.frequency,min:0,max:1}),this._lfoR=new lh({context:this.context,frequency:e.frequency,min:0,max:1,phase:180}),this._delayNodeL=new ud({context:this.context}),this._delayNodeR=new ud({context:this.context}),this.frequency=this._lfoL.frequency,Jt(this,["frequency"]),this._lfoL.frequency.connect(this._lfoR.frequency),this.connectEffectLeft(this._delayNodeL),this.connectEffectRight(this._delayNodeR),this._lfoL.connect(this._delayNodeL.delayTime),this._lfoR.connect(this._delayNodeR.delayTime),this.depth=this._depth,this.type=e.type,this.spread=e.spread}static getDefaults(){return Object.assign(kN.getDefaults(),{frequency:1.5,delayTime:3.5,depth:.7,type:"sine",spread:180,feedback:0,wet:.5})}get depth(){return this._depth}set depth(e){this._depth=e;const t=this._delayTime*e;this._lfoL.min=Math.max(this._delayTime-t,0),this._lfoL.max=this._delayTime+t,this._lfoR.min=Math.max(this._delayTime-t,0),this._lfoR.max=this._delayTime+t}get delayTime(){return this._delayTime*1e3}set delayTime(e){this._delayTime=e/1e3,this.depth=this._depth}get type(){return this._lfoL.type}set type(e){this._lfoL.type=e,this._lfoR.type=e}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(e){this._lfoL.phase=90-e/2,this._lfoR.phase=e/2+90}start(e){return this._lfoL.start(e),this._lfoR.start(e),this}stop(e){return this._lfoL.stop(e),this._lfoR.stop(e),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._delayNodeL.dispose(),this._delayNodeR.dispose(),this.frequency.dispose(),this}}class nm extends Yl{constructor(){const e=ct(nm.getDefaults(),arguments,["distortion"]);super(e),this.name="Distortion",this._shaper=new Th({context:this.context,length:4096}),this._distortion=e.distortion,this.connectEffect(this._shaper),this.distortion=e.distortion,this.oversample=e.oversample}static getDefaults(){return Object.assign(Yl.getDefaults(),{distortion:.4,oversample:"none"})}get distortion(){return this._distortion}set distortion(e){this._distortion=e;const t=e*100,r=Math.PI/180;this._shaper.setMap(i=>Math.abs(i)<.001?0:(3+t)*i*20*r/(Math.PI+t*Math.abs(i)))}get oversample(){return this._shaper.oversample}set oversample(e){this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.dispose(),this}}class NN extends Yl{constructor(e){super(e),this.name="FeedbackEffect",this._feedbackGain=new Xt({context:this.context,gain:e.feedback,units:"normalRange"}),this.feedback=this._feedbackGain.gain,Jt(this,"feedback"),this.effectReturn.chain(this._feedbackGain,this.effectSend)}static getDefaults(){return Object.assign(Yl.getDefaults(),{feedback:.125})}dispose(){return super.dispose(),this._feedbackGain.dispose(),this.feedback.dispose(),this}}class Jy extends NN{constructor(){const e=ct(Jy.getDefaults(),arguments,["delayTime","feedback"]);super(e),this.name="FeedbackDelay",this._delayNode=new ud({context:this.context,delayTime:e.delayTime,maxDelay:e.maxDelay}),this.delayTime=this._delayNode.delayTime,this.connectEffect(this._delayNode),Jt(this,"delayTime")}static getDefaults(){return Object.assign(NN.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._delayNode.dispose(),this.delayTime.dispose(),this}}class DA extends Av{constructor(){const e=ct(DA.getDefaults(),arguments,["frequency","octaves","baseFrequency"]);super(e),this.name="Phaser",this._lfoL=new lh({context:this.context,frequency:e.frequency,min:0,max:1}),this._lfoR=new lh({context:this.context,frequency:e.frequency,min:0,max:1,phase:180}),this._baseFrequency=this.toFrequency(e.baseFrequency),this._octaves=e.octaves,this.Q=new Sn({context:this.context,value:e.Q,units:"positive"}),this._filtersL=this._makeFilters(e.stages,this._lfoL),this._filtersR=this._makeFilters(e.stages,this._lfoR),this.frequency=this._lfoL.frequency,this.frequency.value=e.frequency,this.connectEffectLeft(...this._filtersL),this.connectEffectRight(...this._filtersR),this._lfoL.frequency.connect(this._lfoR.frequency),this.baseFrequency=e.baseFrequency,this.octaves=e.octaves,this._lfoL.start(),this._lfoR.start(),Jt(this,["frequency","Q"])}static getDefaults(){return Object.assign(Av.getDefaults(),{frequency:.5,octaves:3,stages:10,Q:10,baseFrequency:350})}_makeFilters(e,t){const r=[];for(let i=0;ie.disconnect()),this._filtersR.forEach(e=>e.disconnect()),this.frequency.dispose(),this}}class UA extends Yl{constructor(){const e=ct(UA.getDefaults(),arguments,["decay"]);super(e),this.name="Reverb",this._convolver=this.context.createConvolver(),this.ready=Promise.resolve(),this._decay=e.decay,this._preDelay=e.preDelay,this.generate(),this.connectEffect(this._convolver)}static getDefaults(){return Object.assign(Yl.getDefaults(),{decay:1.5,preDelay:.01})}get decay(){return this._decay}set decay(e){e=this.toSeconds(e),Ha(e,.001),this._decay=e,this.generate()}get preDelay(){return this._preDelay}set preDelay(e){e=this.toSeconds(e),Ha(e,0),this._preDelay=e,this.generate()}generate(){return Sr(this,void 0,void 0,function*(){const e=this.ready,t=new By(2,this._decay+this._preDelay,this.context.sampleRate),r=new hd({context:t}),i=new hd({context:t}),s=new Wm({context:t});r.connect(s,0,0),i.connect(s,0,1);const o=new Xt({context:t}).toDestination();s.connect(o),r.start(0),i.start(0),o.gain.setValueAtTime(0,0),o.gain.setValueAtTime(1,this._preDelay),o.gain.exponentialApproachValueAtTime(0,this._preDelay,this.decay);const a=t.render();return this.ready=a.then(Tn),yield e,this._convolver.buffer=(yield a).get(),this})}dispose(){return super.dispose(),this._convolver.disconnect(),this}}class FA extends Yl{constructor(){const e=ct(FA.getDefaults(),arguments,["frequency","depth"]);super(e),this.name="Vibrato",this._delayNode=new ud({context:this.context,delayTime:0,maxDelay:e.maxDelay}),this._lfo=new lh({context:this.context,type:e.type,min:0,max:e.maxDelay,frequency:e.frequency,phase:-90}).start().connect(this._delayNode.delayTime),this.frequency=this._lfo.frequency,this.depth=this._lfo.amplitude,this.depth.value=e.depth,Jt(this,["frequency","depth"]),this.effectSend.chain(this._delayNode,this.effectReturn)}static getDefaults(){return Object.assign(Yl.getDefaults(),{maxDelay:.005,frequency:5,depth:.1,type:"sine"})}get type(){return this._lfo.type}set type(e){this._lfo.type=e}dispose(){return super.dispose(),this._delayNode.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class Nr extends dt{constructor(){const e=ct(Nr.getDefaults(),arguments,["solo"]);super(e),this.name="Solo",this.input=this.output=new Xt({context:this.context}),Nr._allSolos.has(this.context)||Nr._allSolos.set(this.context,new Set),Nr._allSolos.get(this.context).add(this),this.solo=e.solo}static getDefaults(){return Object.assign(dt.getDefaults(),{solo:!1})}get solo(){return this._isSoloed()}set solo(e){e?this._addSolo():this._removeSolo(),Nr._allSolos.get(this.context).forEach(t=>t._updateSolo())}get muted(){return this.input.gain.value===0}_addSolo(){Nr._soloed.has(this.context)||Nr._soloed.set(this.context,new Set),Nr._soloed.get(this.context).add(this)}_removeSolo(){Nr._soloed.has(this.context)&&Nr._soloed.get(this.context).delete(this)}_isSoloed(){return Nr._soloed.has(this.context)&&Nr._soloed.get(this.context).has(this)}_noSolos(){return!Nr._soloed.has(this.context)||Nr._soloed.has(this.context)&&Nr._soloed.get(this.context).size===0}_updateSolo(){this._isSoloed()?this.input.gain.value=1:this._noSolos()?this.input.gain.value=1:this.input.gain.value=0}dispose(){return super.dispose(),Nr._allSolos.get(this.context).delete(this),this._removeSolo(),this}}Nr._allSolos=new Map;Nr._soloed=new Map;class BA extends dt{constructor(){const e=ct(BA.getDefaults(),arguments,["pan","volume"]);super(e),this.name="PanVol",this._panner=this.input=new LA({context:this.context,pan:e.pan,channelCount:e.channelCount}),this.pan=this._panner.pan,this._volume=this.output=new Xl({context:this.context,volume:e.volume}),this.volume=this._volume.volume,this._panner.connect(this._volume),this.mute=e.mute,Jt(this,["pan","volume"])}static getDefaults(){return Object.assign(dt.getDefaults(),{mute:!1,pan:0,volume:0,channelCount:1})}get mute(){return this._volume.mute}set mute(e){this._volume.mute=e}dispose(){return super.dispose(),this._panner.dispose(),this.pan.dispose(),this._volume.dispose(),this.volume.dispose(),this}}class Mf extends dt{constructor(){const e=ct(Mf.getDefaults(),arguments,["volume","pan"]);super(e),this.name="Channel",this._solo=this.input=new Nr({solo:e.solo,context:this.context}),this._panVol=this.output=new BA({context:this.context,pan:e.pan,volume:e.volume,mute:e.mute,channelCount:e.channelCount}),this.pan=this._panVol.pan,this.volume=this._panVol.volume,this._solo.connect(this._panVol),Jt(this,["pan","volume"])}static getDefaults(){return Object.assign(dt.getDefaults(),{pan:0,volume:0,mute:!1,solo:!1,channelCount:1})}get solo(){return this._solo.solo}set solo(e){this._solo.solo=e}get muted(){return this._solo.muted||this.mute}get mute(){return this._panVol.mute}set mute(e){this._panVol.mute=e}_getBus(e){return Mf.buses.has(e)||Mf.buses.set(e,new Xt({context:this.context})),Mf.buses.get(e)}send(e,t=0){const r=this._getBus(e),i=new Xt({context:this.context,units:"decibels",gain:t});return this.connect(i),i.connect(r),i}receive(e){return this._getBus(e).connect(this),this}dispose(){return super.dispose(),this._panVol.dispose(),this.pan.dispose(),this.volume.dispose(),this._solo.dispose(),this}}Mf.buses=new Map;class zA extends dt{constructor(){const e=ct(zA.getDefaults(),arguments,["lowFrequency","highFrequency"]);super(e),this.name="MultibandSplit",this.input=new Xt({context:this.context}),this.output=void 0,this.low=new ro({context:this.context,frequency:0,type:"lowpass"}),this._lowMidFilter=new ro({context:this.context,frequency:0,type:"highpass"}),this.mid=new ro({context:this.context,frequency:0,type:"lowpass"}),this.high=new ro({context:this.context,frequency:0,type:"highpass"}),this._internalChannels=[this.low,this.mid,this.high],this.lowFrequency=new Sn({context:this.context,units:"frequency",value:e.lowFrequency}),this.highFrequency=new Sn({context:this.context,units:"frequency",value:e.highFrequency}),this.Q=new Sn({context:this.context,units:"positive",value:e.Q}),this.input.fan(this.low,this.high),this.input.chain(this._lowMidFilter,this.mid),this.lowFrequency.fan(this.low.frequency,this._lowMidFilter.frequency),this.highFrequency.fan(this.mid.frequency,this.high.frequency),this.Q.connect(this.low.Q),this.Q.connect(this._lowMidFilter.Q),this.Q.connect(this.mid.Q),this.Q.connect(this.high.Q),Jt(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(dt.getDefaults(),{Q:1,highFrequency:2500,lowFrequency:400})}dispose(){return super.dispose(),Fm(this,["high","mid","low","highFrequency","lowFrequency"]),this.low.dispose(),this._lowMidFilter.dispose(),this.mid.dispose(),this.high.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this.Q.dispose(),this}}class VA extends dt{constructor(){const e=ct(VA.getDefaults(),arguments,["threshold","ratio"]);super(e),this.name="Compressor",this._compressor=this.context.createDynamicsCompressor(),this.input=this._compressor,this.output=this._compressor,this.threshold=new Zt({minValue:this._compressor.threshold.minValue,maxValue:this._compressor.threshold.maxValue,context:this.context,convert:!1,param:this._compressor.threshold,units:"decibels",value:e.threshold}),this.attack=new Zt({minValue:this._compressor.attack.minValue,maxValue:this._compressor.attack.maxValue,context:this.context,param:this._compressor.attack,units:"time",value:e.attack}),this.release=new Zt({minValue:this._compressor.release.minValue,maxValue:this._compressor.release.maxValue,context:this.context,param:this._compressor.release,units:"time",value:e.release}),this.knee=new Zt({minValue:this._compressor.knee.minValue,maxValue:this._compressor.knee.maxValue,context:this.context,convert:!1,param:this._compressor.knee,units:"decibels",value:e.knee}),this.ratio=new Zt({minValue:this._compressor.ratio.minValue,maxValue:this._compressor.ratio.maxValue,context:this.context,convert:!1,param:this._compressor.ratio,units:"positive",value:e.ratio}),Jt(this,["knee","release","attack","ratio","threshold"])}static getDefaults(){return Object.assign(dt.getDefaults(),{attack:.003,knee:30,ratio:12,release:.25,threshold:-24})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.disconnect(),this.attack.dispose(),this.release.dispose(),this.threshold.dispose(),this.ratio.dispose(),this.knee.dispose(),this}}class HA extends dt{constructor(){const e=ct(HA.getDefaults(),arguments,["low","mid","high"]);super(e),this.name="EQ3",this.output=new Xt({context:this.context}),this._internalChannels=[],this.input=this._multibandSplit=new zA({context:this.context,highFrequency:e.highFrequency,lowFrequency:e.lowFrequency}),this._lowGain=new Xt({context:this.context,gain:e.low,units:"decibels"}),this._midGain=new Xt({context:this.context,gain:e.mid,units:"decibels"}),this._highGain=new Xt({context:this.context,gain:e.high,units:"decibels"}),this.low=this._lowGain.gain,this.mid=this._midGain.gain,this.high=this._highGain.gain,this.Q=this._multibandSplit.Q,this.lowFrequency=this._multibandSplit.lowFrequency,this.highFrequency=this._multibandSplit.highFrequency,this._multibandSplit.low.chain(this._lowGain,this.output),this._multibandSplit.mid.chain(this._midGain,this.output),this._multibandSplit.high.chain(this._highGain,this.output),Jt(this,["low","mid","high","lowFrequency","highFrequency"]),this._internalChannels=[this._multibandSplit]}static getDefaults(){return Object.assign(dt.getDefaults(),{high:0,highFrequency:2500,low:0,lowFrequency:400,mid:0})}dispose(){return super.dispose(),Fm(this,["low","mid","high","lowFrequency","highFrequency"]),this._multibandSplit.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this._lowGain.dispose(),this._midGain.dispose(),this._highGain.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.Q.dispose(),this}}ji().transport;function GA(){return ji().transport}ji().destination;ji().destination;function Lae(){return ji().destination}ji().listener;ji().draw;ji();const Ub=Ur("256n").toSeconds(),Pae=Ur("8n").toSeconds();function Dae(){const n=new UA;n.set({wet:0});const e=new Jy;e.set({wet:0,delayTime:Ub,maxDelay:"1n",feedback:.666});const t=new PA;t.set({wet:0,depth:.999,frequency:7,feedback:.666});const r=new DA;r.set({wet:0,Q:10});const i=new nm;i.set({wet:0,distortion:.9});const s=new FA;return s.set({wet:0,depth:.2}),{reverb:n,echo:e,chorus:t,phaser:r,distortion:i,vibrato:s}}const Uae={a:1,b:2,c:3,d:4,e:5,f:6,g:7,x:8,"#":9,"!":10,y:13,t:14,s:15,i:16,q:17,h:18,w:19,3:20,".":21,"+":11,"-":12,0:22,1:23,2:24,p:25,4:26,5:27,6:29,7:28,8:30,9:31};let Fae=0;function Bae(n,e,t){let r=e,i=3,s="32n",o="",a="";const c=[];function l(){a="",o="",r+=Ur(s).toSeconds()}function u(){a===null?(c.push([r,[n,s,a]]),l()):gt(a)?(c.push([r,[n,s,a]]),l()):a!==""&&(c.push([r,[n,s,`${a}${o}${i}`]]),l())}for(let h=0;h{if(!k_){const n=GA();n.bpm.value=107,n.start(),lo("synth","audio is enabled!"),k_=!0}}).catch(()=>{})}function Vae(){const n=Lae(),e=new Xl(8);e.connect(n);const t=new VA({threshold:-24,ratio:4,attack:.003,release:.25,knee:30});t.connect(e);const r=new Xt;r.connect(t);const i=new Xl(2);i.connect(t);const s=[xc(r),xc(r),xc(r),xc(r),xc(r),xc(r),xc(r),xc(r),xc(r)],o=new Tv().connect(i);o.maxPolyphony=8,o.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"square"}});function a(De){o.triggerAttackRelease("C6","1i",De)}const c=new Fi().connect(i);o.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"square"}});function l(De){const A=Ur("64n").toSeconds();c.triggerAttackRelease("C6","8n",De),c.frequency.exponentialRampToValueAtTime("C11",A+De)}const u=new ro(350,"bandpass").connect(i),h=new Xt().connect(u);h.gain.value=0;const d=new Tv().connect(h);d.maxPolyphony=8,d.set({envelope:{attack:.001,decay:.01,sustain:.1,release:.1},oscillator:{type:"square"}});function m(De,A){const ie=Ur("64n").toSeconds()+Ur(De).toSeconds();h.gain.setValueAtTime(.5,A),h.gain.exponentialRampToValueAtTime(.01,ie+A),d.triggerAttackRelease([800,540],De,A)}const g=new HA(-10,10,-1).connect(i),v=new ro(800,"highpass",-12);v.connect(g);const y=new wf;y.set({envelope:{attack:.01,decay:.1,sustain:.1,release:.1}}),y.connect(v);function _(De,A){y.triggerAttackRelease(De,A)}const S=new nm().connect(i);S.set({distortion:.666});const E=new Fi;E.set({envelope:{attack:0,decay:.1,sustain:0,release:1},oscillator:{type:"triangle"}}),E.connect(S);const T=new ro;T.set({type:"highpass",frequency:1e4}),T.connect(S);const k=new wf;k.set({envelope:{attack:.01,decay:.1,sustain:0,release:.1}}),k.connect(T);function R(De,A){const ie=Ur("512n").toSeconds(),te=Ur("32n").toSeconds();E.triggerAttackRelease(1e4,De,A,1),E.frequency.exponentialRampToValueAtTime(300,A+ie),E.frequency.exponentialRampToValueAtTime(100,A+te),k.triggerAttackRelease("8n",A,.333),k.volume.setValueAtTime(1,A),k.volume.exponentialRampToValueAtTime(0,A+Ur("32n").toSeconds())}const M=new ro;M.set({type:"bandpass",frequency:256,Q:.17}),M.connect(i);const O=new Fi;O.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"sawtooth"}}),O.connect(M);const C=new Fi;C.set({envelope:{attack:.001,decay:.1,sustain:.001,release:.1},oscillator:{type:"sine"}}),C.connect(M);function I(De,A){O.triggerAttackRelease(2e3,De,A),O.frequency.exponentialRampToValueAtTime(1e3,A+Ur("32n").toSeconds()),C.triggerAttackRelease(999,De,A),C.frequency.exponentialRampToValueAtTime(888,A+Ur("256n").toSeconds())}const U=new nm().connect(i);U.set({distortion:.876});const L=new Fi;L.set({envelope:{attack:0,decay:.1,sustain:0,release:1},oscillator:{type:"triangle"}}),L.connect(U);const P=new ro;P.set({type:"highpass",frequency:1e4}),P.connect(U);const w=new wf;w.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1}}),w.connect(P);function H(De,A){const ie=Ur("512n").toSeconds(),te=Ur("32n").toSeconds();L.triggerAttackRelease(1e4,De,A,1),L.frequency.exponentialRampToValueAtTime(150,A+ie),L.frequency.exponentialRampToValueAtTime(100,A+te),w.triggerAttackRelease("8n",A,.25),w.volume.setValueAtTime(1,A),w.volume.exponentialRampToValueAtTime(0,A+Ur("32n").toSeconds())}const V=new Fi().connect(i);V.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1},oscillator:{type:"sawtooth"}});const B=new Fi().connect(i);V.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1},oscillator:{type:"triangle"}});const z=new wf().connect(i);z.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1}});function W(De,A){const ie=Ur("256n").toSeconds(),te=Ur(De).toSeconds()-ie;V.triggerAttackRelease("C4",te,A,1),V.frequency.exponentialRampToValueAtTime(MN("C0").toFrequency(),A+te),B.triggerAttackRelease("C5",te,A,.5),B.frequency.exponentialRampToValueAtTime(MN("C0").toFrequency(),A+te);const X=Ur("4n").toSeconds();z.triggerAttackRelease("8n",A),z.volume.setValueAtTime(1,A),z.volume.exponentialRampToValueAtTime(0,A+X)}const K=new ro;K.set({type:"bandpass",frequency:256,Q:.17}),K.connect(i);const j=new Fi;j.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"sawtooth"}}),j.connect(K);const Y=new Fi;Y.set({envelope:{attack:.001,decay:.1,sustain:.001,release:.1},oscillator:{type:"sine"}}),Y.connect(K);function ge(De,A){j.triggerAttackRelease(2e3,De,A),j.frequency.exponentialRampToValueAtTime(100,A+Ur("32n").toSeconds()),Y.triggerAttackRelease(699,De,A),Y.frequency.exponentialRampToValueAtTime(399,A+Ur("256n").toSeconds())}const Q=new Gm().connect(i);Q.set({octaves:8});function re(De){Q.triggerAttackRelease("C1","8n",De)}const be=new wv(Ae);function Ae(De,A){if(A===null)return;const[ie,te,X]=A;if(Bt(X)&&Z(s[ie])&&s[ie].source.triggerAttackRelease(X,te,De),gt(X))switch(X){case 0:a(De);break;case 1:l(De);break;case 2:m(te,De);break;case 3:_(te,De);break;case 4:R(te,De);break;case 5:I(te,De);break;case 6:H(te,De);break;case 7:W(te,De);break;case 8:ge(te,De);break;case 9:re(De);break;case-1:--He,He===0&&(Le=-1);break}}function Ee(De,A,ie){let te=A;const X=Bae(De,A,ie),$=X[X.length-1];Z($)&&(te=Math.max(te,$[0]));for(let ne=0;ne{if(k_&&!Z(bu)&&(bu=Vae()),!!Z(bu))switch(n.target){case"tts":_a("tts",async()=>{if(cn(n.data)){const[e,t]=n.data;await jae(e,t)}});break;case"play":if(cn(n.data)){const[e,t]=n.data;t===""?bu.stopplay():bu.addplay(e,t)}break;case"voice":if(cn(n.data)){const[e,t,r]=n.data,i=bu.SOURCE[e];if(!Z(i)){An(Sc.name(),n.target,`unknown voice ${e}`);return}switch(t){case"bpm":if(gt(r)){GA().bpm.value=r;return}break;case"vol":case"volume":if(gt(r)){i.source.volume.value=r;return}break;case"port":case"portamento":if(gt(r)){i.source.portamento=r;return}break;case"env":case"envelope":if(cn(r)){const[s,o,a,c]=r;i.source.set({envelope:{attack:s,decay:o,sustain:a,release:c}});return}break;default:if(Bt(t)){if(Hae(t,r)){i.source.set({oscillator:{type:t}}),cn(r)&&i.source.set({oscillator:{partials:r}}),gt(r)&&i.source.set({oscillator:{partials:[r]}});return}const s=i.source.get().oscillator.type;switch(s){case"pwm":switch(t){case"modfreq":case"modulationfrequency":if(gt(r)){i.source.set({oscillator:{modulationFrequency:r}});return}break}break;case"pulse":switch(t){case"width":if(gt(r)){i.source.set({oscillator:{width:r}});return}break}break;case"custom":case"sine":case"square":case"triangle":case"sawtooth":switch(t){case"phase":if(gt(r)){i.source.set({oscillator:{phase:r}});return}break}break;case"amcustom":case"amsine":case"amsquare":case"amtriangle":case"amsawtooth":switch(t){case"harmonicity":if(gt(r)){i.source.set({oscillator:{harmonicity:r}});return}break;case"modtype":case"modulationtype":if(Bt(r)){i.source.set({oscillator:{modulationType:r}});return}break;case"modenv":case"modulationenvelope":if(cn(r)){const[o,a,c,l]=r;i.source.set({oscillator:{modulationEnvelope:{attack:o,decay:a,sustain:c,release:l}}});return}break}break;case"fmcustom":case"fmsine":case"fmsquare":case"fmtriangle":case"fmsawtooth":switch(t){case"harmonicity":if(gt(r)){i.source.set({oscillator:{harmonicity:r}});return}break;case"modindex":if(gt(r)){i.source.set({oscillator:{modulationIndex:r}});return}break;case"modtype":if(Bt(r)){i.source.set({oscillator:{modulationType:r}});return}break;case"modenv":if(cn(r)){const[o,a,c,l]=r;i.source.set({oscillator:{modulationEnvelope:{attack:o,decay:a,sustain:c,release:l}}});return}break}break;case"fatcustom":case"fatsine":case"fatsquare":case"fattriangle":case"fatsawtooth":switch(t){case"count":if(gt(r)){i.source.set({oscillator:{count:r}});return}break;case"phase":if(gt(r)){i.source.set({oscillator:{phase:r}});return}break;case"spread":if(gt(r)){i.source.set({oscillator:{spread:r}});return}break}break}An(Sc.name(),n.target,`unknown ${s} config ${t}`)}break}}break;case"voicefx":if(cn(n.data)){const[e,t,r,i]=n.data,s=bu.SOURCE[e],o=s==null?void 0:s.fx[t];if(Z(o)){switch(r){case"on":o.wet.value=.2;break;case"off":o.wet.value=0;break;default:if(gt(r))o.wet.value=Nn(.01*r,0,1);else switch(t){case"vibrato":{switch(r){default:An(Sc.name(),n.target,`unknown ${t} config ${r}`);break}break}case"chorus":{switch(r){default:An(Sc.name(),n.target,`unknown ${t} config ${r}`);break}break}case"phaser":{const a=o;switch(r){case"q":gt(i)&&(a.Q.value=i);break;case"octaves":gt(i)&&(a.octaves=i);break;case"basefrequency":gt(i)&&(a.baseFrequency=i);break;default:An(Sc.name(),n.target,`unknown ${t} config ${r}`);break}break}case"distortion":{const a=o;switch(r){case"distortion":gt(i)&&(a.distortion=i);break;case"oversample":switch(i){case"2x":case"4x":case"none":a.oversample=i;break}break;default:An(Sc.name(),n.target,`unknown ${t} config ${r}`);break}break}case"echo":{const a=o;switch(r){case"delaytime":a.delayTime.value=i;break;default:An(Sc.name(),n.target,`unknown ${t} config ${r}`);break}break}case"reverb":{const a=o;switch(r){case"decay":a.decay=i;break;case"predelay":a.preDelay=i;break;default:An(Sc.name(),n.target,`unknown ${t} config ${r}`);break}break}}break}o instanceof Jy&&(o.wet.value===0?o.set({delayTime:Ub}):o.get().delayTime===Ub&&o.set({delayTime:Pae}));return}An(Sc.name(),n.target,`unknown fx ${t}`)}break}});/** + * postprocessing v6.36.4 build Tue Nov 05 2024 + * https://github.com/pmndrs/postprocessing + * Copyright 2015-2024 Raoul van Rüschen + * @license Zlib + */var k1=1/1e3,$ae=1e3,qae=class{constructor(){this.startTime=performance.now(),this.previousTime=0,this.currentTime=0,this._delta=0,this._elapsed=0,this._fixedDelta=1e3/60,this.timescale=1,this.useFixedDelta=!1,this._autoReset=!1}get autoReset(){return this._autoReset}set autoReset(n){typeof document<"u"&&document.hidden!==void 0&&(n?document.addEventListener("visibilitychange",this):document.removeEventListener("visibilitychange",this),this._autoReset=n)}get delta(){return this._delta*k1}get fixedDelta(){return this._fixedDelta*k1}set fixedDelta(n){this._fixedDelta=n*$ae}get elapsed(){return this._elapsed*k1}update(n){this.useFixedDelta?this._delta=this.fixedDelta:(this.previousTime=this.currentTime,this.currentTime=(n!==void 0?n:performance.now())-this.startTime,this._delta=this.currentTime-this.previousTime),this._delta*=this.timescale,this._elapsed+=this._delta}reset(){this._delta=0,this._elapsed=0,this.currentTime=performance.now()-this.startTime}getDelta(){return this.delta}getElapsed(){return this.elapsed}handleEvent(n){document.hidden||(this.currentTime=performance.now()-this.startTime)}dispose(){this.autoReset=!1}},Xae=(()=>{const n=new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),e=new Float32Array([0,0,2,0,0,2]),t=new jo;return t.setAttribute("position",new er(n,3)),t.setAttribute("uv",new er(e,2)),t})(),Yo=class Fb{static get fullscreenGeometry(){return Xae}constructor(e="Pass",t=new Z_,r=new Qv){this.name=e,this.renderer=null,this.scene=t,this.camera=r,this.screen=null,this.rtt=!0,this.needsSwap=!0,this.needsDepthTexture=!1,this.enabled=!0}get renderToScreen(){return!this.rtt}set renderToScreen(e){if(this.rtt===e){const t=this.fullscreenMaterial;t!==null&&(t.needsUpdate=!0),this.rtt=!e}}set mainScene(e){}set mainCamera(e){}setRenderer(e){this.renderer=e}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}get fullscreenMaterial(){return this.screen!==null?this.screen.material:null}set fullscreenMaterial(e){let t=this.screen;t!==null?t.material=e:(t=new Io(Fb.fullscreenGeometry,e),t.frustumCulled=!1,this.scene===null&&(this.scene=new Z_),this.scene.add(t),this.screen=t)}getFullscreenMaterial(){return this.fullscreenMaterial}setFullscreenMaterial(e){this.fullscreenMaterial=e}getDepthTexture(){return null}setDepthTexture(e,t=dh){}render(e,t,r,i,s){throw new Error("Render method not implemented!")}setSize(e,t){}initialize(e,t,r){}dispose(){for(const e of Object.keys(this)){const t=this[e];(t instanceof Gs||t instanceof Kc||t instanceof ur||t instanceof Fb)&&this[e].dispose()}this.fullscreenMaterial!==null&&this.fullscreenMaterial.dispose()}},Kae=class extends Yo{constructor(){super("ClearMaskPass",null,null),this.needsSwap=!1}render(n,e,t,r,i){const s=n.state.buffers.stencil;s.setLocked(!1),s.setTest(!1)}},Yae=`#include +#include +#ifdef FRAMEBUFFER_PRECISION_HIGH +uniform mediump sampler2D inputBuffer; +#else +uniform lowp sampler2D inputBuffer; +#endif +uniform float opacity;varying vec2 vUv;void main(){vec4 texel=texture2D(inputBuffer,vUv);gl_FragColor=opacity*texel; +#include +#include +}`,Zae="varying vec2 vUv;void main(){vUv=position.xy*0.5+0.5;gl_Position=vec4(position.xy,1.0,1.0);}",Jae=class extends qi{constructor(){super({name:"CopyMaterial",uniforms:{inputBuffer:new kn(null),opacity:new kn(1)},blending:Po,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:Yae,vertexShader:Zae})}set inputBuffer(n){this.uniforms.inputBuffer.value=n}setInputBuffer(n){this.uniforms.inputBuffer.value=n}getOpacity(n){return this.uniforms.opacity.value}setOpacity(n){this.uniforms.opacity.value=n}},Qae=class extends Yo{constructor(n,e=!0){super("CopyPass"),this.fullscreenMaterial=new Jae,this.needsSwap=!1,this.renderTarget=n,n===void 0&&(this.renderTarget=new Gs(1,1,{minFilter:fs,magFilter:fs,stencilBuffer:!1,depthBuffer:!1}),this.renderTarget.texture.name="CopyPass.Target"),this.autoResize=e}get resize(){return this.autoResize}set resize(n){this.autoResize=n}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}setAutoResizeEnabled(n){this.autoResize=n}render(n,e,t,r,i){this.fullscreenMaterial.inputBuffer=e.texture,n.setRenderTarget(this.renderToScreen?null:this.renderTarget),n.render(this.scene,this.camera)}setSize(n,e){this.autoResize&&this.renderTarget.setSize(n,e)}initialize(n,e,t){t!==void 0&&(this.renderTarget.texture.type=t,t!==Mi?this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1":n!==null&&n.outputColorSpace===vr&&(this.renderTarget.texture.colorSpace=vr))}},IN=new hn,k3=class extends Yo{constructor(n=!0,e=!0,t=!1){super("ClearPass",null,null),this.needsSwap=!1,this.color=n,this.depth=e,this.stencil=t,this.overrideClearColor=null,this.overrideClearAlpha=-1}setClearFlags(n,e,t){this.color=n,this.depth=e,this.stencil=t}getOverrideClearColor(){return this.overrideClearColor}setOverrideClearColor(n){this.overrideClearColor=n}getOverrideClearAlpha(){return this.overrideClearAlpha}setOverrideClearAlpha(n){this.overrideClearAlpha=n}render(n,e,t,r,i){const s=this.overrideClearColor,o=this.overrideClearAlpha,a=n.getClearAlpha(),c=s!==null,l=o>=0;c?(n.getClearColor(IN),n.setClearColor(s,l?o:a)):l&&n.setClearAlpha(o),n.setRenderTarget(this.renderToScreen?null:e),n.clear(this.color,this.depth,this.stencil),c?n.setClearColor(IN,a):l&&n.setClearAlpha(a)}},ece=class extends Yo{constructor(n,e){super("MaskPass",n,e),this.needsSwap=!1,this.clearPass=new k3(!1,!1,!0),this.inverse=!1}set mainScene(n){this.scene=n}set mainCamera(n){this.camera=n}get inverted(){return this.inverse}set inverted(n){this.inverse=n}get clear(){return this.clearPass.enabled}set clear(n){this.clearPass.enabled=n}getClearPass(){return this.clearPass}isInverted(){return this.inverted}setInverted(n){this.inverted=n}render(n,e,t,r,i){const s=n.getContext(),o=n.state.buffers,a=this.scene,c=this.camera,l=this.clearPass,u=this.inverted?0:1,h=1-u;o.color.setMask(!1),o.depth.setMask(!1),o.color.setLocked(!0),o.depth.setLocked(!0),o.stencil.setTest(!0),o.stencil.setOp(s.REPLACE,s.REPLACE,s.REPLACE),o.stencil.setFunc(s.ALWAYS,u,4294967295),o.stencil.setClear(h),o.stencil.setLocked(!0),this.clearPass.enabled&&(this.renderToScreen?l.render(n,null):(l.render(n,e),l.render(n,t))),this.renderToScreen?(n.setRenderTarget(null),n.render(a,c)):(n.setRenderTarget(e),n.render(a,c),n.setRenderTarget(t),n.render(a,c)),o.color.setLocked(!1),o.depth.setLocked(!1),o.stencil.setLocked(!1),o.stencil.setFunc(s.EQUAL,1,4294967295),o.stencil.setOp(s.KEEP,s.KEEP,s.KEEP),o.stencil.setLocked(!0)}},tce=class{constructor(e=null,{depthBuffer:t=!0,stencilBuffer:r=!1,multisampling:i=0,frameBufferType:s}={}){this.renderer=null,this.inputBuffer=this.createBuffer(t,r,s,i),this.outputBuffer=this.inputBuffer.clone(),this.copyPass=new Qae,this.depthTexture=null,this.passes=[],this.timer=new qae,this.autoRenderToScreen=!0,this.setRenderer(e)}get multisampling(){return this.inputBuffer.samples||0}set multisampling(e){const t=this.inputBuffer,r=this.multisampling;r>0&&e>0?(this.inputBuffer.samples=e,this.outputBuffer.samples=e,this.inputBuffer.dispose(),this.outputBuffer.dispose()):r!==e&&(this.inputBuffer.dispose(),this.outputBuffer.dispose(),this.inputBuffer=this.createBuffer(t.depthBuffer,t.stencilBuffer,t.texture.type,e),this.inputBuffer.depthTexture=this.depthTexture,this.outputBuffer=this.inputBuffer.clone())}getTimer(){return this.timer}getRenderer(){return this.renderer}setRenderer(e){if(this.renderer=e,e!==null){const t=e.getSize(new Et),r=e.getContext().getContextAttributes().alpha,i=this.inputBuffer.texture.type;i===Mi&&e.outputColorSpace===vr&&(this.inputBuffer.texture.colorSpace=vr,this.outputBuffer.texture.colorSpace=vr,this.inputBuffer.dispose(),this.outputBuffer.dispose()),e.autoClear=!1,this.setSize(t.width,t.height);for(const s of this.passes)s.initialize(e,r,i)}}replaceRenderer(e,t=!0){const r=this.renderer,i=r.domElement.parentNode;return this.setRenderer(e),t&&i!==null&&(i.removeChild(r.domElement),i.appendChild(e.domElement)),r}createDepthTexture(){const e=this.depthTexture=new XT;return this.inputBuffer.depthTexture=e,this.inputBuffer.dispose(),this.inputBuffer.stencilBuffer?(e.format=Ju,e.type=Zu):e.type=zl,e}deleteDepthTexture(){if(this.depthTexture!==null){this.depthTexture.dispose(),this.depthTexture=null,this.inputBuffer.depthTexture=null,this.inputBuffer.dispose();for(const e of this.passes)e.setDepthTexture(null)}}createBuffer(e,t,r,i){const s=this.renderer,o=s===null?new Et:s.getDrawingBufferSize(new Et),a={minFilter:fs,magFilter:fs,stencilBuffer:t,depthBuffer:e,type:r},c=new Gs(o.width,o.height,a);return i>0&&(c.ignoreDepthForMultisampleCopy=!1,c.samples=i),r===Mi&&s!==null&&s.outputColorSpace===vr&&(c.texture.colorSpace=vr),c.texture.name="EffectComposer.Buffer",c.texture.generateMipmaps=!1,c}setMainScene(e){for(const t of this.passes)t.mainScene=e}setMainCamera(e){for(const t of this.passes)t.mainCamera=e}addPass(e,t){const r=this.passes,i=this.renderer,s=i.getDrawingBufferSize(new Et),o=i.getContext().getContextAttributes().alpha,a=this.inputBuffer.texture.type;if(e.setRenderer(i),e.setSize(s.width,s.height),e.initialize(i,o,a),this.autoRenderToScreen&&(r.length>0&&(r[r.length-1].renderToScreen=!1),e.renderToScreen&&(this.autoRenderToScreen=!1)),t!==void 0?r.splice(t,0,e):r.push(e),this.autoRenderToScreen&&(r[r.length-1].renderToScreen=!0),e.needsDepthTexture||this.depthTexture!==null)if(this.depthTexture===null){const c=this.createDepthTexture();for(e of r)e.setDepthTexture(c)}else e.setDepthTexture(this.depthTexture)}removePass(e){const t=this.passes,r=t.indexOf(e);if(r!==-1&&t.splice(r,1).length>0){if(this.depthTexture!==null){const o=(c,l)=>c||l.needsDepthTexture;t.reduce(o,!1)||(e.getDepthTexture()===this.depthTexture&&e.setDepthTexture(null),this.deleteDepthTexture())}this.autoRenderToScreen&&r===t.length&&(e.renderToScreen=!1,t.length>0&&(t[t.length-1].renderToScreen=!0))}}removeAllPasses(){const e=this.passes;this.deleteDepthTexture(),e.length>0&&(this.autoRenderToScreen&&(e[e.length-1].renderToScreen=!1),this.passes=[])}render(e){const t=this.renderer,r=this.copyPass;let i=this.inputBuffer,s=this.outputBuffer,o=!1,a,c,l;e===void 0&&(this.timer.update(),e=this.timer.getDelta());for(const u of this.passes)u.enabled&&(u.render(t,i,s,e,o),u.needsSwap&&(o&&(r.renderToScreen=u.renderToScreen,a=t.getContext(),c=t.state.buffers.stencil,c.setFunc(a.NOTEQUAL,1,4294967295),r.render(t,i,s,e,o),c.setFunc(a.EQUAL,1,4294967295)),l=i,i=s,s=l),u instanceof ece?o=!0:u instanceof Kae&&(o=!1))}setSize(e,t,r){const i=this.renderer,s=i.getSize(new Et);(e===void 0||t===void 0)&&(e=s.width,t=s.height),(s.width!==e||s.height!==t)&&i.setSize(e,t,r);const o=i.getDrawingBufferSize(new Et);this.inputBuffer.setSize(o.width,o.height),this.outputBuffer.setSize(o.width,o.height);for(const a of this.passes)a.setSize(o.width,o.height)}reset(){this.dispose(),this.autoRenderToScreen=!0}dispose(){for(const e of this.passes)e.dispose();this.passes=[],this.inputBuffer!==null&&this.inputBuffer.dispose(),this.outputBuffer!==null&&this.outputBuffer.dispose(),this.deleteDepthTexture(),this.copyPass.dispose(),this.timer.dispose(),Yo.fullscreenGeometry.dispose()}},La={NONE:0,DEPTH:1,CONVOLUTION:2},yn={FRAGMENT_HEAD:"FRAGMENT_HEAD",FRAGMENT_MAIN_UV:"FRAGMENT_MAIN_UV",FRAGMENT_MAIN_IMAGE:"FRAGMENT_MAIN_IMAGE",VERTEX_HEAD:"VERTEX_HEAD",VERTEX_MAIN_SUPPORT:"VERTEX_MAIN_SUPPORT"},nce=class{constructor(){this.shaderParts=new Map([[yn.FRAGMENT_HEAD,null],[yn.FRAGMENT_MAIN_UV,null],[yn.FRAGMENT_MAIN_IMAGE,null],[yn.VERTEX_HEAD,null],[yn.VERTEX_MAIN_SUPPORT,null]]),this.defines=new Map,this.uniforms=new Map,this.blendModes=new Map,this.extensions=new Set,this.attributes=La.NONE,this.varyings=new Set,this.uvTransformation=!1,this.readDepth=!1,this.colorSpace=Ql}},N1=!1,ON=class{constructor(n=null){this.originalMaterials=new Map,this.material=null,this.materials=null,this.materialsBackSide=null,this.materialsDoubleSide=null,this.materialsFlatShaded=null,this.materialsFlatShadedBackSide=null,this.materialsFlatShadedDoubleSide=null,this.setMaterial(n),this.meshCount=0,this.replaceMaterial=e=>{if(e.isMesh){let t;if(e.material.flatShading)switch(e.material.side){case Us:t=this.materialsFlatShadedDoubleSide;break;case ci:t=this.materialsFlatShadedBackSide;break;default:t=this.materialsFlatShaded;break}else switch(e.material.side){case Us:t=this.materialsDoubleSide;break;case ci:t=this.materialsBackSide;break;default:t=this.materials;break}this.originalMaterials.set(e,e.material),e.isSkinnedMesh?e.material=t[2]:e.isInstancedMesh?e.material=t[1]:e.material=t[0],++this.meshCount}}}cloneMaterial(n){if(!(n instanceof qi))return n.clone();const e=n.uniforms,t=new Map;for(const i in e){const s=e[i].value;s.isRenderTargetTexture&&(e[i].value=null,t.set(i,s))}const r=n.clone();for(const i of t)e[i[0]].value=i[1],r.uniforms[i[0]].value=i[1];return r}setMaterial(n){if(this.disposeMaterials(),this.material=n,n!==null){const e=this.materials=[this.cloneMaterial(n),this.cloneMaterial(n),this.cloneMaterial(n)];for(const t of e)t.uniforms=Object.assign({},n.uniforms),t.side=zc;e[2].skinning=!0,this.materialsBackSide=e.map(t=>{const r=this.cloneMaterial(t);return r.uniforms=Object.assign({},n.uniforms),r.side=ci,r}),this.materialsDoubleSide=e.map(t=>{const r=this.cloneMaterial(t);return r.uniforms=Object.assign({},n.uniforms),r.side=Us,r}),this.materialsFlatShaded=e.map(t=>{const r=this.cloneMaterial(t);return r.uniforms=Object.assign({},n.uniforms),r.flatShading=!0,r}),this.materialsFlatShadedBackSide=e.map(t=>{const r=this.cloneMaterial(t);return r.uniforms=Object.assign({},n.uniforms),r.flatShading=!0,r.side=ci,r}),this.materialsFlatShadedDoubleSide=e.map(t=>{const r=this.cloneMaterial(t);return r.uniforms=Object.assign({},n.uniforms),r.flatShading=!0,r.side=Us,r})}}render(n,e,t){const r=n.shadowMap.enabled;if(n.shadowMap.enabled=!1,N1){const i=this.originalMaterials;this.meshCount=0,e.traverse(this.replaceMaterial),n.render(e,t);for(const s of i)s[0].material=s[1];this.meshCount!==i.size&&i.clear()}else{const i=e.overrideMaterial;e.overrideMaterial=this.material,n.render(e,t),e.overrideMaterial=i}n.shadowMap.enabled=r}disposeMaterials(){if(this.material!==null){const n=this.materials.concat(this.materialsBackSide).concat(this.materialsDoubleSide).concat(this.materialsFlatShaded).concat(this.materialsFlatShadedBackSide).concat(this.materialsFlatShadedDoubleSide);for(const e of n)e.dispose()}}dispose(){this.originalMaterials.clear(),this.disposeMaterials()}static get workaroundEnabled(){return N1}static set workaroundEnabled(n){N1=n}},Al=-1,zf=class extends Xc{constructor(n,e=Al,t=Al,r=1){super(),this.resizable=n,this.baseSize=new Et(1,1),this.preferredSize=new Et(e,t),this.target=this.preferredSize,this.s=r,this.effectiveSize=new Et,this.addEventListener("change",()=>this.updateEffectiveSize()),this.updateEffectiveSize()}updateEffectiveSize(){const n=this.baseSize,e=this.preferredSize,t=this.effectiveSize,r=this.scale;e.width!==Al?t.width=e.width:e.height!==Al?t.width=Math.round(e.height*(n.width/Math.max(n.height,1))):t.width=Math.round(n.width*r),e.height!==Al?t.height=e.height:e.width!==Al?t.height=Math.round(e.width/Math.max(n.width/Math.max(n.height,1),1)):t.height=Math.round(n.height*r)}get width(){return this.effectiveSize.width}set width(n){this.preferredWidth=n}get height(){return this.effectiveSize.height}set height(n){this.preferredHeight=n}getWidth(){return this.width}getHeight(){return this.height}get scale(){return this.s}set scale(n){this.s!==n&&(this.s=n,this.preferredSize.setScalar(Al),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getScale(){return this.scale}setScale(n){this.scale=n}get baseWidth(){return this.baseSize.width}set baseWidth(n){this.baseSize.width!==n&&(this.baseSize.width=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseWidth(){return this.baseWidth}setBaseWidth(n){this.baseWidth=n}get baseHeight(){return this.baseSize.height}set baseHeight(n){this.baseSize.height!==n&&(this.baseSize.height=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseHeight(){return this.baseHeight}setBaseHeight(n){this.baseHeight=n}setBaseSize(n,e){(this.baseSize.width!==n||this.baseSize.height!==e)&&(this.baseSize.set(n,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}get preferredWidth(){return this.preferredSize.width}set preferredWidth(n){this.preferredSize.width!==n&&(this.preferredSize.width=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredWidth(){return this.preferredWidth}setPreferredWidth(n){this.preferredWidth=n}get preferredHeight(){return this.preferredSize.height}set preferredHeight(n){this.preferredSize.height!==n&&(this.preferredSize.height=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredHeight(){return this.preferredHeight}setPreferredHeight(n){this.preferredHeight=n}setPreferredSize(n,e){(this.preferredSize.width!==n||this.preferredSize.height!==e)&&(this.preferredSize.set(n,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}copy(n){this.s=n.scale,this.baseSize.set(n.baseWidth,n.baseHeight),this.preferredSize.set(n.preferredWidth,n.preferredHeight),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height)}static get AUTO_SIZE(){return Al}},en={SKIP:9,SET:30,ADD:0,ALPHA:1,AVERAGE:2,COLOR:3,COLOR_BURN:4,COLOR_DODGE:5,DARKEN:6,DIFFERENCE:7,DIVIDE:8,DST:9,EXCLUSION:10,HARD_LIGHT:11,HARD_MIX:12,HUE:13,INVERT:14,INVERT_RGB:15,LIGHTEN:16,LINEAR_BURN:17,LINEAR_DODGE:18,LINEAR_LIGHT:19,LUMINOSITY:20,MULTIPLY:21,NEGATION:22,NORMAL:23,OVERLAY:24,PIN_LIGHT:25,REFLECT:26,SATURATION:27,SCREEN:28,SOFT_LIGHT:29,SRC:30,SUBTRACT:31,VIVID_LIGHT:32},rce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x+y,opacity);}",ice="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y,min(y.a,opacity));}",sce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,(x+y)*0.5,opacity);}",oce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.rg,xHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",ace="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(step(0.0,y)*(1.0-min(vec4(1.0),(1.0-x)/y)),vec4(1.0),step(1.0,x));return mix(x,z,opacity);}",cce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=step(0.0,x)*mix(min(vec4(1.0),x/max(1.0-y,1e-9)),vec4(1.0),step(1.0,y));return mix(x,z,opacity);}",lce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,min(x,y),opacity);}",uce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,abs(x-y),opacity);}",hce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x/max(y,1e-12),opacity);}",fce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,(x+y-2.0*x*y),opacity);}",dce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 a=min(x,1.0),b=min(y,1.0);vec4 z=mix(2.0*a*b,1.0-2.0*(1.0-a)*(1.0-b),step(0.5,y));return mix(x,z,opacity);}",pce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,step(1.0,x+y),opacity);}",mce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.r,xHSL.gb));return vec4(mix(x.rgb,z,opacity),y.a);}",gce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,1.0-y,opacity);}",_ce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y*(1.0-x),opacity);}",vce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,max(x,y),opacity);}",yce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,clamp(y+x-1.0,0.0,1.0),opacity);}",xce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,min(x+y,1.0),opacity);}",Sce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,clamp(2.0*y+x-1.0,0.0,1.0),opacity);}",Ece="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.rg,yHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",bce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x*y,opacity);}",Tce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,1.0-abs(1.0-x-y),opacity);}",wce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y,opacity);}",Ace="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(2.0*y*x,1.0-2.0*(1.0-y)*(1.0-x),step(0.5,x));return mix(x,z,opacity);}",Mce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 y2=2.0*y;vec4 z=mix(mix(y2,x,step(0.5*x,y)),max(vec4(0.0),y2-1.0),step(x,(y2-1.0)));return mix(x,z,opacity);}",Cce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(min(x*x/max(1.0-y,1e-12),1.0),y,step(1.0,y));return mix(x,z,opacity);}",Rce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.r,yHSL.g,xHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",kce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x+y-min(x*y,1.0),opacity);}",Nce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 y2=2.0*y;vec4 w=step(0.5,y);vec4 z=mix(x-(1.0-y2)*x*(1.0-x),mix(x+(y2-1.0)*(sqrt(x)-x),x+(y2-1.0)*x*((16.0*x-12.0)*x+3.0),w*(1.0-step(0.25,x))),w);return mix(x,z,opacity);}",Ice="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return y;}",Oce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,max(x+y-1.0,0.0),opacity);}",Lce="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(max(1.0-min((1.0-x)/(2.0*y),1.0),0.0),min(x/(2.0*(1.0-y)),1.0),step(0.5,y));return mix(x,z,opacity);}",Pce=new Map([[en.ADD,rce],[en.ALPHA,ice],[en.AVERAGE,sce],[en.COLOR,oce],[en.COLOR_BURN,ace],[en.COLOR_DODGE,cce],[en.DARKEN,lce],[en.DIFFERENCE,uce],[en.DIVIDE,hce],[en.DST,null],[en.EXCLUSION,fce],[en.HARD_LIGHT,dce],[en.HARD_MIX,pce],[en.HUE,mce],[en.INVERT,gce],[en.INVERT_RGB,_ce],[en.LIGHTEN,vce],[en.LINEAR_BURN,yce],[en.LINEAR_DODGE,xce],[en.LINEAR_LIGHT,Sce],[en.LUMINOSITY,Ece],[en.MULTIPLY,bce],[en.NEGATION,Tce],[en.NORMAL,wce],[en.OVERLAY,Ace],[en.PIN_LIGHT,Mce],[en.REFLECT,Cce],[en.SATURATION,Rce],[en.SCREEN,kce],[en.SOFT_LIGHT,Nce],[en.SRC,Ice],[en.SUBTRACT,Oce],[en.VIVID_LIGHT,Lce]]),Dce=class extends Xc{constructor(n,e=1){super(),this._blendFunction=n,this.opacity=new kn(e)}getOpacity(){return this.opacity.value}setOpacity(n){this.opacity.value=n}get blendFunction(){return this._blendFunction}set blendFunction(n){this._blendFunction=n,this.dispatchEvent({type:"change"})}getBlendFunction(){return this.blendFunction}setBlendFunction(n){this.blendFunction=n}getShaderCode(){return Pce.get(this.blendFunction)}},Bb=class extends Xc{constructor(n,e,{attributes:t=La.NONE,blendFunction:r=en.NORMAL,defines:i=new Map,uniforms:s=new Map,extensions:o=null,vertexShader:a=null}={}){super(),this.name=n,this.renderer=null,this.attributes=t,this.fragmentShader=e,this.vertexShader=a,this.defines=i,this.uniforms=s,this.extensions=o,this.blendMode=new Dce(r),this.blendMode.addEventListener("change",c=>this.setChanged()),this._inputColorSpace=Ql,this._outputColorSpace=ba}get inputColorSpace(){return this._inputColorSpace}set inputColorSpace(n){this._inputColorSpace=n,this.setChanged()}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(n){this._outputColorSpace=n,this.setChanged()}set mainScene(n){}set mainCamera(n){}getName(){return this.name}setRenderer(n){this.renderer=n}getDefines(){return this.defines}getUniforms(){return this.uniforms}getExtensions(){return this.extensions}getBlendMode(){return this.blendMode}getAttributes(){return this.attributes}setAttributes(n){this.attributes=n,this.setChanged()}getFragmentShader(){return this.fragmentShader}setFragmentShader(n){this.fragmentShader=n,this.setChanged()}getVertexShader(){return this.vertexShader}setVertexShader(n){this.vertexShader=n,this.setChanged()}setChanged(){this.dispatchEvent({type:"change"})}setDepthTexture(n,e=dh){}update(n,e,t){}setSize(n,e){}initialize(n,e,t){}dispose(){for(const n of Object.keys(this)){const e=this[n];(e instanceof Gs||e instanceof Kc||e instanceof ur||e instanceof Yo)&&this[n].dispose()}}},j0={RED:0,GREEN:1,BLUE:2,ALPHA:3},N3=class extends Yo{constructor(n,e,t=null){super("RenderPass",n,e),this.needsSwap=!1,this.clearPass=new k3,this.overrideMaterialManager=t===null?null:new ON(t),this.ignoreBackground=!1,this.skipShadowMapUpdate=!1,this.selection=null}set mainScene(n){this.scene=n}set mainCamera(n){this.camera=n}get renderToScreen(){return super.renderToScreen}set renderToScreen(n){super.renderToScreen=n,this.clearPass.renderToScreen=n}get overrideMaterial(){const n=this.overrideMaterialManager;return n!==null?n.material:null}set overrideMaterial(n){const e=this.overrideMaterialManager;n!==null?e!==null?e.setMaterial(n):this.overrideMaterialManager=new ON(n):e!==null&&(e.dispose(),this.overrideMaterialManager=null)}getOverrideMaterial(){return this.overrideMaterial}setOverrideMaterial(n){this.overrideMaterial=n}get clear(){return this.clearPass.enabled}set clear(n){this.clearPass.enabled=n}getSelection(){return this.selection}setSelection(n){this.selection=n}isBackgroundDisabled(){return this.ignoreBackground}setBackgroundDisabled(n){this.ignoreBackground=n}isShadowMapDisabled(){return this.skipShadowMapUpdate}setShadowMapDisabled(n){this.skipShadowMapUpdate=n}getClearPass(){return this.clearPass}render(n,e,t,r,i){const s=this.scene,o=this.camera,a=this.selection,c=o.layers.mask,l=s.background,u=n.shadowMap.autoUpdate,h=this.renderToScreen?null:e;a!==null&&o.layers.set(a.getLayer()),this.skipShadowMapUpdate&&(n.shadowMap.autoUpdate=!1),(this.ignoreBackground||this.clearPass.overrideClearColor!==null)&&(s.background=null),this.clearPass.enabled&&this.clearPass.render(n,e),n.setRenderTarget(h),this.overrideMaterialManager!==null?this.overrideMaterialManager.render(n,s,o):n.render(s,o),o.layers.mask=c,s.background=l,n.shadowMap.autoUpdate=u}},Uce=`#include +#ifdef GL_FRAGMENT_PRECISION_HIGH +uniform highp sampler2D depthBuffer; +#else +uniform mediump sampler2D depthBuffer; +#endif +#ifdef DOWNSAMPLE_NORMALS +uniform lowp sampler2D normalBuffer; +#endif +varying vec2 vUv0;varying vec2 vUv1;varying vec2 vUv2;varying vec2 vUv3;float readDepth(const in vec2 uv){ +#if DEPTH_PACKING == 3201 +return unpackRGBAToDepth(texture2D(depthBuffer,uv)); +#else +return texture2D(depthBuffer,uv).r; +#endif +}int findBestDepth(const in float samples[4]){float c=(samples[0]+samples[1]+samples[2]+samples[3])*0.25;float distances[4];distances[0]=abs(c-samples[0]);distances[1]=abs(c-samples[1]);distances[2]=abs(c-samples[2]);distances[3]=abs(c-samples[3]);float maxDistance=max(max(distances[0],distances[1]),max(distances[2],distances[3]));int remaining[3];int rejected[3];int i,j,k;for(i=0,j=0,k=0;i<4;++i){if(distances[i]this.setSize(a.baseWidth,a.baseHeight))}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}setDepthTexture(n,e=dh){this.fullscreenMaterial.depthBuffer=n,this.fullscreenMaterial.depthPacking=e}render(n,e,t,r,i){n.setRenderTarget(this.renderToScreen?null:this.renderTarget),n.render(this.scene,this.camera)}setSize(n,e){const t=this.resolution;t.setBaseSize(n,e),this.renderTarget.setSize(t.width,t.height),this.fullscreenMaterial.setSize(n,e)}initialize(n,e,t){const r=n.getContext();if(!(r.getExtension("EXT_color_buffer_float")||r.getExtension("EXT_color_buffer_half_float")))throw new Error("Rendering to float texture is not supported.")}},Vce=`#include +#include +#include +#define packFloatToRGBA(v) packDepthToRGBA(v) +#define unpackRGBAToFloat(v) unpackRGBAToDepth(v) +#ifdef FRAMEBUFFER_PRECISION_HIGH +uniform mediump sampler2D inputBuffer; +#else +uniform lowp sampler2D inputBuffer; +#endif +#if DEPTH_PACKING == 3201 +uniform lowp sampler2D depthBuffer; +#elif defined(GL_FRAGMENT_PRECISION_HIGH) +uniform highp sampler2D depthBuffer; +#else +uniform mediump sampler2D depthBuffer; +#endif +uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;vec4 sRGBToLinear(const in vec4 value){return vec4(mix(pow(value.rgb*0.9478672986+vec3(0.0521327014),vec3(2.4)),value.rgb*0.0773993808,vec3(lessThanEqual(value.rgb,vec3(0.04045)))),value.a);}float readDepth(const in vec2 uv){ +#if DEPTH_PACKING == 3201 +return unpackRGBAToDepth(texture2D(depthBuffer,uv)); +#else +return texture2D(depthBuffer,uv).r; +#endif +}float getViewZ(const in float depth){ +#ifdef PERSPECTIVE_CAMERA +return perspectiveDepthToViewZ(depth,cameraNear,cameraFar); +#else +return orthographicDepthToViewZ(depth,cameraNear,cameraFar); +#endif +}vec3 RGBToHCV(const in vec3 RGB){vec4 P=mix(vec4(RGB.bg,-1.0,2.0/3.0),vec4(RGB.gb,0.0,-1.0/3.0),step(RGB.b,RGB.g));vec4 Q=mix(vec4(P.xyw,RGB.r),vec4(RGB.r,P.yzx),step(P.x,RGB.r));float C=Q.x-min(Q.w,Q.y);float H=abs((Q.w-Q.y)/(6.0*C+EPSILON)+Q.z);return vec3(H,C,Q.x);}vec3 RGBToHSL(const in vec3 RGB){vec3 HCV=RGBToHCV(RGB);float L=HCV.z-HCV.y*0.5;float S=HCV.y/(1.0-abs(L*2.0-1.0)+EPSILON);return vec3(HCV.x,S,L);}vec3 HueToRGB(const in float H){float R=abs(H*6.0-3.0)-1.0;float G=2.0-abs(H*6.0-2.0);float B=2.0-abs(H*6.0-4.0);return clamp(vec3(R,G,B),0.0,1.0);}vec3 HSLToRGB(const in vec3 HSL){vec3 RGB=HueToRGB(HSL.x);float C=(1.0-abs(2.0*HSL.z-1.0))*HSL.y;return(RGB-0.5)*C+HSL.z;}FRAGMENT_HEAD void main(){FRAGMENT_MAIN_UV vec4 color0=texture2D(inputBuffer,UV);vec4 color1=vec4(0.0);FRAGMENT_MAIN_IMAGE color0.a=clamp(color0.a,0.0,1.0);gl_FragColor=color0; +#ifdef ENCODE_OUTPUT +#include +#endif +#include +}`,Hce="uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;VERTEX_HEAD void main(){vUv=position.xy*0.5+0.5;VERTEX_MAIN_SUPPORT gl_Position=vec4(position.xy,1.0,1.0);}",Gce=class extends qi{constructor(n,e,t,r,i=!1){super({name:"EffectMaterial",defines:{THREE_REVISION:Xv.replace(/\D+/g,""),DEPTH_PACKING:"0",ENCODE_OUTPUT:"1"},uniforms:{inputBuffer:new kn(null),depthBuffer:new kn(null),resolution:new kn(new Et),texelSize:new kn(new Et),cameraNear:new kn(.3),cameraFar:new kn(1e3),aspect:new kn(1),time:new kn(0)},blending:Po,toneMapped:!1,depthWrite:!1,depthTest:!1,dithering:i}),n&&this.setShaderParts(n),e&&this.setDefines(e),t&&this.setUniforms(t),this.copyCameraSettings(r)}set inputBuffer(n){this.uniforms.inputBuffer.value=n}setInputBuffer(n){this.uniforms.inputBuffer.value=n}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(n){this.uniforms.depthBuffer.value=n}get depthPacking(){return Number(this.defines.DEPTH_PACKING)}set depthPacking(n){this.defines.DEPTH_PACKING=n.toFixed(0),this.needsUpdate=!0}setDepthBuffer(n,e=dh){this.depthBuffer=n,this.depthPacking=e}setShaderData(n){this.setShaderParts(n.shaderParts),this.setDefines(n.defines),this.setUniforms(n.uniforms),this.setExtensions(n.extensions)}setShaderParts(n){return this.fragmentShader=Vce.replace(yn.FRAGMENT_HEAD,n.get(yn.FRAGMENT_HEAD)||"").replace(yn.FRAGMENT_MAIN_UV,n.get(yn.FRAGMENT_MAIN_UV)||"").replace(yn.FRAGMENT_MAIN_IMAGE,n.get(yn.FRAGMENT_MAIN_IMAGE)||""),this.vertexShader=Hce.replace(yn.VERTEX_HEAD,n.get(yn.VERTEX_HEAD)||"").replace(yn.VERTEX_MAIN_SUPPORT,n.get(yn.VERTEX_MAIN_SUPPORT)||""),this.needsUpdate=!0,this}setDefines(n){for(const e of n.entries())this.defines[e[0]]=e[1];return this.needsUpdate=!0,this}setUniforms(n){for(const e of n.entries())this.uniforms[e[0]]=e[1];return this}setExtensions(n){this.extensions={};for(const e of n)this.extensions[e]=!0;return this}get encodeOutput(){return this.defines.ENCODE_OUTPUT!==void 0}set encodeOutput(n){this.encodeOutput!==n&&(n?this.defines.ENCODE_OUTPUT="1":delete this.defines.ENCODE_OUTPUT,this.needsUpdate=!0)}isOutputEncodingEnabled(n){return this.encodeOutput}setOutputEncodingEnabled(n){this.encodeOutput=n}get time(){return this.uniforms.time.value}set time(n){this.uniforms.time.value=n}setDeltaTime(n){this.uniforms.time.value+=n}adoptCameraSettings(n){this.copyCameraSettings(n)}copyCameraSettings(n){n&&(this.uniforms.cameraNear.value=n.near,this.uniforms.cameraFar.value=n.far,n instanceof Ls?this.defines.PERSPECTIVE_CAMERA="1":delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0)}setSize(n,e){const t=this.uniforms;t.resolution.value.set(n,e),t.texelSize.value.set(1/n,1/e),t.aspect.value=n/e}static get Section(){return yn}};function LN(n,e,t){for(const r of e){const i="$1"+n+r.charAt(0).toUpperCase()+r.slice(1),s=new RegExp("([^\\.])(\\b"+r+"\\b)","g");for(const o of t.entries())o[1]!==null&&t.set(o[0],o[1].replace(s,i))}}function Wce(n,e,t){let r=e.getFragmentShader(),i=e.getVertexShader();const s=r!==void 0&&/mainImage/.test(r),o=r!==void 0&&/mainUv/.test(r);if(t.attributes|=e.getAttributes(),r===void 0)throw new Error(`Missing fragment shader (${e.name})`);if(o&&t.attributes&La.CONVOLUTION)throw new Error(`Effects that transform UVs are incompatible with convolution effects (${e.name})`);if(!s&&!o)throw new Error(`Could not find mainImage or mainUv function (${e.name})`);{const a=/\w+\s+(\w+)\([\w\s,]*\)\s*{/g,c=t.shaderParts;let l=c.get(yn.FRAGMENT_HEAD)||"",u=c.get(yn.FRAGMENT_MAIN_UV)||"",h=c.get(yn.FRAGMENT_MAIN_IMAGE)||"",d=c.get(yn.VERTEX_HEAD)||"",m=c.get(yn.VERTEX_MAIN_SUPPORT)||"";const g=new Set,v=new Set;if(o&&(u+=` ${n}MainUv(UV); +`,t.uvTransformation=!0),i!==null&&/mainSupport/.test(i)){const S=/mainSupport *\([\w\s]*?uv\s*?\)/.test(i);m+=` ${n}MainSupport(`,m+=S?`vUv); +`:`); +`;for(const E of i.matchAll(/(?:varying\s+\w+\s+([\S\s]*?);)/g))for(const T of E[1].split(/\s*,\s*/))t.varyings.add(T),g.add(T),v.add(T);for(const E of i.matchAll(a))v.add(E[1])}for(const S of r.matchAll(a))v.add(S[1]);for(const S of e.defines.keys())v.add(S.replace(/\([\w\s,]*\)/g,""));for(const S of e.uniforms.keys())v.add(S);v.delete("while"),v.delete("for"),v.delete("if"),e.uniforms.forEach((S,E)=>t.uniforms.set(n+E.charAt(0).toUpperCase()+E.slice(1),S)),e.defines.forEach((S,E)=>t.defines.set(n+E.charAt(0).toUpperCase()+E.slice(1),S));const y=new Map([["fragment",r],["vertex",i]]);LN(n,v,t.defines),LN(n,v,y),r=y.get("fragment"),i=y.get("vertex");const _=e.blendMode;if(t.blendModes.set(_.blendFunction,_),s){e.inputColorSpace!==null&&e.inputColorSpace!==t.colorSpace&&(h+=e.inputColorSpace===vr?`color0 = sRGBTransferOETF(color0); + `:`color0 = sRGBToLinear(color0); + `),e.outputColorSpace!==ba?t.colorSpace=e.outputColorSpace:e.inputColorSpace!==null&&(t.colorSpace=e.inputColorSpace);const S=/MainImage *\([\w\s,]*?depth[\w\s,]*?\)/;h+=`${n}MainImage(color0, UV, `,t.attributes&La.DEPTH&&S.test(r)&&(h+="depth, ",t.readDepth=!0),h+=`color1); + `;const E=n+"BlendOpacity";t.uniforms.set(E,_.opacity),h+=`color0 = blend${_.blendFunction}(color0, color1, ${E}); + + `,l+=`uniform float ${E}; + +`}if(l+=r+` +`,i!==null&&(d+=i+` +`),c.set(yn.FRAGMENT_HEAD,l),c.set(yn.FRAGMENT_MAIN_UV,u),c.set(yn.FRAGMENT_MAIN_IMAGE,h),c.set(yn.VERTEX_HEAD,d),c.set(yn.VERTEX_MAIN_SUPPORT,m),e.extensions!==null)for(const S of e.extensions)t.extensions.add(S)}}var jce=class extends Yo{constructor(n,...e){super("EffectPass"),this.fullscreenMaterial=new Gce(null,null,null,n),this.listener=t=>this.handleEvent(t),this.effects=[],this.setEffects(e),this.skipRendering=!1,this.minTime=1,this.maxTime=Number.POSITIVE_INFINITY,this.timeScale=1}set mainScene(n){for(const e of this.effects)e.mainScene=n}set mainCamera(n){this.fullscreenMaterial.copyCameraSettings(n);for(const e of this.effects)e.mainCamera=n}get encodeOutput(){return this.fullscreenMaterial.encodeOutput}set encodeOutput(n){this.fullscreenMaterial.encodeOutput=n}get dithering(){return this.fullscreenMaterial.dithering}set dithering(n){const e=this.fullscreenMaterial;e.dithering=n,e.needsUpdate=!0}setEffects(n){for(const e of this.effects)e.removeEventListener("change",this.listener);this.effects=n.sort((e,t)=>t.attributes-e.attributes);for(const e of this.effects)e.addEventListener("change",this.listener)}updateMaterial(){const n=new nce;let e=0;for(const o of this.effects)if(o.blendMode.blendFunction===en.DST)n.attributes|=o.getAttributes()&La.DEPTH;else{if(n.attributes&o.getAttributes()&La.CONVOLUTION)throw new Error(`Convolution effects cannot be merged (${o.name})`);Wce("e"+e++,o,n)}let t=n.shaderParts.get(yn.FRAGMENT_HEAD),r=n.shaderParts.get(yn.FRAGMENT_MAIN_IMAGE),i=n.shaderParts.get(yn.FRAGMENT_MAIN_UV);const s=/\bblend\b/g;for(const o of n.blendModes.values())t+=o.getShaderCode().replace(s,`blend${o.blendFunction}`)+` +`;n.attributes&La.DEPTH?(n.readDepth&&(r=`float depth = readDepth(UV); + + `+r),this.needsDepthTexture=this.getDepthTexture()===null):this.needsDepthTexture=!1,n.colorSpace===vr&&(r+=`color0 = sRGBToLinear(color0); + `),n.uvTransformation?(i=`vec2 transformedUv = vUv; +`+i,n.defines.set("UV","transformedUv")):n.defines.set("UV","vUv"),n.shaderParts.set(yn.FRAGMENT_HEAD,t),n.shaderParts.set(yn.FRAGMENT_MAIN_IMAGE,r),n.shaderParts.set(yn.FRAGMENT_MAIN_UV,i);for(const[o,a]of n.shaderParts)a!==null&&n.shaderParts.set(o,a.trim().replace(/^#/,` +#`));this.skipRendering=e===0,this.needsSwap=!this.skipRendering,this.fullscreenMaterial.setShaderData(n)}recompile(){this.updateMaterial()}getDepthTexture(){return this.fullscreenMaterial.depthBuffer}setDepthTexture(n,e=dh){this.fullscreenMaterial.depthBuffer=n,this.fullscreenMaterial.depthPacking=e;for(const t of this.effects)t.setDepthTexture(n,e)}render(n,e,t,r,i){for(const s of this.effects)s.update(n,e,r);if(!this.skipRendering||this.renderToScreen){const s=this.fullscreenMaterial;s.inputBuffer=e.texture,s.time+=r*this.timeScale,n.setRenderTarget(this.renderToScreen?null:t),n.render(this.scene,this.camera)}}setSize(n,e){this.fullscreenMaterial.setSize(n,e);for(const t of this.effects)t.setSize(n,e)}initialize(n,e,t){this.renderer=n;for(const r of this.effects)r.initialize(n,e,t);this.updateMaterial(),t!==void 0&&t!==Mi&&(this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1")}dispose(){super.dispose();for(const n of this.effects)n.removeEventListener("change",this.listener),n.dispose()}handleEvent(n){switch(n.type){case"change":this.recompile();break}}},$ce=class extends Yo{constructor(n,e,{renderTarget:t,resolutionScale:r=1,width:i=zf.AUTO_SIZE,height:s=zf.AUTO_SIZE,resolutionX:o=i,resolutionY:a=s}={}){super("NormalPass"),this.needsSwap=!1,this.renderPass=new N3(n,e,new rj);const c=this.renderPass;c.ignoreBackground=!0,c.skipShadowMapUpdate=!0;const l=c.getClearPass();l.overrideClearColor=new hn(7829503),l.overrideClearAlpha=1,this.renderTarget=t,this.renderTarget===void 0&&(this.renderTarget=new Gs(1,1,{minFilter:Er,magFilter:Er}),this.renderTarget.texture.name="NormalPass.Target");const u=this.resolution=new zf(this,o,a,r);u.addEventListener("change",h=>this.setSize(u.baseWidth,u.baseHeight))}set mainScene(n){this.renderPass.mainScene=n}set mainCamera(n){this.renderPass.mainCamera=n}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}getResolutionScale(){return this.resolution.scale}setResolutionScale(n){this.resolution.scale=n}render(n,e,t,r,i){const s=this.renderToScreen?null:this.renderTarget;this.renderPass.render(n,s,s)}setSize(n,e){const t=this.resolution;t.setBaseSize(n,e),this.renderTarget.setSize(t.width,t.height)}};let sp;function qce(){var n;if(sp!==void 0)return sp;try{let e;const t=document.createElement("canvas");return sp=!!(window.WebGL2RenderingContext&&(e=t.getContext("webgl2"))),e&&((n=e.getExtension("WEBGL_lose_context"))==null||n.loseContext()),sp}catch{return sp=!1}}const Xce=ke.createContext(null),PN=n=>(n.getAttributes()&La.CONVOLUTION)===La.CONVOLUTION,Kce=Lo.memo(ke.forwardRef(({children:n,camera:e,scene:t,resolutionScale:r,enabled:i=!0,renderPriority:s=1,autoClear:o=!0,depthBuffer:a,enableNormalPass:c,stencilBuffer:l,multisampling:u=8,frameBufferType:h=vd},d)=>{const{gl:m,scene:g,camera:v,size:y}=Ma(),_=t||g,S=e||v,[E,T,k]=ke.useMemo(()=>{const C=qce(),I=new tce(m,{depthBuffer:a,stencilBuffer:l,multisampling:u>0&&C?u:0,frameBufferType:h});I.addPass(new N3(_,S));let U=null,L=null;return c&&(L=new $ce(_,S),L.enabled=!1,I.addPass(L),r!==void 0&&C&&(U=new zce({normalBuffer:L.texture,resolutionScale:r}),U.enabled=!1,I.addPass(U))),[I,L,U]},[S,m,a,l,u,h,_,c,r]);ke.useEffect(()=>E==null?void 0:E.setSize(y.width,y.height),[E,y]),ry((C,I)=>{if(i){const U=m.autoClear;m.autoClear=o,l&&!o&&m.clearStencil(),E.render(I),m.autoClear=U}},i?s:0);const R=ke.useRef(null),M=Dj(R);ke.useLayoutEffect(()=>{const C=[];if(R.current&&M.current&&E){const I=M.current.objects;for(let U=0;U{for(const I of C)E==null||E.removePass(I);T&&(T.enabled=!1),k&&(k.enabled=!1)}},[E,n,S,T,k,M]),ke.useEffect(()=>{const C=m.toneMapping;return m.toneMapping=Ra,()=>{m.toneMapping=C}},[]);const O=ke.useMemo(()=>({composer:E,normalPass:T,downSamplingPass:k,resolutionScale:r,camera:S,scene:_}),[E,T,k,r,S,_]);return ke.useImperativeHandle(d,()=>E,[E]),ve.jsx(Xce.Provider,{value:O,children:ve.jsx("group",{ref:R,children:n})})}));let Yce=0;const DN=new WeakMap,Zce=(n,e)=>Lo.forwardRef(function({blendFunction:r=void 0,opacity:i=void 0,...s},o){let a=DN.get(n);if(!a){const u=`@react-three/postprocessing/${n.name}-${Yce++}`;JT({[u]:n}),DN.set(n,a=u)}const c=Ma(u=>u.camera),l=Lo.useMemo(()=>{var u,h;return[...(u=void 0)!=null?u:[],...(h=s.args)!=null?h:[{...e,...s}]]},[JSON.stringify(s)]);return ve.jsx(a,{camera:c,"blendMode-blendFunction":r,"blendMode-opacity-value":i,...s,ref:o,args:l})});function I1(n,e,t,r){return new(t||(t=Promise))(function(i,s){function o(l){try{c(r.next(l))}catch(u){s(u)}}function a(l){try{c(r.throw(l))}catch(u){s(u)}}function c(l){var u;l.done?i(l.value):(u=l.value,u instanceof t?u:new t(function(h){h(u)})).then(o,a)}c((r=r.apply(n,[])).next())})}const Jce=["geforce 320m","geforce 8600","geforce 8600m gt","geforce 8800 gs","geforce 8800 gt","geforce 9400","geforce 9400m g","geforce 9400m","geforce 9600m gt","geforce 9600m","geforce fx go5200","geforce gt 120","geforce gt 130","geforce gt 330m","geforce gtx 285","google swiftshader","intel g41","intel g45","intel gma 4500mhd","intel gma x3100","intel hd 3000","intel q45","legacy","mali-2","mali-3","mali-4","quadro fx 1500","quadro fx 4","quadro fx 5","radeon hd 2400","radeon hd 2600","radeon hd 4670","radeon hd 4850","radeon hd 4870","radeon hd 5670","radeon hd 5750","radeon hd 6290","radeon hd 6300","radeon hd 6310","radeon hd 6320","radeon hd 6490m","radeon hd 6630m","radeon hd 6750m","radeon hd 6770m","radeon hd 6970m","sgx 543","sgx543"];function UN(n){return n=n.toLowerCase().replace(/.*angle ?\((.+)\)(?: on vulkan [0-9.]+)?$/i,"$1").replace(/\s(\d{1,2}gb|direct3d.+$)|\(r\)| \([^)]+\)$/g,"").replace(/(?:vulkan|opengl) \d+\.\d+(?:\.\d+)?(?: \((.*)\))?/,"$1")}const I3=typeof window>"u",va=(()=>{if(I3)return;const{userAgent:n,platform:e,maxTouchPoints:t}=window.navigator,r=/(iphone|ipod|ipad)/i.test(n),i=e==="iPad"||e==="MacIntel"&&t>0&&!window.MSStream;return{isIpad:i,isMobile:/android/i.test(n)||r||i,isSafari12:/Version\/12.+Safari/.test(n),isFirefox:/Firefox/.test(n)}})();function Qce(n,e,t){if(!t)return[e];const r=function(l){const u=` + precision highp float; + attribute vec3 aPosition; + varying float vvv; + void main() { + vvv = 0.31622776601683794; + gl_Position = vec4(aPosition, 1.0); + } + `,h=` + precision highp float; + varying float vvv; + void main() { + vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * vvv; + enc = fract(enc); + enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0); + gl_FragColor = enc; + } + `,d=l.createShader(35633),m=l.createShader(35632),g=l.createProgram();if(!(m&&d&&g))return;l.shaderSource(d,u),l.shaderSource(m,h),l.compileShader(d),l.compileShader(m),l.attachShader(g,d),l.attachShader(g,m),l.linkProgram(g),l.detachShader(g,d),l.detachShader(g,m),l.deleteShader(d),l.deleteShader(m),l.useProgram(g);const v=l.createBuffer();l.bindBuffer(34962,v),l.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const y=l.getAttribLocation(g,"aPosition");l.vertexAttribPointer(y,3,5126,!1,0,0),l.enableVertexAttribArray(y),l.clearColor(1,1,1,1),l.clear(16384),l.viewport(0,0,1,1),l.drawArrays(4,0,3);const _=new Uint8Array(4);return l.readPixels(0,0,1,1,6408,5121,_),l.deleteProgram(g),l.deleteBuffer(v),_.join("")}(n),i="801621810",s="8016218135",o="80162181161",a=va!=null&&va.isIpad?[["a7",o,12],["a8",s,15],["a8x",s,15],["a9",s,15],["a9x",s,15],["a10",s,15],["a10x",s,15],["a12",i,15],["a12x",i,15],["a12z",i,15],["a14",i,15],["a15",i,15],["m1",i,15],["m2",i,15]]:[["a7",o,12],["a8",s,12],["a9",s,15],["a10",s,15],["a11",i,15],["a12",i,15],["a13",i,15],["a14",i,15],["a15",i,15],["a16",i,15],["a17",i,15]];let c;return r==="80162181255"?c=a.filter(([,,l])=>l>=14):(c=a.filter(([,l])=>l===r),c.length||(c=a)),c.map(([l])=>`apple ${l} gpu`)}class FN extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const O1=[],BN=[];function ele(n,e){if(n===e)return 0;const t=n;n.length>e.length&&(n=e,e=t);let r=n.length,i=e.length;for(;r>0&&n.charCodeAt(~-r)===e.charCodeAt(~-i);)r--,i--;let s,o=0;for(;ol?c>l?l+1:c:c>a?a+1:c;return l}function tle(n){return n!=null}const nle=({mobileTiers:n=[0,15,30,60],desktopTiers:e=[0,15,30,60],override:t={},glContext:r,failIfMajorPerformanceCaveat:i=!1,benchmarksURL:s="https://unpkg.com/detect-gpu@5.0.56/dist/benchmarks"}={})=>I1(void 0,void 0,void 0,function*(){const o={};if(I3)return{tier:0,type:"SSR"};const{isIpad:a=!!(va!=null&&va.isIpad),isMobile:c=!!(va!=null&&va.isMobile),screenSize:l=window.screen,loadBenchmarks:u=k=>I1(void 0,void 0,void 0,function*(){const R=yield fetch(`${s}/${k}`).then(M=>M.json());if(parseInt(R.shift().split(".")[0],10)<4)throw new FN("Detect GPU benchmark data is out of date. Please update to version 4x");return R})}=t;let{renderer:h}=t;const d=(k,R,M,O,C)=>({device:C,fps:O,gpu:M,isMobile:c,tier:k,type:R});let m,g="";if(h)h=UN(h),m=[h];else{const k=r||function(M,O=!1){const C={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:O,powerPreference:"high-performance",stencil:!1};M&&delete C.powerPreference;const I=window.document.createElement("canvas"),U=I.getContext("webgl",C)||I.getContext("experimental-webgl",C);return U??void 0}(va==null?void 0:va.isSafari12,i);if(!k)return d(0,"WEBGL_UNSUPPORTED");const R=va!=null&&va.isFirefox?null:k.getExtension("WEBGL_debug_renderer_info");if(h=R?k.getParameter(R.UNMASKED_RENDERER_WEBGL):k.getParameter(k.RENDERER),!h)return d(1,"FALLBACK");g=h,h=UN(h),m=function(M,O,C){return O==="apple gpu"?Qce(M,O,C):[O]}(k,h,c)}const v=(yield Promise.all(m.map(function(k){var R;return I1(this,void 0,void 0,function*(){const M=(ge=>{const Q=c?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const re of Q)if(ge.includes(re))return re})(k);if(!M)return;const O=`${c?"m":"d"}-${M}${a?"-ipad":""}.json`,C=o[O]=(R=o[O])!==null&&R!==void 0?R:u(O);let I;try{I=yield C}catch(ge){if(ge instanceof FN)throw ge;return}const U=function(ge){var Q;const re=(ge=ge.replace(/\([^)]+\)/,"")).match(/\d+/)||ge.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(Q=re==null?void 0:re.join("").replace(/\W|amd/g,""))!==null&&Q!==void 0?Q:""}(k);let L=I.filter(([,ge])=>ge===U);L.length||(L=I.filter(([ge])=>ge.includes(k)));const P=L.length;if(P===0)return;const w=k.split(/[.,()\[\]/\s]/g).sort().filter((ge,Q,re)=>Q===0||ge!==re[Q-1]).join(" ");let H,[V,,,,B]=P>1?L.map(ge=>[ge,ele(w,ge[2])]).sort(([,ge],[,Q])=>ge-Q)[0][0]:L[0],z=Number.MAX_VALUE;const{devicePixelRatio:W}=window,K=l.width*W*l.height*W;for(const ge of B){const[Q,re]=ge,be=Q*re,Ae=Math.abs(K-be);Aek===M?R-O:k-M);if(!v.length){const k=Jce.find(R=>h.includes(R));return k?d(0,"BLOCKLISTED",k):d(1,"FALLBACK",`${h} (${g})`)}const[,y,_,S]=v[0];if(y===-1)return d(0,"BLOCKLISTED",_,y,S);const E=c?n:e;let T=0;for(let k=0;k=E[k]&&(T=k);return d(T,"BENCHMARK",_,y,S)});var O3={exports:{}};(function(n,e){(function(t,r){n.exports=r()})(No,function(){var t=function(){function r(m){return o.appendChild(m.dom),m}function i(m){for(var g=0;gc+1e3&&(u.update(1e3*l/(m-c),100),c=m,l=0,d)){var g=performance.memory;d.update(g.usedJSHeapSize/1048576,g.jsHeapSizeLimit/1048576)}return m},update:function(){a=this.end()},domElement:o,setMode:i}};return t.Panel=function(r,i,s){var o=1/0,a=0,c=Math.round,l=c(window.devicePixelRatio||1),u=80*l,h=48*l,d=3*l,m=2*l,g=3*l,v=15*l,y=74*l,_=30*l,S=document.createElement("canvas");S.width=u,S.height=h,S.style.cssText="width:80px;height:48px";var E=S.getContext("2d");return E.font="bold "+9*l+"px Helvetica,Arial,sans-serif",E.textBaseline="top",E.fillStyle=s,E.fillRect(0,0,u,h),E.fillStyle=i,E.fillText(r,d,m),E.fillRect(g,v,y,_),E.fillStyle=s,E.globalAlpha=.9,E.fillRect(g,v,y,_),{dom:S,update:function(T,k){o=Math.min(o,T),a=Math.max(a,T),E.fillStyle=s,E.globalAlpha=1,E.fillRect(0,0,u,v),E.fillStyle=i,E.fillText(c(T)+" "+r+" ("+c(o)+"-"+c(a)+")",d,m),E.drawImage(S,g+l,v,y-l,_,g,v,y-l,_),E.fillRect(g+y-l,v,l,_),E.fillStyle=s,E.globalAlpha=.9,E.fillRect(g+y-l,v,l,c((1-T/k)*_))}}},t})})(O3);var rle=O3.exports;const ile=$a(rle),ja=!!JSON.parse("false"),sle=!!JSON.parse("false"),ole=!!JSON.parse("false"),ale=!!JSON.parse("false");JSON.parse("false");const cle=!!JSON.parse("false"),lle=` +vec3 halftone(vec3 texcolor, vec2 st, float frequency) { + float n = 0.1 * snoise(st * 200.0); // Fractal noise + n += 0.05 * snoise(st * 400.0); + n += 0.025 * snoise(st * 800.0); + + // Perform a rough RGB-to-CMYK conversion + vec4 cmyk; + // CMY = 1-RGB + cmyk.xyz = 1.0 - texcolor; + // Black generation: K = min(C,M,Y) + cmyk.w = min(cmyk.x, min(cmyk.y, cmyk.z)); + // Grey component replacement: subtract K from CMY + cmyk.xyz -= cmyk.w; + + // K based modifier + float flex = pow(cmyk.w, 3.11); + + // Distance to nearest point in a grid of + // (frequency x frequency) points over the unit square + + float t = 0.1 + 0.1 * n + 0.11 * flex + 0.1 * cmyk.y; + + // K component: 45 degrees screen angle + vec2 Kst = frequency * mat2(0.707, -0.707, 0.707, 0.707) * st; + vec2 Kuv = 2.0 * fract(Kst) - 1.0; + float k = aastep(0.0, sqrt(cmyk.w) + t - length(Kuv) + n); + + // C component: 15 degrees screen angle + vec2 Cst = frequency*mat2(0.966, -0.259, 0.259, 0.966) * st; + vec2 Cuv = 2.0 * fract(Cst) - 1.0; + float c = aastep(0.0, sqrt(cmyk.x) + t - length(Cuv) + n); + + // M component: -15 degrees screen angle + vec2 Mst = frequency * mat2(0.966, 0.259, -0.259, 0.966) * st; + vec2 Muv = 2.0 * fract(Mst) - 1.0; + float m = aastep(0.0, sqrt(cmyk.y) + t - length(Muv) + n); + + // Y component: 0 degrees screen angle + vec2 Yst = frequency * st; // 0 deg + vec2 Yuv = 2.0 * fract(Yst) - 1.0; + float y = aastep(0.0, sqrt(cmyk.z) + t - length(Yuv) + n); + + // CMY screen in RGB + vec3 black = vec3(n + 0.01); + vec3 rgbscreen = 1.0 - vec3(c,m,y) + n; + + // Blend in K for final color + vec3 factor = mix(rgbscreen, black, 1.1 * k + 0.3 * n); + + // Blend with og color + return mix(factor, texcolor, 0.777); +} + +vec3 halftone(vec3 texcolor, vec2 st) { + return halftone(texcolor, st, 412.321); +} +`,ule=` +float blendLighten(float base, float blend) { + return max(blend,base); +} + +vec3 blendLighten(vec3 base, vec3 blend) { + return vec3(blendLighten(base.r,blend.r),blendLighten(base.g,blend.g),blendLighten(base.b,blend.b)); +} + +vec3 blendLighten(vec3 base, vec3 blend, float opacity) { + return (blendLighten(base, blend) * opacity + base * (1.0 - opacity)); +} + +float blendDarken(float base, float blend) { + return min(blend,base); +} + +vec3 blendDarken(vec3 base, vec3 blend) { + return vec3(blendDarken(base.r,blend.r),blendDarken(base.g,blend.g),blendDarken(base.b,blend.b)); +} + +vec3 blendDarken(vec3 base, vec3 blend, float opacity) { + return (blendDarken(base, blend) * opacity + base * (1.0 - opacity)); +} +`,hle=` +float aastep(float threshold, float value) { + float afwidth = length(vec2(dFdx(value), dFdy(value))) * 0.70710678118654757; + return smoothstep(threshold-afwidth, threshold+afwidth, value); +} +`,fle=` +// +// Description : Array and textureless GLSL 2D simplex noise function. +// Author : Ian McEwan, Ashima Arts. +// Maintainer : ijm +// Lastmod : 20110822 (ijm) +// License : Copyright (C) 2011 Ashima Arts. All rights reserved. +// Distributed under the MIT License. See LICENSE file. +// https://github.com/ashima/webgl-noise +// + +vec3 mod289(vec3 x) { + return x - floor(x * (1.0 / 289.0)) * 289.0; +} + +vec2 mod289(vec2 x) { + return x - floor(x * (1.0 / 289.0)) * 289.0; +} + +vec3 permute(vec3 x) { + return mod289(((x*34.0)+1.0)*x); +} + +float snoise(vec2 v) { + const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0 + 0.366025403784439, // 0.5*(sqrt(3.0)-1.0) + -0.577350269189626, // -1.0 + 2.0 * C.x + 0.024390243902439); // 1.0 / 41.0 +// First corner + vec2 i = floor(v + dot(v, C.yy) ); + vec2 x0 = v - i + dot(i, C.xx); + +// Other corners + vec2 i1; + //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0 + //i1.y = 1.0 - i1.x; + i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); + // x0 = x0 - 0.0 + 0.0 * C.xx ; + // x1 = x0 - i1 + 1.0 * C.xx ; + // x2 = x0 - 1.0 + 2.0 * C.xx ; + vec4 x12 = x0.xyxy + C.xxzz; + x12.xy -= i1; + +// Permutations + i = mod289(i); // Avoid truncation effects in permutation + vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 )) + + i.x + vec3(0.0, i1.x, 1.0 )); + + vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0); + m = m*m ; + m = m*m ; + +// Gradients: 41 points uniformly over a line, mapped onto a diamond. +// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287) + + vec3 x = 2.0 * fract(p * C.www) - 1.0; + vec3 h = abs(x) - 0.5; + vec3 ox = floor(x + 0.5); + vec3 a0 = x - ox; + +// Normalise gradients implicitly by scaling m +// Approximation of: m *= inversesqrt( a0*a0 + h*h ); + m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ); + +// Compute final noise value at P + vec3 g; + g.x = a0.x * x0.x + h.x * x0.y; + g.yz = a0.yz * x12.xz + h.yz * x12.yw; + return 130.0 * dot(m, g); +} +`,dle=` +#ifdef ASPECT_CORRECTION + uniform float scale; +#else + uniform mat3 uvTransform; +#endif + +varying vec2 vUv2; + +void mainSupport(const in vec2 uv) { + #ifdef ASPECT_CORRECTION + vUv2 = uv * vec2(aspect, 1.0) * scale; + #else + vUv2 = (uvTransform * vec3(uv, 1.0)).xy; + #endif +} +`,ple=` +uniform float viewheight; +uniform sampler2D splat; + +${ule} +${hle} +${fle} +${lle} + +float rectdistance(vec2 uv) { + vec2 tl = vec2(-1.0); + vec2 br = vec2(1.0); + vec2 d = max(tl - uv, uv - br); + return abs(length(max(vec2(0.0), d)) + min(0.0, max(d.x, d.y))); +} + +vec2 bendy(const in vec2 xn, float dn, float sn) { + // config + float distortion = 0.0173 + dn; // 0.0173, 0.511 + float scale = 0.991 + sn; // 1.0, 0.7 + // calc + vec3 xDistorted = vec3((1.0 + vec2(distortion, distortion) * dot(xn, xn)) * xn, 1.0); + mat3 kk = mat3( + vec3(1.0, 0.0, 0.0), + vec3(0.0, 1.0, 0.0), + vec3(0.0, 0.0, 1.0) + ); + return (kk * xDistorted).xy * scale; +} + +void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) { + #ifdef UV_TRANSFORM + vec4 bright = texture2D(splat, vUv2); + vec4 dark = texture2D(splat, 1.0 - vUv2); + #else + vec4 bright = texture2D(splat, uv); + vec4 dark = texture2D(splat, 1.0 - uv); + #endif + + float n = 0.1 * snoise(uv.st * 200.0); // Fractal noise + n += 0.05 * snoise(uv.st * 400.0); + n += 0.025 * snoise(uv.st * 800.0); + + vec2 xn = 2.0 * (uv.st - 0.5); + vec2 edge = bendy(xn, 0.0091 * n, 0.0011 * -n); + vec2 bent = edge.xy * 0.5 + 0.5; + + float dx = rectdistance(xn); + float bx = rectdistance(edge); + + // apply shape + float doot = max(abs(edge.x), abs(edge.y)); + if (doot < 1.0) { + // display + outputColor = texture2D(inputBuffer, bent); + + // apply scratches + outputColor.rgb = blendLighten(outputColor.rgb, bright.rgb, 0.111); + outputColor.rgb = blendDarken(outputColor.rgb, dark.rgb, 0.111); + + // apply halftones + outputColor.rgb = halftone(outputColor.rgb, uv.st); + + } else if (doot > 1.004) { + // display shell + // rbgb 205 205 193 + vec3 matte = vec3(205.0 / 255.0, 205.0 / 255.0, 193.0 / 255.0); + vec3 dkmatte = mix(matte, vec3(0.0), 0.5); + float mx = pow(1.0 - bx, 16.0) + n; + outputColor = vec4(mix(matte, dkmatte, mx), inputColor.a); + + } else { + // border + outputColor = vec4(mix(vec3(0.0), outputColor.rgb, 0.5), inputColor.a); + } + + // apply inner shade + if (doot >= 0.5 && doot < 1.0) { + float sh = clamp(0.0, 1.0, 1.0 - bx - 0.7); + vec3 shade = mix(outputColor.rgb, vec3(0.0), pow(sh, 4.0)); + outputColor = vec4(shade, inputColor.a); + } + + // apply outer shade + if (doot >= 0.97) { + float sh = clamp(0.0, 1.0, bx * 24.0); + vec3 dkout = mix(vec3(0.0), outputColor.rgb, 0.81); + vec3 shade = mix(dkout, outputColor.rgb, sh); + outputColor = vec4(shade, inputColor.a); + } +} +`;class mle extends Bb{constructor({splat:e,viewheight:t}={}){super("CRTShapeEffect",ple,{blendFunction:en.NORMAL,attributes:La.CONVOLUTION,defines:new Map([["TEXEL","texel"],["TEXTURE_PRECISION_HIGH","1"]]),uniforms:new Map([["splat",new kn(e)],["viewheight",new kn(t??128)]])})}get splat(){var e;return(e=this.uniforms.get("splat"))==null?void 0:e.value}set splat(e){const{splat:t,uniforms:r,defines:i}=this,s=r.get("splat"),o=r.get("uvTransform");t!==e&&s&&o&&(s.value=e,o.value=e.matrix,i.delete("TEXTURE_PRECISION_HIGH"),e!==null&&(e.matrixAutoUpdate?(i.set("UV_TRANSFORM","1"),this.setVertexShader(dle)):(i.delete("UV_TRANSFORM"),this.setVertexShader(null)),e.type!==Mi&&i.set("TEXTURE_PRECISION_HIGH","1"),(t===null||(t==null?void 0:t.type)!==e.type)&&this.setChanged()))}getTexture(){return this.splat}setTexture(e){this.splat=e}get aspectCorrection(){return this.defines.has("ASPECT_CORRECTION")}set aspectCorrection(e){this.aspectCorrection!==e&&(e?this.defines.set("ASPECT_CORRECTION","1"):this.defines.delete("ASPECT_CORRECTION"),this.setChanged())}get uvTransform(){const e=this.splat;return!!(e!=null&&e.matrixAutoUpdate)}set uvTransform(e){const t=this.splat;Z(t)&&(t.matrixAutoUpdate=e)}setTextureSwizzleRGBA(e,t=e,r=e,i=e){const s="rgba";let o="";(e!==j0.RED||t!==j0.GREEN||r!==j0.BLUE||i!==j0.ALPHA)&&(o=[".",s[e],s[t],s[r],s[i]].join("")),this.defines.set("TEXEL","texel"+o),this.setChanged()}update(){var e;(e=this.splat)!=null&&e.matrixAutoUpdate&&this.splat.updateMatrix()}}const gle=Zce(mle),_le="/assets/scratches-BBiC0fzb.gif",L1=n=>n===Object(n)&&!Array.isArray(n)&&typeof n!="function";function WA(n,e){const t=Ma(s=>s.gl),r=mm(YT,L1(n)?Object.values(n):n);return ke.useLayoutEffect(()=>{e==null||e(r)},[e,r]),ke.useEffect(()=>{if("initTexture"in t){let s=[];Array.isArray(r)?s=r:r instanceof ur?s=[r]:L1(r)&&(s=Object.values(r)),s.forEach(o=>{o instanceof ur&&t.initTexture(o)})}},[t,r]),ke.useMemo(()=>{if(L1(n)){const s={};let o=0;for(const a in n)s[a]=r[o++];return s}else return r},[n,r])}WA.preload=n=>mm.preload(YT,n);WA.clear=n=>mm.clear(YT,n);const zN=n=>{let e;const t=new Set,r=(l,u)=>{const h=typeof l=="function"?l(e):l;if(!Object.is(h,e)){const d=e;e=u??(typeof h!="object"||h===null)?h:Object.assign({},e,h),t.forEach(m=>m(e,d))}},i=()=>e,a={setState:r,getState:i,getInitialState:()=>c,subscribe:l=>(t.add(l),()=>t.delete(l))},c=e=n(r,i,a);return a},jA=n=>n?zN(n):zN,vle=n=>n;function $A(n,e=vle){const t=Lo.useSyncExternalStore(n.subscribe,()=>e(n.getState()),()=>e(n.getInitialState()));return Lo.useDebugValue(t),t}const VN=n=>{const e=jA(n),t=r=>$A(e,r);return Object.assign(t,e),t},jm=n=>n?VN(n):VN;function yle(n){const e=ke.useRef();return t=>{const r=n(t);return(e.current===void 0||r===void 0?e.current===r:PL(e.current,r))?e.current:e.current=r}}const kc=jm(()=>({desync:!1,gadget:{player:"",layers:[],panels:[],reset:!1,focus:""}}));var N_=(n=>(n[n.OFF=0]="OFF",n[n.INFO=1]="INFO",n[n.DEBUG=2]="DEBUG",n))(N_||{});const HN=128;var Bi=(n=>(n[n.TOP=0]="TOP",n[n.BOTTOM=1]="BOTTOM",n[n.FULL=2]="FULL",n[n.SPLIT_Y=3]="SPLIT_Y",n[n.SPLIT_Y_ALT=4]="SPLIT_Y_ALT",n[n.MAX=5]="MAX",n))(Bi||{});const cs=jm(()=>({layout:1,terminal:{open:!0,level:1,logs:[]},editor:{open:!1,player:"",book:"",page:"",type:"",title:""}})),Cr=jm(()=>({scroll:0,xcursor:0,ycursor:0,xselect:void 0,yselect:void 0,bufferindex:0,buffer:[""]})),mr=jm(()=>({id:"",xscroll:0,yscroll:0,cursor:0,select:void 0})),zb=3,L3=2,Vf=8,Hf=14,ps=Vf*L3,$i=Hf*L3,Nc=16;var _p=(n=>(n[n.BLANK=0]="BLANK",n[n.TILES=1]="TILES",n[n.SPRITES=2]="SPRITES",n[n.DITHER=3]="DITHER",n[n.MEDIA=4]="MEDIA",n[n.CONTROL=5]="CONTROL",n))(_p||{});function xle(n){let e=0,t=0,r=0,i=0,s=1;return n.forEach(o=>{switch(o.type){case 1:e=Math.max(e,o.width),t=Math.max(t,o.height);break;case 3:e=Math.max(e,o.width),t=Math.max(t,o.height);break;case 5:r=o.focusx,i=o.focusy,s=o.viewscale;break}}),{width:e,height:t,focusx:r,focusy:i,viewscale:s}}var Ti=(n=>(n[n.START=0]="START",n[n.LEFT=1]="LEFT",n[n.RIGHT=2]="RIGHT",n[n.TOP=3]="TOP",n[n.BOTTOM=4]="BOTTOM",n[n.SCROLL=5]="SCROLL",n))(Ti||{});const Sle={start:0,left:1,right:2,top:3,bottom:4,scroll:5},Ele={0:1,1:20,2:20,3:1,4:1,5:40};function Rd(n,e){return`${n}:${e}`}const P3=1,D3=16,U3=256;var Ue=(n=>(n[n.NONE=0]="NONE",n[n.ALT=1]="ALT",n[n.CTRL=2]="CTRL",n[n.SHIFT=3]="SHIFT",n[n.MOVE_UP=4]="MOVE_UP",n[n.MOVE_DOWN=5]="MOVE_DOWN",n[n.MOVE_LEFT=6]="MOVE_LEFT",n[n.MOVE_RIGHT=7]="MOVE_RIGHT",n[n.OK_BUTTON=8]="OK_BUTTON",n[n.CANCEL_BUTTON=9]="CANCEL_BUTTON",n[n.MENU_BUTTON=10]="MENU_BUTTON",n[n.SHOOT_UP=11]="SHOOT_UP",n[n.SHOOT_DOWN=12]="SHOOT_DOWN",n[n.SHOOT_LEFT=13]="SHOOT_LEFT",n[n.SHOOT_RIGHT=14]="SHOOT_RIGHT",n))(Ue||{});const ble=new xe,F3=ke.createContext([]);function Qy(){return ke.useContext(F3)}function Tle({width:n=0,height:e=0,children:t,...r}){const i=ke.useRef(null),[s]=ke.useState(()=>{const a=[];return n&&a.push(new Co,new Co),e&&a.push(new Co,new Co),a}),[o]=ke.useState(()=>[new xe(0,0,0),new xe(0,0,0),new xe(0,0,0),new xe(0,0,0),new xe(0,0,0)]);return ry(()=>{if(i.current){const a=i.current.localToWorld(o[0].set(0,0,0)),c=[];if(n){const l=n*.5;c.push(i.current.localToWorld(o[3].set(l,0,0)),i.current.localToWorld(o[4].set(-l,0,0)))}if(e){const l=e*.5;c.push(i.current.localToWorld(o[1].set(0,l,0)),i.current.localToWorld(o[2].set(0,-l,0)))}for(let l=0;lSymbol.iterator in n,WN=n=>"entries"in n,jN=(n,e)=>{const t=n instanceof Map?n:new Map(n.entries()),r=e instanceof Map?e:new Map(e.entries());if(t.size!==r.size)return!1;for(const[i,s]of t)if(!Object.is(s,r.get(i)))return!1;return!0},wle=(n,e)=>{const t=n[Symbol.iterator](),r=e[Symbol.iterator]();let i=t.next(),s=r.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=t.next(),s=r.next()}return!!i.done&&!!s.done};function Ale(n,e){return Object.is(n,e)?!0:typeof n!="object"||n===null||typeof e!="object"||e===null?!1:!GN(n)||!GN(e)?jN({entries:()=>Object.entries(n)},{entries:()=>Object.entries(e)}):WN(n)&&WN(e)?jN(n,e):wle(n,e)}function iu(n){const e=Lo.useRef();return t=>{const r=n(t);return Ale(e.current,r)?e.current:e.current=r}}const Mle=Date.now(),Mo={get value(){return(Date.now()-Mle)/1e3%1e6}},Cle=120;let B3=0;function Rle(n){B3=Cle/n}Rle(150);const qA={get value(){return B3}};function XA(n){const e=n.clone();return e.uniforms.time=Mo,e.uniforms.interval=qA,e}function kle(n,e,t,r){const i=e*t*4;for(let s=0,o=0;s + + varying vec2 vUv; + + void main() { + vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); + gl_Position = projectionMatrix * mvPosition; + + vUv = uv; + + #include + } + `,fragmentShader:` + #include + + uniform vec3 color; + uniform sampler2D data; + + varying vec2 vUv; + + // adapted from https://www.shadertoy.com/view/Mlt3z8 + float bayerDither2x2( vec2 v ) { + return mod( 3.0 * v.y + 2.0 * v.x, 4.0 ); + } + + float bayerDither4x4( vec2 v ) { + vec2 P1 = mod( v, 2.0 ); + vec2 P2 = mod( floor( 0.5 * v ), 2.0 ); + return 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 ); + } + + void main() { + #include + + float alpha = texture2D(data, vUv).r; + if (alpha < 1.0) { + vec2 ditherCoord = floor( mod( gl_FragCoord.xy, 4.0 ) ); + if ( bayerDither4x4( ditherCoord ) / 16.0 >= alpha ) { + discard; + } + } + + gl_FragColor.rgba = vec4(color.xyz, 1.0); + } + `});function Ole(){return XA(Ile)}function ex(n,e,t){typeof n!="number"&&(n=0,e=0,t=1),typeof e!="number"&&(e=n,n=0,t=1),typeof t!="number"&&(t=1);const r=[],i=Math.min(n,e),s=Math.max(n,e);for(let o=i;o<=s;o+=t)r.push(o);return r}function Lle(n){return n[gp(0,n.length-1)]}function Cc(...n){return Lle(n.flat())}function z3(n,e=16){return n?ex(e-1).map(t=>{const r=t*zb;return new hn(n.bits[r]/63,n.bits[r+1]/63,n.bits[r+2]/63)}):[]}function Ple(n){const e=document.createElement("canvas");if(e.width=(n==null?void 0:n.width)||1,e.height=(n==null?void 0:n.height)||1,n){const t=e.getContext("2d"),r=t==null?void 0:t.getImageData(0,0,n.width,n.height);if(r&&t){let i=0;const{data:s}=r;for(let o=0;oKA(n),[n])}const Mv=[0,1,0],W3=[1,1,0],Cv=[1,0,0],j3=[0,0,0],Wle=new Float32Array([...Mv,...Cv,...W3,...Mv,...j3,...Cv]),jle=new Float32Array([...Mv.slice(0,2),...Cv.slice(0,2),...W3.slice(0,2),...Mv.slice(0,2),...j3.slice(0,2),...Cv.slice(0,2)]);function $le(n,e,t,r,i,s){const o=e*t*4;for(let a=0,c=0;a{switch(a%3){case 0:return o*r;case 1:return o*i;default:return o}});n.setAttribute("position",new er(s,3)),n.setAttribute("uv",new er(jle,2)),n.computeBoundingBox(),n.computeBoundingSphere()}const Xle=z3(H3()),qN=KA(tx()),Kle=new qi({transparent:!1,uniforms:{time:Mo,interval:qA,map:new kn(qN),alt:new kn(qN),data:new kn(null),palette:new kn(Xle),size:{value:new Et},step:{value:new Et}},vertexShader:` + #include + varying vec2 vUv; + void main() { + vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); + gl_Position = projectionMatrix * mvPosition; + vUv = uv; + #include + } + `,fragmentShader:` + #include + + uniform float time; + uniform float interval; + uniform sampler2D map; + uniform sampler2D alt; + uniform usampler2D data; + uniform vec3 palette[16]; + uniform vec2 size; + uniform vec2 step; + varying vec2 vUv; + + void main() { + #include + + uvec4 tiledata = texture(data, vUv); + int colori = int(tiledata.z); + int bgi = int(tiledata.w); + + vec2 charPosition = mod(vUv, size) / size; + vec2 uv = vec2(charPosition.x * step.x, charPosition.y * step.y); + vec3 color = palette[colori]; + + uv.x += step.x * float(tiledata.x); + uv.y += step.y * float(tiledata.y); + uv.y = 1.0 - uv.y; + + bool useAlt = mod(time, interval * 2.0) > interval; + vec3 blip = useAlt ? texture(alt, uv).rgb : texture(map, uv).rgb; + + if (blip.r == 0.0) { + if (bgi >= ${wn.ONCLEAR}) { + discard; + } + color = palette[bgi]; + } + + gl_FragColor.rgb = color; + gl_FragColor.a = 1.0; + } + `});function Yle(){return XA(Kle)}function nx({width:n,height:e,alphas:t}){const r=Qy(),i=ke.useRef(null),[s]=ke.useState(()=>Ole());return ke.useEffect(()=>{s.uniforms.data.value=Nle(n,e)},[s.uniforms.data,n,e]),ke.useEffect(()=>{kle(s.uniforms.data.value,n,e,t)},[s.uniforms.data.value,n,e,t]),ke.useEffect(()=>{i.current&&($3(i.current,n,e),s.clipping=r.length>0,s.clippingPlanes=r,s.needsUpdate=!0)},[s,r,n,e]),ve.jsx("mesh",{material:s,children:ve.jsx("bufferGeometry",{ref:i})})}function Zle({width:n,height:e,alpha:t}){const r=ke.useMemo(()=>new Array(n*e).fill(t),[n,e,t]);return ve.jsx(nx,{width:n,height:e,alphas:r})}const op=new lj,Tu=new Et;function Jle({width:n,height:e,top:t,left:r,right:i,bottom:s,scale:o=.125,alpha:a=.25}){const c=ke.useMemo(()=>{const l=new Array(n*e);op.min.x=r,op.min.y=t,op.max.x=i,op.max.y=s,Tu.x=0,Tu.y=0;for(let u=0;u=n&&(Tu.x=0,++Tu.y);return l},[n,e,t,r,i,s,o,a]);return ve.jsx(nx,{width:n,height:e,alphas:c})}const Qle=z3(H3()),XN=KA(tx()),eue=JL*2,tue=new qi({transparent:!1,uniforms:{time:Mo,interval:qA,smoothrate:new kn(eue),map:new kn(XN),alt:new kn(XN),palette:new kn(Qle),pointSize:{value:new Et(ps,$i)},rows:new kn(1),step:new kn(new Et)},vertexShader:` + #include + + attribute float visible; + attribute vec4 charData; + attribute vec3 lastPosition; + attribute vec2 lastColor; + attribute vec2 lastBg; + attribute vec2 animShake; + attribute vec2 animBounce; + + uniform float smoothrate; + uniform float time; + uniform float interval; + uniform vec2 pointSize; + uniform vec3 palette[16]; + uniform float tindex; + + varying float vVisible; + varying vec2 vCharData; + varying vec3 vColor; + varying vec4 vBg; + + float rand(float co) { + return fract(sin(co*(91.3458)) * 47453.5453); + } + + vec3 colorFromIndex(float index) { + return palette[int(index)]; + } + + vec4 empty; + + vec4 bgFromIndex(float index) { + if (int(index) >= ${wn.ONCLEAR}) { + return empty; + } + vec4 bg; + bg.rgb = colorFromIndex(index); + bg.a = 1.0; + return bg; + } + + float animDelta(float startTime, float deltaMod, float maxDelta) { + float delta = time - startTime; + if (delta < 0.0) { + return maxDelta; + } + return clamp(delta * deltaMod, 0.0, maxDelta); + } + + void main() { + vVisible = visible; + + float deltaPosition = clamp((time - lastPosition.z) * smoothrate, 0.0, 1.0); + vec2 animPosition = mix(lastPosition.xy, position.xy, deltaPosition); + + float deltaShake = 1.0 - animDelta(animShake.y, smoothrate * 0.5, 1.0); + animPosition += vec2( + deltaShake - rand(cos(time) + animShake.x) * deltaShake * 2.0, + deltaShake - rand(sin(time) + animShake.x) * deltaShake * 2.0 + ) * 0.5; + + float deltaBounce = 1.0 - abs(1.0 - animDelta(animBounce.y, smoothrate, 2.0)); + animPosition.y -= smoothstep(0.0, 1.0, deltaBounce); + + float deltaColor = animDelta(lastColor.y, smoothrate, 1.0); + vec3 sourceColor = colorFromIndex(lastColor.x); + vec3 destColor = colorFromIndex(charData.z); + vColor = mix(sourceColor, destColor, deltaColor); + + float deltaBg = animDelta(lastBg.y, smoothrate, 1.0); + vec4 sourceBg = bgFromIndex(lastBg.x); + vec4 destBg = bgFromIndex(charData.w); + vBg = mix(sourceBg, destBg, deltaBg); + + vCharData.xy = charData.xy; + + animPosition = animPosition * pointSize; + animPosition += pointSize * 0.5; + animPosition.x += (pointSize.y - pointSize.x) * 0.5; + + vec4 mvPosition = modelViewMatrix * vec4(animPosition, 0.0, 1.0); + gl_Position = projectionMatrix * mvPosition; + + // this handles things being scaled + gl_PointSize = pointSize.y * modelViewMatrix[0][0]; + + #include + } + `,fragmentShader:` + #include + + uniform float time; + uniform float interval; + uniform sampler2D map; + uniform sampler2D alt; + uniform float rows; + uniform vec2 step; + uniform vec2 pointSize; + + varying float vVisible; + varying vec2 vCharData; + varying vec3 vColor; + varying vec4 vBg; + + void main() { + #include + + float xscale = pointSize.y / pointSize.x; + float px = gl_PointCoord.x * xscale; + + if (vVisible == 0.0 || px >= 1.0) { + discard; + } + + vec2 lookup = vec2(vCharData.x, vCharData.y); + + vec2 idx = vec2(px, 1.0 - gl_PointCoord.y); + vec2 char = vec2(lookup.x * step.x, (rows - lookup.y) * step.y); + vec2 uv = idx * step + char; + + bool useAlt = mod(time, interval * 2.0) > interval; + vec3 blip = useAlt ? texture2D(alt, uv).rgb : texture2D(map, uv).rgb; + + if (blip.r == 0.0) { + gl_FragColor = vBg; + } else { + gl_FragColor.rgb = vColor; + gl_FragColor.a = 1.0; + } + } + `});function nue(){return XA(tue)}const rue=tx(),KN=2048;function iue({sprites:n}){const e=G3(rue),t=Qy(),r=ke.useRef(null),i=ke.useRef([]),[s]=ke.useState(()=>nue()),{width:o=0,height:a=0}=(e==null?void 0:e.image)??{};return ke.useMemo(()=>{var h;i.current.length===0&&(i.current=Array.from({length:KN},()=>({id:"",x:0,y:0,char:0,color:0,bg:0})));const c={};for(let d=0;dd.id));let u=0;for(let d=0;d{const{current:c}=r,{current:l}=i;if(!c||!l)return;let u=c.getAttribute("visible"),h=c.getAttribute("lastVisible"),d=c.getAttribute("position"),m=c.getAttribute("charData"),g=c.getAttribute("lastPosition"),v=c.getAttribute("lastColor"),y=c.getAttribute("lastBg"),_=c.getAttribute("animShake"),S=c.getAttribute("animBounce");if(!u||u.count!==l.length){u=new er(new Float32Array(l.length),1),h=new er(new Float32Array(l.length),1),d=new er(new Float32Array(l.length*3),3),m=new er(new Float32Array(l.length*4),4),g=new er(new Float32Array(l.length*3),3),v=new er(new Float32Array(l.length*2),2),y=new er(new Float32Array(l.length*2),2),_=new er(new Float32Array(l.length*2),2),S=new er(new Float32Array(l.length*2),2);for(let E=0;E{if(!e||!r.current)return;const c=Math.round(o/Vf),l=Math.round(a/Hf);s.uniforms.rows.value=l-1,s.uniforms.step.value.x=1/c,s.uniforms.step.value.y=1/l,s.clipping=t.length>0,s.clippingPlanes=t,s.needsUpdate=!0},[e,s,o,a,t]),ve.jsx("points",{frustumCulled:!1,material:s,children:ve.jsx("bufferGeometry",{ref:r})})}const sue=tx();function q3({width:n,height:e,char:t,color:r,bg:i}){const s=G3(sue),o=Qy(),[a]=ke.useState(()=>Yle()),c=ke.useRef(null),{width:l=0,height:u=0}=(s==null?void 0:s.image)??{};return ke.useEffect(()=>{n===0||e===0||(a.uniforms.data.value=qle(n,e))},[a.uniforms.data,n,e]),ke.useEffect(()=>{n===0||e===0||$le(a.uniforms.data.value,n,e,t,r,i)},[a.uniforms.data.value,n,e,t,r,i]),ke.useEffect(()=>{n===0||e===0||!c.current||!s||($3(c.current,n,e),a.uniforms.size.value.x=1/n,a.uniforms.size.value.y=1/e,a.uniforms.step.value.x=1/Math.round(l/Vf),a.uniforms.step.value.y=1/Math.round(u/Hf),a.clipping=o.length>0,a.clippingPlanes=o,a.needsUpdate=!0)},[s,a,n,e,l,u,o]),ve.jsx("mesh",{material:a,children:ve.jsx("bufferGeometry",{ref:c})})}function oue({id:n,z:e}){const t=kc(iu(r=>r.gadget.layers.find(i=>i.id===n)));switch(t==null?void 0:t.type){default:case _p.BLANK:return null;case _p.TILES:return ve.jsx("group",{position:[0,0,e],children:ve.jsx(q3,{width:t.width,height:t.height,char:[...t.char],color:[...t.color],bg:[...t.bg]})},t.id);case _p.SPRITES:return ve.jsx("group",{position:[0,0,e],children:ve.jsx(iue,{sprites:[...t.sprites]})},t.id);case _p.DITHER:return ve.jsx("group",{position:[0,0,e],children:ve.jsx(nx,{width:t.width,height:t.height,alphas:[...t.alphas]})},t.id)}}var YA={};Object.defineProperty(YA,"__esModule",{value:!0});var X3=YA.GamepadHelper=void 0;const Jn=class Jn{static getButtonValue(e,t){var r,i;return(i=(r=Jn.gamepads[e])==null?void 0:r.buttons[t])==null?void 0:i.value}static getAxisValue(e,t){var r;return(r=Jn.gamepads[e])==null?void 0:r.axes[t]}static update(){Jn.checkForNewGamepads(),!(!Jn.gamepads||Object.keys(Jn.gamepads).length<1)&&(Jn.gamepadsLastUpdate&&Object.keys(Jn.gamepadsLastUpdate).length>0&&Object.values(Jn.gamepads).forEach(e=>{var t;for(let r=0;r1;m&&(d=d.slice(0,-1));var g=JA(d),v=P1[g];if(d.length>1&&!v&&!K3[d]&&!ZA[g])throw new TypeError('Unknown modifier: "'+d+'"');(s===1||!v)&&(t?r.key=g:r.which=J3(d)),v&&(r[v]=m?null:!0)}}catch(y){c=!0,l=y}finally{try{!a&&u.return&&u.return()}finally{if(c)throw l}}return r}function Z3(n,e){for(var t in n){var r=n[t],i=void 0;if(r!=null&&(t==="key"&&e.key!=null?i=e.key.toLowerCase():t==="which"?i=r===91&&e.which===93?91:e.which:i=e[t],!(i==null&&r===!1)&&i!==r))return!1}return!0}function J3(n){n=JA(n);var e=ZA[n]||n.toUpperCase().charCodeAt(0);return e}function JA(n){return n=n.toLowerCase(),n=K3[n]||n,n}var uue=ol.default=rx;ol.isHotkey=rx;ol.isCodeHotkey=cue;ol.isKeyHotkey=lue;ol.parseHotkey=Y3;ol.compareHotkey=Z3;ol.toKeyCode=J3;ol.toKeyName=JA;function Q3(n){return{all:n=n||new Map,on:function(e,t){var r=n.get(e);r?r.push(t):n.set(e,[t])},off:function(e,t){var r=n.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):n.set(e,[]))},emit:function(e,t){var r=n.get(e);r&&r.slice().map(function(i){i(t)}),(r=n.get("*"))&&r.slice().map(function(i){i(e,t)})}}}const fd=navigator.userAgent.includes("Mac"),hue=fd?"cmd":"ctrl",Ta={[Ue.NONE]:!1,[Ue.ALT]:!1,[Ue.CTRL]:!1,[Ue.SHIFT]:!1,[Ue.MOVE_UP]:!1,[Ue.MOVE_DOWN]:!1,[Ue.MOVE_LEFT]:!1,[Ue.MOVE_RIGHT]:!1,[Ue.OK_BUTTON]:!1,[Ue.CANCEL_BUTTON]:!1,[Ue.MENU_BUTTON]:!1,[Ue.SHOOT_UP]:!1,[Ue.SHOOT_DOWN]:!1,[Ue.SHOOT_LEFT]:!1,[Ue.SHOOT_RIGHT]:!1};let I_=0,YN=performance.now();const ZN=200;function ss(n){Ta[n]||(I_=0,t4(n,{alt:Ta[Ue.ALT],ctrl:Ta[Ue.CTRL],shift:Ta[Ue.SHIFT]})),Ta[n]=!0}function os(n){Ta[n]=!1}const Sa={root:Q3(),ignorehotkeys:!1},e4=ke.createContext(Sa.root);function ix(n){return{alt:n.altKey,ctrl:fd?n.metaKey:n.ctrlKey,shift:n.shiftKey}}function t4(n,e){Sa.root.emit(Ue[n],e)}document.addEventListener("keydown",n=>{const e=Kt(n.key),t=ix(n);switch(e){case"s":t.ctrl&&sy("tape","#save",Xi()),n.preventDefault();break;case"v":case"r":t.ctrl||n.preventDefault();break;case"i":!fd&&t.shift&&t.ctrl||n.preventDefault();break;case"dead":fd&&t.alt&&t.ctrl||n.preventDefault();break;case"alt":case"meta":case"shift":case"control":break;default:n.preventDefault();break}switch(t.alt?ss(Ue.ALT):os(Ue.ALT),t.ctrl?ss(Ue.CTRL):os(Ue.CTRL),t.shift?ss(Ue.SHIFT):os(Ue.SHIFT),e){case"arrowleft":ss(Ue.MOVE_LEFT);break;case"arrowright":ss(Ue.MOVE_RIGHT);break;case"arrowup":ss(Ue.MOVE_UP);break;case"arrowdown":ss(Ue.MOVE_DOWN);break;case"enter":ss(Ue.OK_BUTTON);break;case"esc":case"escape":ss(Ue.CANCEL_BUTTON);break;case"tab":ss(Ue.MENU_BUTTON);break}Sa.root.emit("keydown",n)},{capture:!0});document.addEventListener("keyup",n=>{const e=Kt(n.key),t=ix(n);switch(t.alt?ss(Ue.ALT):os(Ue.ALT),t.ctrl?ss(Ue.CTRL):os(Ue.CTRL),t.shift?ss(Ue.SHIFT):os(Ue.SHIFT),e){case"arrowleft":os(Ue.MOVE_LEFT);break;case"arrowright":os(Ue.MOVE_RIGHT);break;case"arrowup":os(Ue.MOVE_UP);break;case"arrowdown":os(Ue.MOVE_DOWN);break;case"enter":os(Ue.OK_BUTTON);break;case"esc":case"escape":os(Ue.CANCEL_BUTTON);break;case"tab":os(Ue.MENU_BUTTON);break}},{capture:!0});const fue=0,due=1,pue=2,mue=3,gue=4,_ue=5,vue=6,yue=7,xue=9,Sue=12,Eue=13,bue=14,Tue=15,n4={[fue]:Ue.OK_BUTTON,[due]:Ue.CANCEL_BUTTON,[pue]:Ue.OK_BUTTON,[mue]:Ue.CANCEL_BUTTON,[gue]:Ue.ALT,[_ue]:Ue.ALT,[vue]:Ue.CTRL,[yue]:Ue.CTRL,[xue]:Ue.MENU_BUTTON,[Sue]:Ue.MOVE_UP,[Eue]:Ue.MOVE_DOWN,[bue]:Ue.MOVE_LEFT,[Tue]:Ue.MOVE_RIGHT};document.addEventListener("gamepadbuttondown",n=>{ss(n4[n.detail.button])});document.addEventListener("gamepadbuttonup",n=>{os(n4[n.detail.button])});function r4(){const n=performance.now(),e=n-YN;if(I_+=e,I_>=ZN){I_%=ZN;const t={alt:!!Ta[Ue.ALT],ctrl:!!Ta[Ue.CTRL],shift:!!Ta[Ue.SHIFT]};[Ue.MOVE_UP,Ue.MOVE_DOWN,Ue.MOVE_LEFT,Ue.MOVE_RIGHT,Ue.OK_BUTTON,Ue.CANCEL_BUTTON,Ue.MENU_BUTTON,Ue.SHOOT_UP,Ue.SHOOT_DOWN,Ue.SHOOT_LEFT,Ue.SHOOT_RIGHT].forEach(i=>{Ta[i]&&t4(i,t)})}YN=n,X3.update(),setTimeout(r4,1)}r4();const JN="keyup";function Np({hotkey:n,children:e}){return ke.useEffect(()=>{const t=uue(n,{byKey:!0});function r(i){Sa.ignorehotkeys===!1&&t(i)&&e()}return document.addEventListener(JN,r,!1),()=>document.removeEventListener(JN,r,!1)},[n,e]),null}function bs(n){const e=ke.useContext(e4);return ke.useEffect(()=>{const t=Object.entries(n);return t.forEach(([r,i])=>e.on(r,i)),()=>{t.forEach(([r,i])=>e.off(r,i))}},[e,n]),null}function $m({blockhotkeys:n,children:e}){const[t]=ke.useState(()=>Q3());return ke.useEffect(()=>{const r=Sa.root,i=Sa.ignorehotkeys;return Sa.root=t,Sa.ignorehotkeys=!!n,()=>{Sa.root=r,Sa.ignorehotkeys=i}},[t,n]),ve.jsx(e4.Provider,{value:t,children:e})}const wue=new Et(0,0);function wu(n,e,t){let r=0;t.alt&&(r|=P3),t.ctrl&&(r|=D3),t.shift&&(r|=U3),GL(n)&&J9("framed",e,r,n)}function Aue({width:n,height:e}){const t=n*ps,r=e*$i,i=ke.useRef(null);ry((a,c)=>{const{current:l}=i;if(!l)return;const u=xle(kc.getState().gadget.layers),h=u.width*ps*u.viewscale,d=h-t,m=u.height*$i*u.viewscale,g=m-r,v=Math.round(Math.min(t,r)*.3333),y=-u.focusx*ps*u.viewscale,_=t*.5+y,S=-u.focusy*$i*u.viewscale,E=r*.5+S,T=h=v){const O=M<0?-v:v;l.userData.focus.x=Math.round(T-O)}}if(g<0)l.userData.focus.y=k;else{const M=l.position.y-k;if(Math.abs(M)>=v){const O=M<0?-v:v;l.userData.focus.y=Math.round(k-O*.5)}}const R=6;l.position.x+=(l.userData.focus.x-l.position.x)*c*R,l.position.y+=(l.userData.focus.y-l.position.y)*c*R,d>=0&&(l.position.x=Nn(l.position.x,-d,0)),g>=0&&(l.position.y=Nn(l.position.y,-g,0))});const s=Xi();kc(a=>a.gadget.layers.length);const{layers:o}=kc.getState().gadget;return ve.jsxs(ve.Fragment,{children:[ve.jsx(bs,{MOVE_LEFT:a=>wu(s,Ue.MOVE_LEFT,a),MOVE_RIGHT:a=>wu(s,Ue.MOVE_RIGHT,a),MOVE_UP:a=>wu(s,Ue.MOVE_UP,a),MOVE_DOWN:a=>wu(s,Ue.MOVE_DOWN,a),OK_BUTTON:a=>wu(s,Ue.OK_BUTTON,a),CANCEL_BUTTON:a=>wu(s,Ue.CANCEL_BUTTON,a),MENU_BUTTON:a=>wu(s,Ue.MENU_BUTTON,a)}),ve.jsx(Tle,{width:t,height:r,children:ve.jsx("group",{ref:i,children:o.map((a,c)=>ve.jsx(oue,{id:a.id,z:c*2},a.id))})})]})}function Hb(n){console&&console.error&&console.error(`Error: ${n}`)}function i4(n){console&&console.warn&&console.warn(`Warning: ${n}`)}function s4(n){const e=new Date().getTime(),t=n();return{time:new Date().getTime()-e,value:t}}function o4(n){function e(){}e.prototype=n;const t=new e;function r(){return typeof t.bar}return r(),r(),n}function Mue(n){return Cue(n)?n.LABEL:n.name}function Cue(n){return xs(n.LABEL)&&n.LABEL!==""}class Qa{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){this._definition=e}accept(e){e.visit(this),At(this.definition,t=>{t.accept(e)})}}class Ts extends Qa{constructor(e){super([]),this.idx=1,ys(this,$o(e,t=>t!==void 0))}set definition(e){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(e){e.visit(this)}}class kd extends Qa{constructor(e){super(e.definition),this.orgText="",ys(this,$o(e,t=>t!==void 0))}}class ws extends Qa{constructor(e){super(e.definition),this.ignoreAmbiguities=!1,ys(this,$o(e,t=>t!==void 0))}}class vs extends Qa{constructor(e){super(e.definition),this.idx=1,ys(this,$o(e,t=>t!==void 0))}}class ec extends Qa{constructor(e){super(e.definition),this.idx=1,ys(this,$o(e,t=>t!==void 0))}}class tc extends Qa{constructor(e){super(e.definition),this.idx=1,ys(this,$o(e,t=>t!==void 0))}}class Vr extends Qa{constructor(e){super(e.definition),this.idx=1,ys(this,$o(e,t=>t!==void 0))}}class Zo extends Qa{constructor(e){super(e.definition),this.idx=1,ys(this,$o(e,t=>t!==void 0))}}class Jo extends Qa{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){super(e.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,ys(this,$o(e,t=>t!==void 0))}}let tr=class{constructor(e){this.idx=1,ys(this,$o(e,t=>t!==void 0))}accept(e){e.visit(this)}};function Rue(n){return ot(n,O_)}function O_(n){function e(t){return ot(t,O_)}if(n instanceof Ts){const t={type:"NonTerminal",name:n.nonTerminalName,idx:n.idx};return xs(n.label)&&(t.label=n.label),t}else{if(n instanceof ws)return{type:"Alternative",definition:e(n.definition)};if(n instanceof vs)return{type:"Option",idx:n.idx,definition:e(n.definition)};if(n instanceof ec)return{type:"RepetitionMandatory",idx:n.idx,definition:e(n.definition)};if(n instanceof tc)return{type:"RepetitionMandatoryWithSeparator",idx:n.idx,separator:O_(new tr({terminalType:n.separator})),definition:e(n.definition)};if(n instanceof Zo)return{type:"RepetitionWithSeparator",idx:n.idx,separator:O_(new tr({terminalType:n.separator})),definition:e(n.definition)};if(n instanceof Vr)return{type:"Repetition",idx:n.idx,definition:e(n.definition)};if(n instanceof Jo)return{type:"Alternation",idx:n.idx,definition:e(n.definition)};if(n instanceof tr){const t={type:"Terminal",name:n.terminalType.name,label:Mue(n.terminalType),idx:n.idx};xs(n.label)&&(t.terminalLabel=n.label);const r=n.terminalType.PATTERN;return n.terminalType.PATTERN&&(t.pattern=Gc(r)?r.source:r),t}else{if(n instanceof kd)return{type:"Rule",name:n.name,orgText:n.orgText,definition:e(n.definition)};throw Error("non exhaustive match")}}}class Ah{visit(e){const t=e;switch(t.constructor){case Ts:return this.visitNonTerminal(t);case ws:return this.visitAlternative(t);case vs:return this.visitOption(t);case ec:return this.visitRepetitionMandatory(t);case tc:return this.visitRepetitionMandatoryWithSeparator(t);case Zo:return this.visitRepetitionWithSeparator(t);case Vr:return this.visitRepetition(t);case Jo:return this.visitAlternation(t);case tr:return this.visitTerminal(t);case kd:return this.visitRule(t);default:throw Error("non exhaustive match")}}visitNonTerminal(e){}visitAlternative(e){}visitOption(e){}visitRepetition(e){}visitRepetitionMandatory(e){}visitRepetitionMandatoryWithSeparator(e){}visitRepetitionWithSeparator(e){}visitAlternation(e){}visitTerminal(e){}visitRule(e){}}function kue(n){return n instanceof ws||n instanceof vs||n instanceof Vr||n instanceof ec||n instanceof tc||n instanceof Zo||n instanceof tr||n instanceof kd}function Rv(n,e=[]){return n instanceof vs||n instanceof Vr||n instanceof Zo?!0:n instanceof Jo?eA(n.definition,r=>Rv(r,e)):n instanceof Ts&&Qi(e,n)?!1:n instanceof Qa?(n instanceof Ts&&e.push(n),Uo(n.definition,r=>Rv(r,e))):!1}function Nue(n){return n instanceof Jo}function Ea(n){if(n instanceof Ts)return"SUBRULE";if(n instanceof vs)return"OPTION";if(n instanceof Jo)return"OR";if(n instanceof ec)return"AT_LEAST_ONE";if(n instanceof tc)return"AT_LEAST_ONE_SEP";if(n instanceof Zo)return"MANY_SEP";if(n instanceof Vr)return"MANY";if(n instanceof tr)return"CONSUME";throw Error("non exhaustive match")}class sx{walk(e,t=[]){At(e.definition,(r,i)=>{const s=di(e.definition,i+1);if(r instanceof Ts)this.walkProdRef(r,s,t);else if(r instanceof tr)this.walkTerminal(r,s,t);else if(r instanceof ws)this.walkFlat(r,s,t);else if(r instanceof vs)this.walkOption(r,s,t);else if(r instanceof ec)this.walkAtLeastOne(r,s,t);else if(r instanceof tc)this.walkAtLeastOneSep(r,s,t);else if(r instanceof Zo)this.walkManySep(r,s,t);else if(r instanceof Vr)this.walkMany(r,s,t);else if(r instanceof Jo)this.walkOr(r,s,t);else throw Error("non exhaustive match")})}walkTerminal(e,t,r){}walkProdRef(e,t,r){}walkFlat(e,t,r){const i=t.concat(r);this.walk(e,i)}walkOption(e,t,r){const i=t.concat(r);this.walk(e,i)}walkAtLeastOne(e,t,r){const i=[new vs({definition:e.definition})].concat(t,r);this.walk(e,i)}walkAtLeastOneSep(e,t,r){const i=QN(e,t,r);this.walk(e,i)}walkMany(e,t,r){const i=[new vs({definition:e.definition})].concat(t,r);this.walk(e,i)}walkManySep(e,t,r){const i=QN(e,t,r);this.walk(e,i)}walkOr(e,t,r){const i=t.concat(r);At(e.definition,s=>{const o=new ws({definition:[s]});this.walk(o,i)})}}function QN(n,e,t){return[new vs({definition:[new tr({terminalType:n.separator})].concat(n.definition)})].concat(e,t)}function qm(n){if(n instanceof Ts)return qm(n.referencedRule);if(n instanceof tr)return Lue(n);if(kue(n))return Iue(n);if(Nue(n))return Oue(n);throw Error("non exhaustive match")}function Iue(n){let e=[];const t=n.definition;let r=0,i=t.length>r,s,o=!0;for(;i&&o;)s=t[r],o=Rv(s),e=e.concat(qm(s)),r=r+1,i=t.length>r;return Ry(e)}function Oue(n){const e=ot(n.definition,t=>qm(t));return Ry(gs(e))}function Lue(n){return[n.terminalType]}const a4="_~IN~_";class Pue extends sx{constructor(e){super(),this.topProd=e,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(e,t,r){}walkProdRef(e,t,r){const i=Uue(e.referencedRule,e.idx)+this.topProd.name,s=t.concat(r),o=new ws({definition:s}),a=qm(o);this.follows[i]=a}}function Due(n){const e={};return At(n,t=>{const r=new Pue(t).startWalking();ys(e,r)}),e}function Uue(n,e){return n.name+e+a4}function Ct(n){return n.charCodeAt(0)}function D1(n,e){Array.isArray(n)?n.forEach(function(t){e.push(t)}):e.push(n)}function ap(n,e){if(n[e]===!0)throw"duplicate flag "+e;n[e],n[e]=!0}function lf(n){if(n===void 0)throw Error("Internal Error - Should never get here!");return!0}function Fue(){throw Error("Internal Error - Should never get here!")}function eI(n){return n.type==="Character"}const kv=[];for(let n=Ct("0");n<=Ct("9");n++)kv.push(n);const Nv=[Ct("_")].concat(kv);for(let n=Ct("a");n<=Ct("z");n++)Nv.push(n);for(let n=Ct("A");n<=Ct("Z");n++)Nv.push(n);const tI=[Ct(" "),Ct("\f"),Ct(` +`),Ct("\r"),Ct(" "),Ct("\v"),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct(" "),Ct("\u2028"),Ct("\u2029"),Ct(" "),Ct(" "),Ct(" "),Ct("\uFEFF")],Bue=/[0-9a-fA-F]/,q0=/[0-9]/,zue=/[1-9]/;class Vue{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(e){this.idx=e.idx,this.input=e.input,this.groupIdx=e.groupIdx}pattern(e){this.idx=0,this.input=e,this.groupIdx=0,this.consumeChar("/");const t=this.disjunction();this.consumeChar("/");const r={type:"Flags",loc:{begin:this.idx,end:e.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":ap(r,"global");break;case"i":ap(r,"ignoreCase");break;case"m":ap(r,"multiLine");break;case"u":ap(r,"unicode");break;case"y":ap(r,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:r,value:t,loc:this.loc(0)}}disjunction(){const e=[],t=this.idx;for(e.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),e.push(this.alternative());return{type:"Disjunction",value:e,loc:this.loc(t)}}alternative(){const e=[],t=this.idx;for(;this.isTerm();)e.push(this.term());return{type:"Alternative",value:e,loc:this.loc(t)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){const e=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(e)};case"$":return{type:"EndAnchor",loc:this.loc(e)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(e)};case"B":return{type:"NonWordBoundary",loc:this.loc(e)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let t;switch(this.popChar()){case"=":t="Lookahead";break;case"!":t="NegativeLookahead";break}lf(t);const r=this.disjunction();return this.consumeChar(")"),{type:t,value:r,loc:this.loc(e)}}return Fue()}quantifier(e=!1){let t;const r=this.idx;switch(this.popChar()){case"*":t={atLeast:0,atMost:1/0};break;case"+":t={atLeast:1,atMost:1/0};break;case"?":t={atLeast:0,atMost:1};break;case"{":const i=this.integerIncludingZero();switch(this.popChar()){case"}":t={atLeast:i,atMost:i};break;case",":let s;this.isDigit()?(s=this.integerIncludingZero(),t={atLeast:i,atMost:s}):t={atLeast:i,atMost:1/0},this.consumeChar("}");break}if(e===!0&&t===void 0)return;lf(t);break}if(!(e===!0&&t===void 0)&&lf(t))return this.peekChar(0)==="?"?(this.consumeChar("?"),t.greedy=!1):t.greedy=!0,t.type="Quantifier",t.loc=this.loc(r),t}atom(){let e;const t=this.idx;switch(this.peekChar()){case".":e=this.dotAll();break;case"\\":e=this.atomEscape();break;case"[":e=this.characterClass();break;case"(":e=this.group();break}if(e===void 0&&this.isPatternCharacter()&&(e=this.patternCharacter()),lf(e))return e.loc=this.loc(t),this.isQuantifier()&&(e.quantifier=this.quantifier()),e}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[Ct(` +`),Ct("\r"),Ct("\u2028"),Ct("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let e,t=!1;switch(this.popChar()){case"d":e=kv;break;case"D":e=kv,t=!0;break;case"s":e=tI;break;case"S":e=tI,t=!0;break;case"w":e=Nv;break;case"W":e=Nv,t=!0;break}if(lf(e))return{type:"Set",value:e,complement:t}}controlEscapeAtom(){let e;switch(this.popChar()){case"f":e=Ct("\f");break;case"n":e=Ct(` +`);break;case"r":e=Ct("\r");break;case"t":e=Ct(" ");break;case"v":e=Ct("\v");break}if(lf(e))return{type:"Character",value:e}}controlLetterEscapeAtom(){this.consumeChar("c");const e=this.popChar();if(/[a-zA-Z]/.test(e)===!1)throw Error("Invalid ");return{type:"Character",value:e.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:Ct("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){const e=this.popChar();return{type:"Character",value:Ct(e)}}classPatternCharacterAtom(){switch(this.peekChar()){case` +`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:const e=this.popChar();return{type:"Character",value:Ct(e)}}}characterClass(){const e=[];let t=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),t=!0);this.isClassAtom();){const r=this.classAtom();if(r.type,eI(r)&&this.isRangeDash()){this.consumeChar("-");const i=this.classAtom();if(i.type,eI(i)){if(i.value=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(e){return{begin:e,end:this.idx}}}class QA{visitChildren(e){for(const t in e){const r=e[t];e.hasOwnProperty(t)&&(r.type!==void 0?this.visit(r):Array.isArray(r)&&r.forEach(i=>{this.visit(i)},this))}}visit(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e);break}this.visitChildren(e)}visitPattern(e){}visitFlags(e){}visitDisjunction(e){}visitAlternative(e){}visitStartAnchor(e){}visitEndAnchor(e){}visitWordBoundary(e){}visitNonWordBoundary(e){}visitLookahead(e){}visitNegativeLookahead(e){}visitCharacter(e){}visitSet(e){}visitGroup(e){}visitGroupBackReference(e){}visitQuantifier(e){}}let L_={};const Hue=new Vue;function ox(n){const e=n.toString();if(L_.hasOwnProperty(e))return L_[e];{const t=Hue.pattern(e);return L_[e]=t,t}}function Gue(){L_={}}const c4="Complement Sets are not supported for first char optimization",Iv=`Unable to use "first char" lexer optimizations: +`;function Wue(n,e=!1){try{const t=ox(n);return Gb(t.value,{},t.flags.ignoreCase)}catch(t){if(t.message===c4)e&&i4(`${Iv} Unable to optimize: < ${n.toString()} > + Complement Sets cannot be automatically optimized. + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let r="";e&&(r=` + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),Hb(`${Iv} + Failed parsing: < ${n.toString()} > + Using the @chevrotain/regexp-to-ast library + Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+r)}}return[]}function Gb(n,e,t){switch(n.type){case"Disjunction":for(let i=0;i{if(typeof c=="number")X0(c,e,t);else{const l=c;if(t===!0)for(let u=l.from;u<=l.to;u++)X0(u,e,t);else{for(let u=l.from;u<=l.to&&u=yp){const u=l.from>=yp?l.from:yp,h=l.to,d=Zl(u),m=Zl(h);for(let g=d;g<=m;g++)e[g]=g}}}});break;case"Group":Gb(o.value,e,t);break;default:throw Error("Non Exhaustive Match")}const a=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&Wb(o)===!1||o.type!=="Group"&&a===!1)break}break;default:throw Error("non exhaustive match!")}return Lr(e)}function X0(n,e,t){const r=Zl(n);e[r]=r,t===!0&&jue(n,e)}function jue(n,e){const t=String.fromCharCode(n),r=t.toUpperCase();if(r!==t){const i=Zl(r.charCodeAt(0));e[i]=i}else{const i=t.toLowerCase();if(i!==t){const s=Zl(i.charCodeAt(0));e[s]=s}}}function nI(n,e){return sd(n.value,t=>{if(typeof t=="number")return Qi(e,t);{const r=t;return sd(e,i=>r.from<=i&&i<=r.to)!==void 0}})}function Wb(n){const e=n.quantifier;return e&&e.atLeast===0?!0:n.value?fn(n.value)?Uo(n.value,Wb):Wb(n.value):!1}class $ue extends QA{constructor(e){super(),this.targetCharCodes=e,this.found=!1}visitChildren(e){if(this.found!==!0){switch(e.type){case"Lookahead":this.visitLookahead(e);return;case"NegativeLookahead":this.visitNegativeLookahead(e);return}super.visitChildren(e)}}visitCharacter(e){Qi(this.targetCharCodes,e.value)&&(this.found=!0)}visitSet(e){e.complement?nI(e,this.targetCharCodes)===void 0&&(this.found=!0):nI(e,this.targetCharCodes)!==void 0&&(this.found=!0)}}function eM(n,e){if(e instanceof RegExp){const t=ox(e),r=new $ue(n);return r.visit(t),r.found}else return sd(e,t=>Qi(n,t.charCodeAt(0)))!==void 0}const hh="PATTERN",vp="defaultMode",K0="modes";let l4=typeof new RegExp("(?:)").sticky=="boolean";function que(n,e){e=Qw(e,{useSticky:l4,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` +`],tracer:(S,E)=>E()});const t=e.tracer;t("initCharCodeToOptimizedIndexMap",()=>{ghe()});let r;t("Reject Lexer.NA",()=>{r=Cy(n,S=>S[hh]===Wr.NA)});let i=!1,s;t("Transform Patterns",()=>{i=!1,s=ot(r,S=>{const E=S[hh];if(Gc(E)){const T=E.source;return T.length===1&&T!=="^"&&T!=="$"&&T!=="."&&!E.ignoreCase?T:T.length===2&&T[0]==="\\"&&!Qi(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],T[1])?T[1]:e.useSticky?iI(E):rI(E)}else{if(Qc(E))return i=!0,{exec:E};if(typeof E=="object")return i=!0,E;if(typeof E=="string"){if(E.length===1)return E;{const T=E.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),k=new RegExp(T);return e.useSticky?iI(k):rI(k)}}else throw Error("non exhaustive match")}})});let o,a,c,l,u;t("misc mapping",()=>{o=ot(r,S=>S.tokenTypeIdx),a=ot(r,S=>{const E=S.GROUP;if(E!==Wr.SKIPPED){if(xs(E))return E;if(Wc(E))return!1;throw Error("non exhaustive match")}}),c=ot(r,S=>{const E=S.LONGER_ALT;if(E)return fn(E)?ot(E,k=>oN(r,k)):[oN(r,E)]}),l=ot(r,S=>S.PUSH_MODE),u=ot(r,S=>Tt(S,"POP_MODE"))});let h;t("Line Terminator Handling",()=>{const S=f4(e.lineTerminatorCharacters);h=ot(r,E=>!1),e.positionTracking!=="onlyOffset"&&(h=ot(r,E=>Tt(E,"LINE_BREAKS")?!!E.LINE_BREAKS:h4(E,S)===!1&&eM(S,E.PATTERN)))});let d,m,g,v;t("Misc Mapping #2",()=>{d=ot(r,u4),m=ot(s,dhe),g=Ss(r,(S,E)=>{const T=E.GROUP;return xs(T)&&T!==Wr.SKIPPED&&(S[T]=[]),S},{}),v=ot(s,(S,E)=>({pattern:s[E],longerAlt:c[E],canLineTerminator:h[E],isCustom:d[E],short:m[E],group:a[E],push:l[E],pop:u[E],tokenTypeIdx:o[E],tokenType:r[E]}))});let y=!0,_=[];return e.safeMode||t("First Char Optimization",()=>{_=Ss(r,(S,E,T)=>{if(typeof E.PATTERN=="string"){const k=E.PATTERN.charCodeAt(0),R=Zl(k);U1(S,R,v[T])}else if(fn(E.START_CHARS_HINT)){let k;At(E.START_CHARS_HINT,R=>{const M=typeof R=="string"?R.charCodeAt(0):R,O=Zl(M);k!==O&&(k=O,U1(S,O,v[T]))})}else if(Gc(E.PATTERN))if(E.PATTERN.unicode)y=!1,e.ensureOptimizations&&Hb(`${Iv} Unable to analyze < ${E.PATTERN.toString()} > pattern. + The regexp unicode flag is not currently supported by the regexp-to-ast library. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{const k=Wue(E.PATTERN,e.ensureOptimizations);zn(k)&&(y=!1),At(k,R=>{U1(S,R,v[T])})}else e.ensureOptimizations&&Hb(`${Iv} TokenType: <${E.name}> is using a custom token pattern without providing parameter. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),y=!1;return S},[])}),{emptyGroups:g,patternIdxToConfig:v,charCodeToPatternIdxToConfig:_,hasCustom:i,canBeOptimized:y}}function Xue(n,e){let t=[];const r=Yue(n);t=t.concat(r.errors);const i=Zue(r.valid),s=i.valid;return t=t.concat(i.errors),t=t.concat(Kue(s)),t=t.concat(she(s)),t=t.concat(ohe(s,e)),t=t.concat(ahe(s)),t}function Kue(n){let e=[];const t=yo(n,r=>Gc(r[hh]));return e=e.concat(Que(t)),e=e.concat(nhe(t)),e=e.concat(rhe(t)),e=e.concat(ihe(t)),e=e.concat(ehe(t)),e}function Yue(n){const e=yo(n,i=>!Tt(i,hh)),t=ot(e,i=>({message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:lr.MISSING_PATTERN,tokenTypes:[i]})),r=My(n,e);return{errors:t,valid:r}}function Zue(n){const e=yo(n,i=>{const s=i[hh];return!Gc(s)&&!Qc(s)&&!Tt(s,"exec")&&!xs(s)}),t=ot(e,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:lr.INVALID_PATTERN,tokenTypes:[i]})),r=My(n,e);return{errors:t,valid:r}}const Jue=/[^\\][$]/;function Que(n){class e extends QA{constructor(){super(...arguments),this.found=!1}visitEndAnchor(s){this.found=!0}}const t=yo(n,i=>{const s=i.PATTERN;try{const o=ox(s),a=new e;return a.visit(o),a.found}catch{return Jue.test(s.source)}});return ot(t,i=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain end of input anchor '$' + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:lr.EOI_ANCHOR_FOUND,tokenTypes:[i]}))}function ehe(n){const e=yo(n,r=>r.PATTERN.test(""));return ot(e,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' must not match an empty string",type:lr.EMPTY_MATCH_PATTERN,tokenTypes:[r]}))}const the=/[^\\[][\^]|^\^/;function nhe(n){class e extends QA{constructor(){super(...arguments),this.found=!1}visitStartAnchor(s){this.found=!0}}const t=yo(n,i=>{const s=i.PATTERN;try{const o=ox(s),a=new e;return a.visit(o),a.found}catch{return the.test(s.source)}});return ot(t,i=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain start of input anchor '^' + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:lr.SOI_ANCHOR_FOUND,tokenTypes:[i]}))}function rhe(n){const e=yo(n,r=>{const i=r[hh];return i instanceof RegExp&&(i.multiline||i.global)});return ot(e,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:lr.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[r]}))}function ihe(n){const e=[];let t=ot(n,s=>Ss(n,(o,a)=>(s.PATTERN.source===a.PATTERN.source&&!Qi(e,a)&&a.PATTERN!==Wr.NA&&(e.push(a),o.push(a)),o),[]));t=Am(t);const r=yo(t,s=>s.length>1);return ot(r,s=>{const o=ot(s,c=>c.name);return{message:`The same RegExp pattern ->${Vo(s).PATTERN}<-has been used in all of the following Token Types: ${o.join(", ")} <-`,type:lr.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}})}function she(n){const e=yo(n,r=>{if(!Tt(r,"GROUP"))return!1;const i=r.GROUP;return i!==Wr.SKIPPED&&i!==Wr.NA&&!xs(i)});return ot(e,r=>({message:"Token Type: ->"+r.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:lr.INVALID_GROUP_TYPE_FOUND,tokenTypes:[r]}))}function ohe(n,e){const t=yo(n,i=>i.PUSH_MODE!==void 0&&!Qi(e,i.PUSH_MODE));return ot(t,i=>({message:`Token Type: ->${i.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${i.PUSH_MODE}<-which does not exist`,type:lr.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}))}function ahe(n){const e=[],t=Ss(n,(r,i,s)=>{const o=i.PATTERN;return o===Wr.NA||(xs(o)?r.push({str:o,idx:s,tokenType:i}):Gc(o)&&lhe(o)&&r.push({str:o.source,idx:s,tokenType:i})),r},[]);return At(n,(r,i)=>{At(t,({str:s,idx:o,tokenType:a})=>{if(i${a.name}<- can never be matched. +Because it appears AFTER the Token Type ->${r.name}<-in the lexer's definition. +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;e.push({message:c,type:lr.UNREACHABLE_PATTERN,tokenTypes:[r,a]})}})}),e}function che(n,e){if(Gc(e)){const t=e.exec(n);return t!==null&&t.index===0}else{if(Qc(e))return e(n,0,[],{});if(Tt(e,"exec"))return e.exec(n,0,[],{});if(typeof e=="string")return e===n;throw Error("non exhaustive match")}}function lhe(n){return sd([".","\\","[","]","|","^","$","(",")","?","*","+","{"],t=>n.source.indexOf(t)!==-1)===void 0}function rI(n){const e=n.ignoreCase?"i":"";return new RegExp(`^(?:${n.source})`,e)}function iI(n){const e=n.ignoreCase?"iy":"y";return new RegExp(`${n.source}`,e)}function uhe(n,e,t){const r=[];return Tt(n,vp)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+vp+`> property in its definition +`,type:lr.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),Tt(n,K0)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+K0+`> property in its definition +`,type:lr.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),Tt(n,K0)&&Tt(n,vp)&&!Tt(n.modes,n.defaultMode)&&r.push({message:`A MultiMode Lexer cannot be initialized with a ${vp}: <${n.defaultMode}>which does not exist +`,type:lr.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),Tt(n,K0)&&At(n.modes,(i,s)=>{At(i,(o,a)=>{if(Wc(o))r.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${s}> at index: <${a}> +`,type:lr.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED});else if(Tt(o,"LONGER_ALT")){const c=fn(o.LONGER_ALT)?o.LONGER_ALT:[o.LONGER_ALT];At(c,l=>{!Wc(l)&&!Qi(i,l)&&r.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${l.name}> on token <${o.name}> outside of mode <${s}> +`,type:lr.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),r}function hhe(n,e,t){const r=[];let i=!1;const s=Am(gs(Lr(n.modes))),o=Cy(s,c=>c[hh]===Wr.NA),a=f4(t);return e&&At(o,c=>{const l=h4(c,a);if(l!==!1){const h={message:mhe(c,l),type:l.issue,tokenType:c};r.push(h)}else Tt(c,"LINE_BREAKS")?c.LINE_BREAKS===!0&&(i=!0):eM(a,c.PATTERN)&&(i=!0)}),e&&!i&&r.push({message:`Warning: No LINE_BREAKS Found. + This Lexer has been defined to track line and column information, + But none of the Token Types can be identified as matching a line terminator. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS + for details.`,type:lr.NO_LINE_BREAKS_FLAGS}),r}function fhe(n){const e={},t=vo(n);return At(t,r=>{const i=n[r];if(fn(i))e[r]=[];else throw Error("non exhaustive match")}),e}function u4(n){const e=n.PATTERN;if(Gc(e))return!1;if(Qc(e))return!0;if(Tt(e,"exec"))return!0;if(xs(e))return!1;throw Error("non exhaustive match")}function dhe(n){return xs(n)&&n.length===1?n.charCodeAt(0):!1}const phe={test:function(n){const e=n.length;for(let t=this.lastIndex;t Token Type + Root cause: ${e.errMsg}. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(e.issue===lr.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. + The problem is in the <${n.name}> Token Type + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function f4(n){return ot(n,t=>xs(t)?t.charCodeAt(0):t)}function U1(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}const yp=256;let P_=[];function Zl(n){return n255?255+~~(n/255):n}}function Xm(n,e){const t=n.tokenTypeIdx;return t===e.tokenTypeIdx?!0:e.isParent===!0&&e.categoryMatchesMap[t]===!0}function Ov(n,e){return n.tokenTypeIdx===e.tokenTypeIdx}let sI=1;const d4={};function Km(n){const e=_he(n);vhe(e),xhe(e),yhe(e),At(e,t=>{t.isParent=t.categoryMatches.length>0})}function _he(n){let e=mi(n),t=n,r=!0;for(;r;){t=Am(gs(ot(t,s=>s.CATEGORIES)));const i=My(t,e);e=e.concat(i),zn(i)?r=!1:t=i}return e}function vhe(n){At(n,e=>{m4(e)||(d4[sI]=e,e.tokenTypeIdx=sI++),oI(e)&&!fn(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),oI(e)||(e.CATEGORIES=[]),She(e)||(e.categoryMatches=[]),Ehe(e)||(e.categoryMatchesMap={})})}function yhe(n){At(n,e=>{e.categoryMatches=[],At(e.categoryMatchesMap,(t,r)=>{e.categoryMatches.push(d4[r].tokenTypeIdx)})})}function xhe(n){At(n,e=>{p4([],e)})}function p4(n,e){At(n,t=>{e.categoryMatchesMap[t.tokenTypeIdx]=!0}),At(e.CATEGORIES,t=>{const r=n.concat(e);Qi(r,t)||p4(r,t)})}function m4(n){return Tt(n,"tokenTypeIdx")}function oI(n){return Tt(n,"CATEGORIES")}function She(n){return Tt(n,"categoryMatches")}function Ehe(n){return Tt(n,"categoryMatchesMap")}function bhe(n){return Tt(n,"tokenTypeIdx")}const The={buildUnableToPopLexerModeMessage(n){return`Unable to pop Lexer Mode after encountering Token ->${n.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(n,e,t,r,i){return`unexpected character: ->${n.charAt(e)}<- at offset: ${e}, skipped ${t} characters.`}};var lr;(function(n){n[n.MISSING_PATTERN=0]="MISSING_PATTERN",n[n.INVALID_PATTERN=1]="INVALID_PATTERN",n[n.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",n[n.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",n[n.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",n[n.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",n[n.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",n[n.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",n[n.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",n[n.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",n[n.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",n[n.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",n[n.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",n[n.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",n[n.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",n[n.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",n[n.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",n[n.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(lr||(lr={}));const xp={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` +`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:The,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(xp);class Wr{constructor(e,t=xp){if(this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(i,s)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;const o=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${i}>`);const{time:a,value:c}=s4(s),l=a>10?console.warn:console.log;return this.traceInitIndent time: ${a}ms`),this.traceInitIndent--,c}else return s()},typeof t=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`);this.config=ys({},xp,t);const r=this.config.traceInitPerf;r===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof r=="number"&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let i,s=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===xp.lineTerminatorsPattern)this.config.lineTerminatorsPattern=phe;else if(this.config.lineTerminatorCharacters===xp.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(t.safeMode&&t.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),fn(e)?i={modes:{defaultMode:mi(e)},defaultMode:vp}:(s=!1,i=mi(e))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(uhe(i,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(hhe(i,this.trackStartLines,this.config.lineTerminatorCharacters))})),i.modes=i.modes?i.modes:{},At(i.modes,(a,c)=>{i.modes[c]=Cy(a,l=>Wc(l))});const o=vo(i.modes);if(At(i.modes,(a,c)=>{this.TRACE_INIT(`Mode: <${c}> processing`,()=>{if(this.modes.push(c),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(Xue(a,o))}),zn(this.lexerDefinitionErrors)){Km(a);let l;this.TRACE_INIT("analyzeTokenTypes",()=>{l=que(a,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:t.positionTracking,ensureOptimizations:t.ensureOptimizations,safeMode:t.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[c]=l.patternIdxToConfig,this.charCodeToPatternIdxToConfig[c]=l.charCodeToPatternIdxToConfig,this.emptyGroups=ys({},this.emptyGroups,l.emptyGroups),this.hasCustom=l.hasCustom||this.hasCustom,this.canModeBeOptimized[c]=l.canBeOptimized}})}),this.defaultMode=i.defaultMode,!zn(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){const c=ot(this.lexerDefinitionErrors,l=>l.message).join(`----------------------- +`);throw new Error(`Errors detected in definition of Lexer: +`+c)}At(this.lexerDefinitionWarning,a=>{i4(a.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(l4?(this.chopInput=nd,this.match=this.matchWithTest):(this.updateLastIndex=Fr,this.match=this.matchWithExec),s&&(this.handleModes=Fr),this.trackStartLines===!1&&(this.computeNewColumn=nd),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=Fr),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{const a=Ss(this.canModeBeOptimized,(c,l,u)=>(l===!1&&c.push(u),c),[]);if(t.ensureOptimizations&&!zn(a))throw Error(`Lexer Modes: < ${a.join(", ")} > cannot be optimized. + Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. + Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{Gue()}),this.TRACE_INIT("toFastProperties",()=>{o4(this)})})}tokenize(e,t=this.defaultMode){if(!zn(this.lexerDefinitionErrors)){const i=ot(this.lexerDefinitionErrors,s=>s.message).join(`----------------------- +`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: +`+i)}return this.tokenizeInternal(e,t)}tokenizeInternal(e,t){let r,i,s,o,a,c,l,u,h,d,m,g,v,y,_;const S=e,E=S.length;let T=0,k=0;const R=this.hasCustom?0:Math.floor(e.length/10),M=new Array(R),O=[];let C=this.trackStartLines?1:void 0,I=this.trackStartLines?1:void 0;const U=fhe(this.emptyGroups),L=this.trackStartLines,P=this.config.lineTerminatorsPattern;let w=0,H=[],V=[];const B=[],z=[];Object.freeze(z);let W;function K(){return H}function j(be){const Ae=Zl(be),Ee=V[Ae];return Ee===void 0?z:Ee}const Y=be=>{if(B.length===1&&be.tokenType.PUSH_MODE===void 0){const Ae=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(be);O.push({offset:be.startOffset,line:be.startLine,column:be.startColumn,length:be.image.length,message:Ae})}else{B.pop();const Ae=id(B);H=this.patternIdxToConfig[Ae],V=this.charCodeToPatternIdxToConfig[Ae],w=H.length;const Ee=this.canModeBeOptimized[Ae]&&this.config.safeMode===!1;V&&Ee?W=j:W=K}};function ge(be){B.push(be),V=this.charCodeToPatternIdxToConfig[be],H=this.patternIdxToConfig[be],w=H.length,w=H.length;const Ae=this.canModeBeOptimized[be]&&this.config.safeMode===!1;V&&Ae?W=j:W=K}ge.call(this,t);let Q;const re=this.config.recoveryEnabled;for(;Tc.length){c=o,l=u,Q=it;break}}}break}}if(c!==null){if(h=c.length,d=Q.group,d!==void 0&&(m=Q.tokenTypeIdx,g=this.createTokenInstance(c,T,m,Q.tokenType,C,I,h),this.handlePayload(g,l),d===!1?k=this.addToken(M,k,g):U[d].push(g)),e=this.chopInput(e,h),T=T+h,I=this.computeNewColumn(I,h),L===!0&&Q.canLineTerminator===!0){let Le=0,He,qe;P.lastIndex=0;do He=P.test(c),He===!0&&(qe=P.lastIndex-1,Le++);while(He===!0);Le!==0&&(C=C+Le,I=h-qe,this.updateTokenEndLineColumnLocation(g,d,qe,Le,C,I,h))}this.handleModes(Q,Y,ge,g)}else{const Le=T,He=C,qe=I;let it=re===!1;for(;it===!1&&T ${Ip(n)} <--`:`token of type --> ${n.name} <--`} but found --> '${e.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:n,ruleName:e}){return"Redundant input, expecting EOF but found: "+n.image},buildNoViableAltMessage({expectedPathsPerAlt:n,actual:e,previous:t,customUserDescription:r,ruleName:i}){const s="Expecting: ",a=` +but found: '`+Vo(e).image+"'";if(r)return s+r+a;{const c=Ss(n,(d,m)=>d.concat(m),[]),l=ot(c,d=>`[${ot(d,m=>Ip(m)).join(", ")}]`),h=`one of these possible Token sequences: +${ot(l,(d,m)=>` ${m+1}. ${d}`).join(` +`)}`;return s+h+a}},buildEarlyExitMessage({expectedIterationPaths:n,actual:e,customUserDescription:t,ruleName:r}){const i="Expecting: ",o=` +but found: '`+Vo(e).image+"'";if(t)return i+t+o;{const c=`expecting at least one iteration which starts with one of these possible Token sequences:: + <${ot(n,l=>`[${ot(l,u=>Ip(u)).join(",")}]`).join(" ,")}>`;return i+c+o}}};Object.freeze(_4);const Che={buildRuleNotFoundError(n,e){return"Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+`<- +inside top level rule: ->`+n.name+"<-"}},Wu={buildDuplicateFoundError(n,e){function t(u){return u instanceof tr?u.terminalType.name:u instanceof Ts?u.nonTerminalName:""}const r=n.name,i=Vo(e),s=i.idx,o=Ea(i),a=t(i),c=s>0;let l=`->${o}${c?s:""}<- ${a?`with argument: ->${a}<-`:""} + appears more than once (${e.length} times) in the top level rule: ->${r}<-. + For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES + `;return l=l.replace(/[ \t]+/g," "),l=l.replace(/\s\s+/g,` +`),l},buildNamespaceConflictError(n){return`Namespace conflict found in grammar. +The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${n.name}>. +To resolve this make sure each Terminal and Non-Terminal names are unique +This is easy to accomplish by using the convention that Terminal names start with an uppercase letter +and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(n){const e=ot(n.prefixPath,i=>Ip(i)).join(", "),t=n.alternation.idx===0?"":n.alternation.idx;return`Ambiguous alternatives: <${n.ambiguityIndices.join(" ,")}> due to common lookahead prefix +in inside <${n.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX +For Further details.`},buildAlternationAmbiguityError(n){const e=ot(n.prefixPath,i=>Ip(i)).join(", "),t=n.alternation.idx===0?"":n.alternation.idx;let r=`Ambiguous Alternatives Detected: <${n.ambiguityIndices.join(" ,")}> in inside <${n.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +`;return r=r+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`,r},buildEmptyRepetitionError(n){let e=Ea(n.repetition);return n.repetition.idx!==0&&(e+=n.repetition.idx),`The repetition <${e}> within Rule <${n.topLevelRule.name}> can never consume any tokens. +This could lead to an infinite loop.`},buildTokenNameError(n){return"deprecated"},buildEmptyAlternationError(n){return`Ambiguous empty alternative: <${n.emptyChoiceIdx+1}> in inside <${n.topLevelRule.name}> Rule. +Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(n){return`An Alternation cannot have more than 256 alternatives: + inside <${n.topLevelRule.name}> Rule. + has ${n.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(n){const e=n.topLevelRule.name,t=ot(n.leftRecursionPath,s=>s.name),r=`${e} --> ${t.concat([e]).join(" --> ")}`;return`Left Recursion found in grammar. +rule: <${e}> can be invoked from itself (directly or indirectly) +without consuming any Tokens. The grammar path that causes this is: + ${r} + To fix this refactor your grammar to remove the left recursion. +see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(n){return"deprecated"},buildDuplicateRuleNameError(n){let e;return n.topLevelRule instanceof kd?e=n.topLevelRule.name:e=n.topLevelRule,`Duplicate definition, rule: ->${e}<- is already defined in the grammar: ->${n.grammarName}<-`}};function Rhe(n,e){const t=new khe(n,e);return t.resolveRefs(),t.errors}class khe extends Ah{constructor(e,t){super(),this.nameToTopRule=e,this.errMsgProvider=t,this.errors=[]}resolveRefs(){At(Lr(this.nameToTopRule),e=>{this.currTopLevel=e,e.accept(this)})}visitNonTerminal(e){const t=this.nameToTopRule[e.nonTerminalName];if(t)e.referencedRule=t;else{const r=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:r,type:Ki.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}}}class Nhe extends sx{constructor(e,t){super(),this.topProd=e,this.path=t,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=mi(this.path.ruleStack).reverse(),this.occurrenceStack=mi(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(e,t=[]){this.found||super.walk(e,t)}walkProdRef(e,t,r){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){const i=t.concat(r);this.updateExpectedNext(),this.walk(e.referencedRule,i)}}updateExpectedNext(){zn(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}}class Ihe extends Nhe{constructor(e,t){super(e,t),this.path=t,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(e,t,r){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){const i=t.concat(r),s=new ws({definition:i});this.possibleTokTypes=qm(s),this.found=!0}}}class ax extends sx{constructor(e,t){super(),this.topRule=e,this.occurrence=t,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}}class Ohe extends ax{walkMany(e,t,r){if(e.idx===this.occurrence){const i=Vo(t.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tr&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkMany(e,t,r)}}class mI extends ax{walkManySep(e,t,r){if(e.idx===this.occurrence){const i=Vo(t.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tr&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkManySep(e,t,r)}}class Lhe extends ax{walkAtLeastOne(e,t,r){if(e.idx===this.occurrence){const i=Vo(t.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tr&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOne(e,t,r)}}class gI extends ax{walkAtLeastOneSep(e,t,r){if(e.idx===this.occurrence){const i=Vo(t.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tr&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOneSep(e,t,r)}}function jb(n,e,t=[]){t=mi(t);let r=[],i=0;function s(a){return a.concat(di(n,i+1))}function o(a){const c=jb(s(a),e,t);return r.concat(c)}for(;t.length{zn(c.definition)===!1&&(r=o(c.definition))}),r;if(a instanceof tr)t.push(a.terminalType);else throw Error("non exhaustive match")}i++}return r.push({partialPath:t,suffixDef:di(n,i)}),r}function v4(n,e,t,r){const i="EXIT_NONE_TERMINAL",s=[i],o="EXIT_ALTERNATIVE";let a=!1;const c=e.length,l=c-r-1,u=[],h=[];for(h.push({idx:-1,def:n,ruleStack:[],occurrenceStack:[]});!zn(h);){const d=h.pop();if(d===o){a&&id(h).idx<=l&&h.pop();continue}const m=d.def,g=d.idx,v=d.ruleStack,y=d.occurrenceStack;if(zn(m))continue;const _=m[0];if(_===i){const S={idx:g,def:di(m),ruleStack:Zp(v),occurrenceStack:Zp(y)};h.push(S)}else if(_ instanceof tr)if(g=0;S--){const E=_.definition[S],T={idx:g,def:E.definition.concat(di(m)),ruleStack:v,occurrenceStack:y};h.push(T),h.push(o)}else if(_ instanceof ws)h.push({idx:g,def:_.definition.concat(di(m)),ruleStack:v,occurrenceStack:y});else if(_ instanceof kd)h.push(Phe(_,g,v,y));else throw Error("non exhaustive match")}return u}function Phe(n,e,t,r){const i=mi(t);i.push(n.name);const s=mi(r);return s.push(1),{idx:e,def:n.definition,ruleStack:i,occurrenceStack:s}}var cr;(function(n){n[n.OPTION=0]="OPTION",n[n.REPETITION=1]="REPETITION",n[n.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",n[n.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",n[n.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",n[n.ALTERNATION=5]="ALTERNATION"})(cr||(cr={}));function y4(n){if(n instanceof vs||n==="Option")return cr.OPTION;if(n instanceof Vr||n==="Repetition")return cr.REPETITION;if(n instanceof ec||n==="RepetitionMandatory")return cr.REPETITION_MANDATORY;if(n instanceof tc||n==="RepetitionMandatoryWithSeparator")return cr.REPETITION_MANDATORY_WITH_SEPARATOR;if(n instanceof Zo||n==="RepetitionWithSeparator")return cr.REPETITION_WITH_SEPARATOR;if(n instanceof Jo||n==="Alternation")return cr.ALTERNATION;throw Error("non exhaustive match")}function Dhe(n,e,t,r,i,s){const o=tM(n,e,t),a=E4(o)?Ov:Xm;return s(o,r,a,i)}function Uhe(n,e,t,r,i,s){const o=nM(n,e,i,t),a=E4(o)?Ov:Xm;return s(o[0],a,r)}function Fhe(n,e,t,r){const i=n.length,s=Uo(n,o=>Uo(o,a=>a.length===1));if(e)return function(o){const a=ot(o,c=>c.GATE);for(let c=0;cgs(c)),a=Ss(o,(c,l,u)=>(At(l,h=>{Tt(c,h.tokenTypeIdx)||(c[h.tokenTypeIdx]=u),At(h.categoryMatches,d=>{Tt(c,d)||(c[d]=u)})}),c),{});return function(){const c=this.LA(1);return a[c.tokenTypeIdx]}}else return function(){for(let o=0;os.length===1),i=n.length;if(r&&!t){const s=gs(n);if(s.length===1&&zn(s[0].categoryMatches)){const a=s[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===a}}else{const o=Ss(s,(a,c,l)=>(a[c.tokenTypeIdx]=!0,At(c.categoryMatches,u=>{a[u]=!0}),a),[]);return function(){const a=this.LA(1);return o[a.tokenTypeIdx]===!0}}}else return function(){e:for(let s=0;sjb([o],1)),r=_I(t.length),i=ot(t,o=>{const a={};return At(o,c=>{const l=F1(c.partialPath);At(l,u=>{a[u]=!0})}),a});let s=t;for(let o=1;o<=e;o++){const a=s;s=_I(a.length);for(let c=0;c{const _=F1(y.partialPath);At(_,S=>{i[c][S]=!0})})}}}}return r}function tM(n,e,t,r){const i=new x4(n,cr.ALTERNATION,r);return e.accept(i),S4(i.result,t)}function nM(n,e,t,r){const i=new x4(n,t);e.accept(i);const s=i.result,a=new zhe(e,n,t).startWalking(),c=new ws({definition:s}),l=new ws({definition:a});return S4([c,l],r)}function $b(n,e){e:for(let t=0;t{const i=e[r];return t===i||i.categoryMatchesMap[t.tokenTypeIdx]})}function E4(n){return Uo(n,e=>Uo(e,t=>Uo(t,r=>zn(r.categoryMatches))))}function Ghe(n){const e=n.lookaheadStrategy.validate({rules:n.rules,tokenTypes:n.tokenTypes,grammarName:n.grammarName});return ot(e,t=>Object.assign({type:Ki.CUSTOM_LOOKAHEAD_VALIDATION},t))}function Whe(n,e,t,r){const i=uo(n,c=>jhe(c,t)),s=rfe(n,e,t),o=uo(n,c=>Qhe(c,t)),a=uo(n,c=>Xhe(c,n,r,t));return i.concat(s,o,a)}function jhe(n,e){const t=new qhe;n.accept(t);const r=t.allProductions,i=xU(r,$he),s=$o(i,a=>a.length>1);return ot(Lr(s),a=>{const c=Vo(a),l=e.buildDuplicateFoundError(n,a),u=Ea(c),h={message:l,type:Ki.DUPLICATE_PRODUCTIONS,ruleName:n.name,dslName:u,occurrence:c.idx},d=b4(c);return d&&(h.parameter=d),h})}function $he(n){return`${Ea(n)}_#_${n.idx}_#_${b4(n)}`}function b4(n){return n instanceof tr?n.terminalType.name:n instanceof Ts?n.nonTerminalName:""}class qhe extends Ah{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(e){this.allProductions.push(e)}visitOption(e){this.allProductions.push(e)}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}visitAlternation(e){this.allProductions.push(e)}visitTerminal(e){this.allProductions.push(e)}}function Xhe(n,e,t,r){const i=[];if(Ss(e,(o,a)=>a.name===n.name?o+1:o,0)>1){const o=r.buildDuplicateRuleNameError({topLevelRule:n,grammarName:t});i.push({message:o,type:Ki.DUPLICATE_RULE_NAME,ruleName:n.name})}return i}function Khe(n,e,t){const r=[];let i;return Qi(e,n)||(i=`Invalid rule override, rule: ->${n}<- cannot be overridden in the grammar: ->${t}<-as it is not defined in any of the super grammars `,r.push({message:i,type:Ki.INVALID_RULE_OVERRIDE,ruleName:n})),r}function T4(n,e,t,r=[]){const i=[],s=D_(e.definition);if(zn(s))return[];{const o=n.name;Qi(s,n)&&i.push({message:t.buildLeftRecursionError({topLevelRule:n,leftRecursionPath:r}),type:Ki.LEFT_RECURSION,ruleName:o});const c=My(s,r.concat([n])),l=uo(c,u=>{const h=mi(r);return h.push(u),T4(n,u,t,h)});return i.concat(l)}}function D_(n){let e=[];if(zn(n))return e;const t=Vo(n);if(t instanceof Ts)e.push(t.referencedRule);else if(t instanceof ws||t instanceof vs||t instanceof ec||t instanceof tc||t instanceof Zo||t instanceof Vr)e=e.concat(D_(t.definition));else if(t instanceof Jo)e=gs(ot(t.definition,s=>D_(s.definition)));else if(!(t instanceof tr))throw Error("non exhaustive match");const r=Rv(t),i=n.length>1;if(r&&i){const s=di(n);return e.concat(D_(s))}else return e}class rM extends Ah{constructor(){super(...arguments),this.alternations=[]}visitAlternation(e){this.alternations.push(e)}}function Yhe(n,e){const t=new rM;n.accept(t);const r=t.alternations;return uo(r,s=>{const o=Zp(s.definition);return uo(o,(a,c)=>{const l=v4([a],[],Xm,1);return zn(l)?[{message:e.buildEmptyAlternationError({topLevelRule:n,alternation:s,emptyChoiceIdx:c}),type:Ki.NONE_LAST_EMPTY_ALT,ruleName:n.name,occurrence:s.idx,alternative:c+1}]:[]})})}function Zhe(n,e,t){const r=new rM;n.accept(r);let i=r.alternations;return i=Cy(i,o=>o.ignoreAmbiguities===!0),uo(i,o=>{const a=o.idx,c=o.maxLookahead||e,l=tM(a,n,c,o),u=tfe(l,o,n,t),h=nfe(l,o,n,t);return u.concat(h)})}class Jhe extends Ah{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}}function Qhe(n,e){const t=new rM;n.accept(t);const r=t.alternations;return uo(r,s=>s.definition.length>255?[{message:e.buildTooManyAlternativesError({topLevelRule:n,alternation:s}),type:Ki.TOO_MANY_ALTS,ruleName:n.name,occurrence:s.idx}]:[])}function efe(n,e,t){const r=[];return At(n,i=>{const s=new Jhe;i.accept(s);const o=s.allProductions;At(o,a=>{const c=y4(a),l=a.maxLookahead||e,u=a.idx,d=nM(u,i,c,l)[0];if(zn(gs(d))){const m=t.buildEmptyRepetitionError({topLevelRule:i,repetition:a});r.push({message:m,type:Ki.NO_NON_EMPTY_LOOKAHEAD,ruleName:i.name})}})}),r}function tfe(n,e,t,r){const i=[],s=Ss(n,(a,c,l)=>(e.definition[l].ignoreAmbiguities===!0||At(c,u=>{const h=[l];At(n,(d,m)=>{l!==m&&$b(d,u)&&e.definition[m].ignoreAmbiguities!==!0&&h.push(m)}),h.length>1&&!$b(i,u)&&(i.push(u),a.push({alts:h,path:u}))}),a),[]);return ot(s,a=>{const c=ot(a.alts,u=>u+1);return{message:r.buildAlternationAmbiguityError({topLevelRule:t,alternation:e,ambiguityIndices:c,prefixPath:a.path}),type:Ki.AMBIGUOUS_ALTS,ruleName:t.name,occurrence:e.idx,alternatives:a.alts}})}function nfe(n,e,t,r){const i=Ss(n,(o,a,c)=>{const l=ot(a,u=>({idx:c,path:u}));return o.concat(l)},[]);return Am(uo(i,o=>{if(e.definition[o.idx].ignoreAmbiguities===!0)return[];const c=o.idx,l=o.path,u=yo(i,d=>e.definition[d.idx].ignoreAmbiguities!==!0&&d.idx{const m=[d.idx+1,c+1],g=e.idx===0?"":e.idx;return{message:r.buildAlternationPrefixAmbiguityError({topLevelRule:t,alternation:e,ambiguityIndices:m,prefixPath:d.path}),type:Ki.AMBIGUOUS_PREFIX_ALTS,ruleName:t.name,occurrence:g,alternatives:m}})}))}function rfe(n,e,t){const r=[],i=ot(e,s=>s.name);return At(n,s=>{const o=s.name;if(Qi(i,o)){const a=t.buildNamespaceConflictError(s);r.push({message:a,type:Ki.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:o})}}),r}function ife(n){const e=Qw(n,{errMsgProvider:Che}),t={};return At(n.rules,r=>{t[r.name]=r}),Rhe(t,e.errMsgProvider)}function sfe(n){return n=Qw(n,{errMsgProvider:Wu}),Whe(n.rules,n.tokenTypes,n.errMsgProvider,n.grammarName)}const w4="MismatchedTokenException",A4="NoViableAltException",M4="EarlyExitException",C4="NotAllInputParsedException",R4=[w4,A4,M4,C4];Object.freeze(R4);function Lv(n){return Qi(R4,n.name)}class cx extends Error{constructor(e,t){super(e),this.token=t,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class k4 extends cx{constructor(e,t,r){super(e,t),this.previousToken=r,this.name=w4}}class ofe extends cx{constructor(e,t,r){super(e,t),this.previousToken=r,this.name=A4}}class afe extends cx{constructor(e,t){super(e,t),this.name=C4}}class cfe extends cx{constructor(e,t,r){super(e,t),this.previousToken=r,this.name=M4}}const B1={},N4="InRuleRecoveryException";class lfe extends Error{constructor(e){super(e),this.name=N4}}class ufe{initRecoverable(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=Tt(e,"recoveryEnabled")?e.recoveryEnabled:$c.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=hfe)}getTokenToInsert(e){const t=Ym(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return t.isInsertedInRecovery=!0,t}canTokenTypeBeInsertedInRecovery(e){return!0}canTokenTypeBeDeletedInRecovery(e){return!0}tryInRepetitionRecovery(e,t,r,i){const s=this.findReSyncTokenType(),o=this.exportLexerState(),a=[];let c=!1;const l=this.LA(1);let u=this.LA(1);const h=()=>{const d=this.LA(0),m=this.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:l,previous:d,ruleName:this.getCurrRuleFullName()}),g=new k4(m,l,this.LA(0));g.resyncedTokens=Zp(a),this.SAVE_ERROR(g)};for(;!c;)if(this.tokenMatcher(u,i)){h();return}else if(r.call(this)){h(),e.apply(this,t);return}else this.tokenMatcher(u,s)?c=!0:(u=this.SKIP_TOKEN(),this.addToResyncTokens(u,a));this.importLexerState(o)}shouldInRepetitionRecoveryBeTried(e,t,r){return!(r===!1||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,t)))}getFollowsForInRuleRecovery(e,t){const r=this.getCurrentGrammarPath(e,t);return this.getNextPossibleTokenTypes(r)}tryInRuleRecovery(e,t){if(this.canRecoverWithSingleTokenInsertion(e,t))return this.getTokenToInsert(e);if(this.canRecoverWithSingleTokenDeletion(e)){const r=this.SKIP_TOKEN();return this.consumeToken(),r}throw new lfe("sad sad panda")}canPerformInRuleRecovery(e,t){return this.canRecoverWithSingleTokenInsertion(e,t)||this.canRecoverWithSingleTokenDeletion(e)}canRecoverWithSingleTokenInsertion(e,t){if(!this.canTokenTypeBeInsertedInRecovery(e)||zn(t))return!1;const r=this.LA(1);return sd(t,s=>this.tokenMatcher(r,s))!==void 0}canRecoverWithSingleTokenDeletion(e){return this.canTokenTypeBeDeletedInRecovery(e)?this.tokenMatcher(this.LA(2),e):!1}isInCurrentRuleReSyncSet(e){const t=this.getCurrFollowKey(),r=this.getFollowSetFromFollowKey(t);return Qi(r,e)}findReSyncTokenType(){const e=this.flattenFollowSet();let t=this.LA(1),r=2;for(;;){const i=sd(e,s=>Mhe(t,s));if(i!==void 0)return i;t=this.LA(r),r++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return B1;const e=this.getLastExplicitRuleShortName(),t=this.getLastExplicitRuleOccurrenceIndex(),r=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:t,inRule:this.shortRuleNameToFullName(r)}}buildFullFollowKeyStack(){const e=this.RULE_STACK,t=this.RULE_OCCURRENCE_STACK;return ot(e,(r,i)=>i===0?B1:{ruleName:this.shortRuleNameToFullName(r),idxInCallingRule:t[i],inRule:this.shortRuleNameToFullName(e[i-1])})}flattenFollowSet(){const e=ot(this.buildFullFollowKeyStack(),t=>this.getFollowSetFromFollowKey(t));return gs(e)}getFollowSetFromFollowKey(e){if(e===B1)return[fh];const t=e.ruleName+e.idxInCallingRule+a4+e.inRule;return this.resyncFollows[t]}addToResyncTokens(e,t){return this.tokenMatcher(e,fh)||t.push(e),t}reSyncTo(e){const t=[];let r=this.LA(1);for(;this.tokenMatcher(r,e)===!1;)r=this.SKIP_TOKEN(),this.addToResyncTokens(r,t);return Zp(t)}attemptInRepetitionRecovery(e,t,r,i,s,o,a){}getCurrentGrammarPath(e,t){const r=this.getHumanReadableRuleStack(),i=mi(this.RULE_OCCURRENCE_STACK);return{ruleStack:r,occurrenceStack:i,lastTok:e,lastTokOccurrence:t}}getHumanReadableRuleStack(){return ot(this.RULE_STACK,e=>this.shortRuleNameToFullName(e))}}function hfe(n,e,t,r,i,s,o){const a=this.getKeyForAutomaticLookahead(r,i);let c=this.firstAfterRepMap[a];if(c===void 0){const d=this.getCurrRuleFullName(),m=this.getGAstProductions()[d];c=new s(m,i).startWalking(),this.firstAfterRepMap[a]=c}let l=c.token,u=c.occurrence;const h=c.isEndOfRule;this.RULE_STACK.length===1&&h&&l===void 0&&(l=fh,u=1),!(l===void 0||u===void 0)&&this.shouldInRepetitionRecoveryBeTried(l,u,o)&&this.tryInRepetitionRecovery(n,e,t,l)}const ffe=4,su=8,I4=1<T4(t,t,Wu))}validateEmptyOrAlternatives(e){return uo(e,t=>Yhe(t,Wu))}validateAmbiguousAlternationAlternatives(e,t){return uo(e,r=>Zhe(r,t,Wu))}validateSomeNonEmptyLookaheadPath(e,t){return efe(e,t,Wu)}buildLookaheadForAlternation(e){return Dhe(e.prodOccurrence,e.rule,e.maxLookahead,e.hasPredicates,e.dynamicTokensEnabled,Fhe)}buildLookaheadForOptional(e){return Uhe(e.prodOccurrence,e.rule,e.maxLookahead,e.dynamicTokensEnabled,y4(e.prodType),Bhe)}}class pfe{initLooksAhead(e){this.dynamicTokensEnabled=Tt(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:$c.dynamicTokensEnabled,this.maxLookahead=Tt(e,"maxLookahead")?e.maxLookahead:$c.maxLookahead,this.lookaheadStrategy=Tt(e,"lookaheadStrategy")?e.lookaheadStrategy:new dfe({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(e){At(e,t=>{this.TRACE_INIT(`${t.name} Rule Lookahead`,()=>{const{alternation:r,repetition:i,option:s,repetitionMandatory:o,repetitionMandatoryWithSeparator:a,repetitionWithSeparator:c}=gfe(t);At(r,l=>{const u=l.idx===0?"":l.idx;this.TRACE_INIT(`${Ea(l)}${u}`,()=>{const h=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:l.idx,rule:t,maxLookahead:l.maxLookahead||this.maxLookahead,hasPredicates:l.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),d=z1(this.fullRuleNameToShort[t.name],I4,l.idx);this.setLaFuncCache(d,h)})}),At(i,l=>{this.computeLookaheadFunc(t,l.idx,qb,"Repetition",l.maxLookahead,Ea(l))}),At(s,l=>{this.computeLookaheadFunc(t,l.idx,O4,"Option",l.maxLookahead,Ea(l))}),At(o,l=>{this.computeLookaheadFunc(t,l.idx,Xb,"RepetitionMandatory",l.maxLookahead,Ea(l))}),At(a,l=>{this.computeLookaheadFunc(t,l.idx,U_,"RepetitionMandatoryWithSeparator",l.maxLookahead,Ea(l))}),At(c,l=>{this.computeLookaheadFunc(t,l.idx,Kb,"RepetitionWithSeparator",l.maxLookahead,Ea(l))})})})}computeLookaheadFunc(e,t,r,i,s,o){this.TRACE_INIT(`${o}${t===0?"":t}`,()=>{const a=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:t,rule:e,maxLookahead:s||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:i}),c=z1(this.fullRuleNameToShort[e.name],r,t);this.setLaFuncCache(c,a)})}getKeyForAutomaticLookahead(e,t){const r=this.getLastExplicitRuleShortName();return z1(r,e,t)}getLaFuncFromCache(e){return this.lookAheadFuncsCache.get(e)}setLaFuncCache(e,t){this.lookAheadFuncsCache.set(e,t)}}class mfe extends Ah{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(e){this.dslMethods.option.push(e)}visitRepetitionWithSeparator(e){this.dslMethods.repetitionWithSeparator.push(e)}visitRepetitionMandatory(e){this.dslMethods.repetitionMandatory.push(e)}visitRepetitionMandatoryWithSeparator(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)}visitRepetition(e){this.dslMethods.repetition.push(e)}visitAlternation(e){this.dslMethods.alternation.push(e)}}const Y0=new mfe;function gfe(n){Y0.reset(),n.accept(Y0);const e=Y0.dslMethods;return Y0.reset(),e}function vI(n,e){isNaN(n.startOffset)===!0?(n.startOffset=e.startOffset,n.endOffset=e.endOffset):n.endOffseto.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: + ${s.join(` + +`).replace(/\n/g,` + `)}`)}}};return t.prototype=r,t.prototype.constructor=t,t._RULE_NAMES=e,t}function Efe(n,e,t){const r=function(){};L4(r,n+"BaseSemanticsWithDefaults");const i=Object.create(t.prototype);return At(e,s=>{i[s]=xfe}),r.prototype=i,r.prototype.constructor=r,r}var Yb;(function(n){n[n.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",n[n.MISSING_METHOD=1]="MISSING_METHOD"})(Yb||(Yb={}));function bfe(n,e){return Tfe(n,e)}function Tfe(n,e){const t=yo(e,i=>Qc(n[i])===!1),r=ot(t,i=>({msg:`Missing visitor method: <${i}> on ${n.constructor.name} CST Visitor.`,type:Yb.MISSING_METHOD,methodName:i}));return Am(r)}class wfe{initTreeBuilder(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=Tt(e,"nodeLocationTracking")?e.nodeLocationTracking:$c.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=Fr,this.cstFinallyStateUpdate=Fr,this.cstPostTerminal=Fr,this.cstPostNonTerminal=Fr,this.cstPostRule=Fr;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=yI,this.setNodeLocationFromNode=yI,this.cstPostRule=Fr,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=Fr,this.setNodeLocationFromNode=Fr,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=vI,this.setNodeLocationFromNode=vI,this.cstPostRule=Fr,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=Fr,this.setNodeLocationFromNode=Fr,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=Fr,this.setNodeLocationFromNode=Fr,this.cstPostRule=Fr,this.setInitialNodeLocation=Fr;else throw Error(`Invalid config option: "${e.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(e){e.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(e){const t=this.LA(1);e.location={startOffset:t.startOffset,startLine:t.startLine,startColumn:t.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(e){const t={name:e,children:Object.create(null)};this.setInitialNodeLocation(t),this.CST_STACK.push(t)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(e){const t=this.LA(0),r=e.location;r.startOffset<=t.startOffset?(r.endOffset=t.endOffset,r.endLine=t.endLine,r.endColumn=t.endColumn):(r.startOffset=NaN,r.startLine=NaN,r.startColumn=NaN)}cstPostRuleOnlyOffset(e){const t=this.LA(0),r=e.location;r.startOffset<=t.startOffset?r.endOffset=t.endOffset:r.startOffset=NaN}cstPostTerminal(e,t){const r=this.CST_STACK[this.CST_STACK.length-1];_fe(r,t,e),this.setNodeLocationFromToken(r.location,t)}cstPostNonTerminal(e,t){const r=this.CST_STACK[this.CST_STACK.length-1];vfe(r,t,e),this.setNodeLocationFromNode(r.location,e.location)}getBaseCstVisitorConstructor(){if(Wc(this.baseCstVisitorConstructor)){const e=Sfe(this.className,vo(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(Wc(this.baseCstVisitorWithDefaultsConstructor)){const e=Efe(this.className,vo(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){const e=this.RULE_STACK;return e[e.length-1]}getPreviousExplicitRuleShortName(){const e=this.RULE_STACK;return e[e.length-2]}getLastExplicitRuleOccurrenceIndex(){const e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]}}class Afe{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(e){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):Dv}LA(e){const t=this.currIdx+e;return t<0||this.tokVectorLength<=t?Dv:this.tokVector[t]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(e){this.currIdx=e}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}}class Mfe{ACTION(e){return e.call(this)}consume(e,t,r){return this.consumeInternal(t,e,r)}subrule(e,t,r){return this.subruleInternal(t,e,r)}option(e,t){return this.optionInternal(t,e)}or(e,t){return this.orInternal(t,e)}many(e,t){return this.manyInternal(e,t)}atLeastOne(e,t){return this.atLeastOneInternal(e,t)}CONSUME(e,t){return this.consumeInternal(e,0,t)}CONSUME1(e,t){return this.consumeInternal(e,1,t)}CONSUME2(e,t){return this.consumeInternal(e,2,t)}CONSUME3(e,t){return this.consumeInternal(e,3,t)}CONSUME4(e,t){return this.consumeInternal(e,4,t)}CONSUME5(e,t){return this.consumeInternal(e,5,t)}CONSUME6(e,t){return this.consumeInternal(e,6,t)}CONSUME7(e,t){return this.consumeInternal(e,7,t)}CONSUME8(e,t){return this.consumeInternal(e,8,t)}CONSUME9(e,t){return this.consumeInternal(e,9,t)}SUBRULE(e,t){return this.subruleInternal(e,0,t)}SUBRULE1(e,t){return this.subruleInternal(e,1,t)}SUBRULE2(e,t){return this.subruleInternal(e,2,t)}SUBRULE3(e,t){return this.subruleInternal(e,3,t)}SUBRULE4(e,t){return this.subruleInternal(e,4,t)}SUBRULE5(e,t){return this.subruleInternal(e,5,t)}SUBRULE6(e,t){return this.subruleInternal(e,6,t)}SUBRULE7(e,t){return this.subruleInternal(e,7,t)}SUBRULE8(e,t){return this.subruleInternal(e,8,t)}SUBRULE9(e,t){return this.subruleInternal(e,9,t)}OPTION(e){return this.optionInternal(e,0)}OPTION1(e){return this.optionInternal(e,1)}OPTION2(e){return this.optionInternal(e,2)}OPTION3(e){return this.optionInternal(e,3)}OPTION4(e){return this.optionInternal(e,4)}OPTION5(e){return this.optionInternal(e,5)}OPTION6(e){return this.optionInternal(e,6)}OPTION7(e){return this.optionInternal(e,7)}OPTION8(e){return this.optionInternal(e,8)}OPTION9(e){return this.optionInternal(e,9)}OR(e){return this.orInternal(e,0)}OR1(e){return this.orInternal(e,1)}OR2(e){return this.orInternal(e,2)}OR3(e){return this.orInternal(e,3)}OR4(e){return this.orInternal(e,4)}OR5(e){return this.orInternal(e,5)}OR6(e){return this.orInternal(e,6)}OR7(e){return this.orInternal(e,7)}OR8(e){return this.orInternal(e,8)}OR9(e){return this.orInternal(e,9)}MANY(e){this.manyInternal(0,e)}MANY1(e){this.manyInternal(1,e)}MANY2(e){this.manyInternal(2,e)}MANY3(e){this.manyInternal(3,e)}MANY4(e){this.manyInternal(4,e)}MANY5(e){this.manyInternal(5,e)}MANY6(e){this.manyInternal(6,e)}MANY7(e){this.manyInternal(7,e)}MANY8(e){this.manyInternal(8,e)}MANY9(e){this.manyInternal(9,e)}MANY_SEP(e){this.manySepFirstInternal(0,e)}MANY_SEP1(e){this.manySepFirstInternal(1,e)}MANY_SEP2(e){this.manySepFirstInternal(2,e)}MANY_SEP3(e){this.manySepFirstInternal(3,e)}MANY_SEP4(e){this.manySepFirstInternal(4,e)}MANY_SEP5(e){this.manySepFirstInternal(5,e)}MANY_SEP6(e){this.manySepFirstInternal(6,e)}MANY_SEP7(e){this.manySepFirstInternal(7,e)}MANY_SEP8(e){this.manySepFirstInternal(8,e)}MANY_SEP9(e){this.manySepFirstInternal(9,e)}AT_LEAST_ONE(e){this.atLeastOneInternal(0,e)}AT_LEAST_ONE1(e){return this.atLeastOneInternal(1,e)}AT_LEAST_ONE2(e){this.atLeastOneInternal(2,e)}AT_LEAST_ONE3(e){this.atLeastOneInternal(3,e)}AT_LEAST_ONE4(e){this.atLeastOneInternal(4,e)}AT_LEAST_ONE5(e){this.atLeastOneInternal(5,e)}AT_LEAST_ONE6(e){this.atLeastOneInternal(6,e)}AT_LEAST_ONE7(e){this.atLeastOneInternal(7,e)}AT_LEAST_ONE8(e){this.atLeastOneInternal(8,e)}AT_LEAST_ONE9(e){this.atLeastOneInternal(9,e)}AT_LEAST_ONE_SEP(e){this.atLeastOneSepFirstInternal(0,e)}AT_LEAST_ONE_SEP1(e){this.atLeastOneSepFirstInternal(1,e)}AT_LEAST_ONE_SEP2(e){this.atLeastOneSepFirstInternal(2,e)}AT_LEAST_ONE_SEP3(e){this.atLeastOneSepFirstInternal(3,e)}AT_LEAST_ONE_SEP4(e){this.atLeastOneSepFirstInternal(4,e)}AT_LEAST_ONE_SEP5(e){this.atLeastOneSepFirstInternal(5,e)}AT_LEAST_ONE_SEP6(e){this.atLeastOneSepFirstInternal(6,e)}AT_LEAST_ONE_SEP7(e){this.atLeastOneSepFirstInternal(7,e)}AT_LEAST_ONE_SEP8(e){this.atLeastOneSepFirstInternal(8,e)}AT_LEAST_ONE_SEP9(e){this.atLeastOneSepFirstInternal(9,e)}RULE(e,t,r=Uv){if(Qi(this.definedRulesNames,e)){const o={message:Wu.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),type:Ki.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(o)}this.definedRulesNames.push(e);const i=this.defineRule(e,t,r);return this[e]=i,i}OVERRIDE_RULE(e,t,r=Uv){const i=Khe(e,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(i);const s=this.defineRule(e,t,r);return this[e]=s,s}BACKTRACK(e,t){return function(){this.isBackTrackingStack.push(1);const r=this.saveRecogState();try{return e.apply(this,t),!0}catch(i){if(Lv(i))return!1;throw i}finally{this.reloadRecogState(r),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return Rue(Lr(this.gastProductionsCache))}}class Cfe{initRecognizerEngine(e,t){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=Ov,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},Tt(t,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 + For Further details.`);if(fn(e)){if(zn(e))throw Error(`A Token Vocabulary cannot be empty. + Note that the first argument for the parser constructor + is no longer a Token vector (since v4.0).`);if(typeof e[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 + For Further details.`)}if(fn(e))this.tokensMap=Ss(e,(s,o)=>(s[o.name]=o,s),{});else if(Tt(e,"modes")&&Uo(gs(Lr(e.modes)),bhe)){const s=gs(Lr(e.modes)),o=Ry(s);this.tokensMap=Ss(o,(a,c)=>(a[c.name]=c,a),{})}else if(_o(e))this.tokensMap=mi(e);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=fh;const r=Tt(e,"modes")?gs(Lr(e.modes)):Lr(e),i=Uo(r,s=>zn(s.categoryMatches));this.tokenMatcher=i?Ov:Xm,Km(Lr(this.tokensMap))}defineRule(e,t,r){if(this.selfAnalysisDone)throw Error(`Grammar rule <${e}> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);const i=Tt(r,"resyncEnabled")?r.resyncEnabled:Uv.resyncEnabled,s=Tt(r,"recoveryValueFunc")?r.recoveryValueFunc:Uv.recoveryValueFunc,o=this.ruleShortNameIdx<o.call(this)&&a.call(this)}}else s=e;if(i.call(this)===!0)return s.call(this)}atLeastOneInternal(e,t){const r=this.getKeyForAutomaticLookahead(Xb,e);return this.atLeastOneInternalLogic(e,t,r)}atLeastOneInternalLogic(e,t,r){let i=this.getLaFuncFromCache(r),s;if(typeof t!="function"){s=t.DEF;const o=t.GATE;if(o!==void 0){const a=i;i=()=>o.call(this)&&a.call(this)}}else s=t;if(i.call(this)===!0){let o=this.doSingleRepetition(s);for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s)}else throw this.raiseEarlyExitException(e,cr.REPETITION_MANDATORY,t.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[e,t],i,Xb,e,Lhe)}atLeastOneSepFirstInternal(e,t){const r=this.getKeyForAutomaticLookahead(U_,e);this.atLeastOneSepFirstInternalLogic(e,t,r)}atLeastOneSepFirstInternalLogic(e,t,r){const i=t.DEF,s=t.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,a,i,gI],a,U_,e,gI)}else throw this.raiseEarlyExitException(e,cr.REPETITION_MANDATORY_WITH_SEPARATOR,t.ERR_MSG)}manyInternal(e,t){const r=this.getKeyForAutomaticLookahead(qb,e);return this.manyInternalLogic(e,t,r)}manyInternalLogic(e,t,r){let i=this.getLaFuncFromCache(r),s;if(typeof t!="function"){s=t.DEF;const a=t.GATE;if(a!==void 0){const c=i;i=()=>a.call(this)&&c.call(this)}}else s=t;let o=!0;for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s);this.attemptInRepetitionRecovery(this.manyInternal,[e,t],i,qb,e,Ohe,o)}manySepFirstInternal(e,t){const r=this.getKeyForAutomaticLookahead(Kb,e);this.manySepFirstInternalLogic(e,t,r)}manySepFirstInternalLogic(e,t,r){const i=t.DEF,s=t.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,a,i,mI],a,Kb,e,mI)}}repetitionSepSecondInternal(e,t,r,i,s){for(;r();)this.CONSUME(t),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,t,r,i,s],r,U_,e,s)}doSingleRepetition(e){const t=this.getLexerPosition();return e.call(this),this.getLexerPosition()>t}orInternal(e,t){const r=this.getKeyForAutomaticLookahead(I4,t),i=fn(e)?e:e.DEF,o=this.getLaFuncFromCache(r).call(this,i);if(o!==void 0)return i[o].ALT.call(this);this.raiseNoAltException(t,e.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){const e=this.LA(1),t=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new afe(t,e))}}subruleInternal(e,t,r){let i;try{const s=r!==void 0?r.ARGS:void 0;return this.subruleIdx=t,i=e.apply(this,s),this.cstPostNonTerminal(i,r!==void 0&&r.LABEL!==void 0?r.LABEL:e.ruleName),i}catch(s){throw this.subruleInternalError(s,r,e.ruleName)}}subruleInternalError(e,t,r){throw Lv(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,t!==void 0&&t.LABEL!==void 0?t.LABEL:r),delete e.partialCstResult),e}consumeInternal(e,t,r){let i;try{const s=this.LA(1);this.tokenMatcher(s,e)===!0?(this.consumeToken(),i=s):this.consumeInternalError(e,s,r)}catch(s){i=this.consumeInternalRecovery(e,t,s)}return this.cstPostTerminal(r!==void 0&&r.LABEL!==void 0?r.LABEL:e.name,i),i}consumeInternalError(e,t,r){let i;const s=this.LA(0);throw r!==void 0&&r.ERR_MSG?i=r.ERR_MSG:i=this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:t,previous:s,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new k4(i,t,s))}consumeInternalRecovery(e,t,r){if(this.recoveryEnabled&&r.name==="MismatchedTokenException"&&!this.isBackTracking()){const i=this.getFollowsForInRuleRecovery(e,t);try{return this.tryInRuleRecovery(e,i)}catch(s){throw s.name===N4?r:s}}else throw r}saveRecogState(){const e=this.errors,t=mi(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:t,CST_STACK:this.CST_STACK}}reloadRecogState(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK}ruleInvocationStateUpdate(e,t,r){this.RULE_OCCURRENCE_STACK.push(r),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(t)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){const e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]}shortRuleNameToFullName(e){return this.shortRuleNameToFull[e]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),fh)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}}class Rfe{initErrorHandler(e){this._errors=[],this.errorMessageProvider=Tt(e,"errorMessageProvider")?e.errorMessageProvider:$c.errorMessageProvider}SAVE_ERROR(e){if(Lv(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:mi(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return mi(this._errors)}set errors(e){this._errors=e}raiseEarlyExitException(e,t,r){const i=this.getCurrRuleFullName(),s=this.getGAstProductions()[i],a=nM(e,s,t,this.maxLookahead)[0],c=[];for(let u=1;u<=this.maxLookahead;u++)c.push(this.LA(u));const l=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:c,previous:this.LA(0),customUserDescription:r,ruleName:i});throw this.SAVE_ERROR(new cfe(l,this.LA(1),this.LA(0)))}raiseNoAltException(e,t){const r=this.getCurrRuleFullName(),i=this.getGAstProductions()[r],s=tM(e,i,this.maxLookahead),o=[];for(let l=1;l<=this.maxLookahead;l++)o.push(this.LA(l));const a=this.LA(0),c=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:s,actual:o,previous:a,customUserDescription:t,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new ofe(c,this.LA(1),a))}}class kfe{initContentAssist(){}computeContentAssist(e,t){const r=this.gastProductionsCache[e];if(Wc(r))throw Error(`Rule ->${e}<- does not exist in this grammar.`);return v4([r],t,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(e){const t=Vo(e.ruleStack),i=this.getGAstProductions()[t];return new Ihe(i,e).startWalking()}}const lx={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(lx);const xI=!0,SI=Math.pow(2,su)-1,P4=Ws({name:"RECORDING_PHASE_TOKEN",pattern:Wr.NA});Km([P4]);const D4=Ym(P4,`This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(D4);const Nfe={name:`This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}};class Ife{initGastRecorder(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let e=0;e<10;e++){const t=e>0?e:"";this[`CONSUME${t}`]=function(r,i){return this.consumeInternalRecord(r,e,i)},this[`SUBRULE${t}`]=function(r,i){return this.subruleInternalRecord(r,e,i)},this[`OPTION${t}`]=function(r){return this.optionInternalRecord(r,e)},this[`OR${t}`]=function(r){return this.orInternalRecord(r,e)},this[`MANY${t}`]=function(r){this.manyInternalRecord(e,r)},this[`MANY_SEP${t}`]=function(r){this.manySepFirstInternalRecord(e,r)},this[`AT_LEAST_ONE${t}`]=function(r){this.atLeastOneInternalRecord(e,r)},this[`AT_LEAST_ONE_SEP${t}`]=function(r){this.atLeastOneSepFirstInternalRecord(e,r)}}this.consume=function(e,t,r){return this.consumeInternalRecord(t,e,r)},this.subrule=function(e,t,r){return this.subruleInternalRecord(t,e,r)},this.option=function(e,t){return this.optionInternalRecord(t,e)},this.or=function(e,t){return this.orInternalRecord(t,e)},this.many=function(e,t){this.manyInternalRecord(e,t)},this.atLeastOne=function(e,t){this.atLeastOneInternalRecord(e,t)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{const e=this;for(let t=0;t<10;t++){const r=t>0?t:"";delete e[`CONSUME${r}`],delete e[`SUBRULE${r}`],delete e[`OPTION${r}`],delete e[`OR${r}`],delete e[`MANY${r}`],delete e[`MANY_SEP${r}`],delete e[`AT_LEAST_ONE${r}`],delete e[`AT_LEAST_ONE_SEP${r}`]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA})}ACTION_RECORD(e){}BACKTRACK_RECORD(e,t){return()=>!0}LA_RECORD(e){return Dv}topLevelRuleRecord(e,t){try{const r=new kd({definition:[],name:e});return r.name=e,this.recordingProdStack.push(r),t.call(this),this.recordingProdStack.pop(),r}catch(r){if(r.KNOWN_RECORDER_ERROR!==!0)try{r.message=r.message+` + This error was thrown during the "grammar recording phase" For more info see: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw r}throw r}}optionInternalRecord(e,t){return cp.call(this,vs,e,t)}atLeastOneInternalRecord(e,t){cp.call(this,ec,t,e)}atLeastOneSepFirstInternalRecord(e,t){cp.call(this,tc,t,e,xI)}manyInternalRecord(e,t){cp.call(this,Vr,t,e)}manySepFirstInternalRecord(e,t){cp.call(this,Zo,t,e,xI)}orInternalRecord(e,t){return Ofe.call(this,e,t)}subruleInternalRecord(e,t,r){if(Pv(t),!e||Tt(e,"ruleName")===!1){const a=new Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw a.KNOWN_RECORDER_ERROR=!0,a}const i=id(this.recordingProdStack),s=e.ruleName,o=new Ts({idx:t,nonTerminalName:s,label:r==null?void 0:r.LABEL,referencedRule:void 0});return i.definition.push(o),this.outputCst?Nfe:lx}consumeInternalRecord(e,t,r){if(Pv(t),!m4(e)){const o=new Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw o.KNOWN_RECORDER_ERROR=!0,o}const i=id(this.recordingProdStack),s=new tr({idx:t,terminalType:e,label:r==null?void 0:r.LABEL});return i.definition.push(s),D4}}function cp(n,e,t,r=!1){Pv(t);const i=id(this.recordingProdStack),s=Qc(e)?e:e.DEF,o=new n({definition:[],idx:t});return r&&(o.separator=e.SEP),Tt(e,"MAX_LOOKAHEAD")&&(o.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(o),s.call(this),i.definition.push(o),this.recordingProdStack.pop(),lx}function Ofe(n,e){Pv(e);const t=id(this.recordingProdStack),r=fn(n)===!1,i=r===!1?n:n.DEF,s=new Jo({definition:[],idx:e,ignoreAmbiguities:r&&n.IGNORE_AMBIGUITIES===!0});Tt(n,"MAX_LOOKAHEAD")&&(s.maxLookahead=n.MAX_LOOKAHEAD);const o=eA(i,a=>Qc(a.GATE));return s.hasPredicates=o,t.definition.push(s),At(i,a=>{const c=new ws({definition:[]});s.definition.push(c),Tt(a,"IGNORE_AMBIGUITIES")?c.ignoreAmbiguities=a.IGNORE_AMBIGUITIES:Tt(a,"GATE")&&(c.ignoreAmbiguities=!0),this.recordingProdStack.push(c),a.ALT.call(this),this.recordingProdStack.pop()}),lx}function EI(n){return n===0?"":`${n}`}function Pv(n){if(n<0||n>SI){const e=new Error(`Invalid DSL Method idx value: <${n}> + Idx value must be a none negative value smaller than ${SI+1}`);throw e.KNOWN_RECORDER_ERROR=!0,e}}class Lfe{initPerformanceTracer(e){if(Tt(e,"traceInitPerf")){const t=e.traceInitPerf,r=typeof t=="number";this.traceInitMaxIdent=r?t:1/0,this.traceInitPerf=r?t>0:t}else this.traceInitMaxIdent=0,this.traceInitPerf=$c.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(e,t){if(this.traceInitPerf===!0){this.traceInitIndent++;const r=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${e}>`);const{time:i,value:s}=s4(t),o=i>10?console.warn:console.log;return this.traceInitIndent time: ${i}ms`),this.traceInitIndent--,s}else return t()}}function Pfe(n,e){e.forEach(t=>{const r=t.prototype;Object.getOwnPropertyNames(r).forEach(i=>{if(i==="constructor")return;const s=Object.getOwnPropertyDescriptor(r,i);s&&(s.get||s.set)?Object.defineProperty(n.prototype,i,s):n.prototype[i]=t.prototype[i]})})}const Dv=Ym(fh,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(Dv);const $c=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:_4,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),Uv=Object.freeze({recoveryValueFunc:()=>{},resyncEnabled:!0});var Ki;(function(n){n[n.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",n[n.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",n[n.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",n[n.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",n[n.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",n[n.LEFT_RECURSION=5]="LEFT_RECURSION",n[n.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",n[n.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",n[n.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",n[n.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",n[n.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",n[n.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",n[n.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",n[n.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(Ki||(Ki={}));class Zm{static performSelfAnalysis(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let e;this.selfAnalysisDone=!0;const t=this.className;this.TRACE_INIT("toFastProps",()=>{o4(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),At(this.definedRulesNames,i=>{const o=this[i].originalGrammarAction;let a;this.TRACE_INIT(`${i} Rule`,()=>{a=this.topLevelRuleRecord(i,o)}),this.gastProductionsCache[i]=a})}finally{this.disableRecording()}});let r=[];if(this.TRACE_INIT("Grammar Resolving",()=>{r=ife({rules:Lr(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(r)}),this.TRACE_INIT("Grammar Validations",()=>{if(zn(r)&&this.skipValidations===!1){const i=sfe({rules:Lr(this.gastProductionsCache),tokenTypes:Lr(this.tokensMap),errMsgProvider:Wu,grammarName:t}),s=Ghe({lookaheadStrategy:this.lookaheadStrategy,rules:Lr(this.gastProductionsCache),tokenTypes:Lr(this.tokensMap),grammarName:t});this.definitionErrors=this.definitionErrors.concat(i,s)}}),zn(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{const i=Due(Lr(this.gastProductionsCache));this.resyncFollows=i}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var i,s;(s=(i=this.lookaheadStrategy).initialize)===null||s===void 0||s.call(i,{rules:Lr(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(Lr(this.gastProductionsCache))})),!Zm.DEFER_DEFINITION_ERRORS_HANDLING&&!zn(this.definitionErrors))throw e=ot(this.definitionErrors,i=>i.message),new Error(`Parser Definition Errors detected: + ${e.join(` +------------------------------- +`)}`)})}constructor(e,t){this.definitionErrors=[],this.selfAnalysisDone=!1;const r=this;if(r.initErrorHandler(t),r.initLexerAdapter(),r.initLooksAhead(t),r.initRecognizerEngine(e,t),r.initRecoverable(t),r.initTreeBuilder(t),r.initContentAssist(),r.initGastRecorder(t),r.initPerformanceTracer(t),Tt(t,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. + Please use the flag on the relevant DSL method instead. + See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES + For further details.`);this.skipValidations=Tt(t,"skipValidations")?t.skipValidations:$c.skipValidations}}Zm.DEFER_DEFINITION_ERRORS_HANDLING=!1;Pfe(Zm,[ufe,pfe,wfe,Afe,Cfe,Mfe,Rfe,kfe,Ife,Lfe]);class Dfe extends Zm{constructor(e,t=$c){const r=mi(t);r.outputCst=!0,super(e,r)}}function Ufe(n){const e=new Ffe,t=Lr(n);return ot(t,r=>e.visitRule(r))}class Ffe extends Ah{visitRule(e){const t=this.visitEach(e.definition),r=xU(t,s=>s.propertyName),i=ot(r,(s,o)=>{const a=!eA(s,l=>!l.canBeNull);let c=s[0].type;return s.length>1&&(c=ot(s,l=>l.type)),{name:o,type:c,optional:a}});return{name:e.name,properties:i}}visitAlternative(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitOption(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitRepetition(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitRepetitionMandatory(e){return this.visitEach(e.definition)}visitRepetitionMandatoryWithSeparator(e){return this.visitEach(e.definition).concat({propertyName:e.separator.name,canBeNull:!0,type:Z0(e.separator)})}visitRepetitionWithSeparator(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0}).concat({propertyName:e.separator.name,canBeNull:!0,type:Z0(e.separator)})}visitAlternation(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitTerminal(e){return[{propertyName:e.label||e.terminalType.name,canBeNull:!1,type:Z0(e)}]}visitNonTerminal(e){return[{propertyName:e.label||e.nonTerminalName,canBeNull:!1,type:Z0(e)}]}visitEachAndOverrideWith(e,t){return ot(this.visitEach(e),r=>ys({},r,t))}visitEach(e){return gs(ot(e,t=>this.visit(t)))}}function Z0(n){return n instanceof Ts?{kind:"rule",name:n.referencedRule.name}:{kind:"token"}}function Bfe(n,e){let t=[];return t=t.concat('import type { CstNode, ICstVisitor, IToken } from "chevrotain";'),t=t.concat(gs(ot(n,r=>zfe(r)))),e.includeVisitorInterface&&(t=t.concat(Wfe(e.visitorInterfaceName,n))),t.join(` + +`)+` +`}function zfe(n){const e=Vfe(n),t=Hfe(n);return[e,t]}function Vfe(n){const e=U4(n.name),t=iM(n.name);return`export interface ${e} extends CstNode { + name: "${n.name}"; + children: ${t}; +}`}function Hfe(n){return`export type ${iM(n.name)} = { + ${ot(n.properties,t=>Gfe(t)).join(` + `)} +};`}function Gfe(n){const e=$fe(n.type);return`${n.name}${n.optional?"?":""}: ${e}[];`}function Wfe(n,e){return`export interface ${n} extends ICstVisitor { + ${ot(e,t=>jfe(t)).join(` + `)} +}`}function jfe(n){const e=iM(n.name);return`${n.name}(children: ${e}, param?: IN): OUT;`}function $fe(n){if(fn(n)){const e=Ry(ot(n,r=>bI(r)));return"("+Ss(e,(r,i)=>r+" | "+i)+")"}else return bI(n)}function bI(n){return n.kind==="token"?"IToken":U4(n.name)}function U4(n){return oU(n)+"CstNode"}function iM(n){return oU(n)+"CstChildren"}const qfe={includeVisitorInterface:!0,visitorInterfaceName:"ICstNodeVisitor"};function Xfe(n,e){const t=Object.assign(Object.assign({},qfe),e),r=Ufe(n);return Bfe(r,t)}var F4={exports:{}},V1={exports:{}},TI;function Kfe(){return TI||(TI=1,function(n,e){(function(t,r){n.exports=r()})(No,function(){function t(v){return!isNaN(parseFloat(v))&&isFinite(v)}function r(v){return v.charAt(0).toUpperCase()+v.substring(1)}function i(v){return function(){return this[v]}}var s=["isConstructor","isEval","isNative","isToplevel"],o=["columnNumber","lineNumber"],a=["fileName","functionName","source"],c=["args"],l=["evalOrigin"],u=s.concat(o,a,c,l);function h(v){if(v)for(var y=0;y-1&&(u=u.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var h=u.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),d=h.match(/ (\(.+\)$)/);h=d?h.replace(d[0],""):h;var m=this.extractLocation(d?d[1]:h),g=d&&h||void 0,v=["eval",""].indexOf(m[0])>-1?void 0:m[0];return new r({functionName:g,fileName:v,lineNumber:m[1],columnNumber:m[2],source:u})},this)},parseFFOrSafari:function(c){var l=c.stack.split(` +`).filter(function(u){return!u.match(o)},this);return l.map(function(u){if(u.indexOf(" > eval")>-1&&(u=u.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),u.indexOf("@")===-1&&u.indexOf(":")===-1)return new r({functionName:u});var h=/((.*".+"[^@]*)?[^@]*)(?:@)/,d=u.match(h),m=d&&d[1]?d[1]:void 0,g=this.extractLocation(u.replace(h,""));return new r({functionName:m,fileName:g[0],lineNumber:g[1],columnNumber:g[2],source:u})},this)},parseOpera:function(c){return!c.stacktrace||c.message.indexOf(` +`)>-1&&c.message.split(` +`).length>c.stacktrace.split(` +`).length?this.parseOpera9(c):c.stack?this.parseOpera11(c):this.parseOpera10(c)},parseOpera9:function(c){for(var l=/Line (\d+).*script (?:in )?(\S+)/i,u=c.message.split(` +`),h=[],d=2,m=u.length;d/,"$2").replace(/\([^)]*\)/g,"")||void 0,v;m.match(/\(([^)]*)\)/)&&(v=m.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var y=v===void 0||v==="[arguments not available]"?void 0:v.split(",");return new r({functionName:g,args:y,fileName:d[0],lineNumber:d[1],columnNumber:d[2],source:u})},this)}}})})(F4);var Yfe=F4.exports;const Zfe=$a(Yfe);function al(n){const e={},t={get(){return[!1,void 0]},set(){return[!1,void 0]},tick(){},everytick(){},...n,getcommand(r){return e[r]},command(r,i){return e[r]=i,t}};return t}function Ic(n){return Z(n)&&Z(n.x)&&Z(n.y)}function ti(n,e){switch(e){case st.NORTH:--n.y;break;case st.SOUTH:++n.y;break;case st.WEST:--n.x;break;case st.EAST:++n.x;break}return n}function uf(n,e){const t=e.x-n.x,r=e.y-n.y;if(t<0)return st.WEST;if(t>0)return st.EAST;if(r<0)return st.NORTH;if(r>0)return st.SOUTH}const B4={idle:"IDLE",up:"NORTH",down:"SOUTH",left:"WEST",right:"EAST",by:"BY",at:"AT",flow:"FLOW",seek:"SEEK",rndns:"RNDNS",rndne:"RNDNE",rnd:"RND",cw:"CW",ccw:"CCW",opp:"OPP",rndp:"RNDP",i:"IDLE",u:"NORTH",north:"NORTH",n:"NORTH",d:"SOUTH",south:"SOUTH",s:"SOUTH",l:"WEST",west:"WEST",w:"WEST",r:"EAST",east:"EAST",e:"EAST",edit:"EDIT"};function Uc(n){return cn(n)&&z4(n[0])}function z4(n){return Z(st[n])&&Bt(n)}function Jfe(n){const e=st[n];return Z(e)?e:st.IDLE}function V4(n){if(Bt(n))return B4[Kt(n)]}function wI(n){if(Uc(n))return n;if(z4(n))return[n];const e=V4(n);if(Z(e))return[e]}function AI(n){const e=se.words[n],t=wI(e);if(Uc(t))return[t,n+1];const[r,i]=Hi(n),s=wI(r);return Uc(s)?[s,i]:[void 0,n]}function Zb(n){const e=[];let[t,r]=AI(n);for(;Uc(t);){if(e.push(...t),(t[0]==="AT"||t[0]==="BY")&&t.length<2){const[o,a,c]=Ve(se.words,r,[Ie.NUMBER,Ie.NUMBER]);e.push(o,a),r=c}const[i,s]=AI(r);t=i,r=s}return e.length?[e,r]:[void 0,n]}function dd(n){return cn(n)&&typeof n[0]=="string"}function MI(n){const e=se.words[n];if(dd(e))return[e,n+1];const[t,r]=Gv(n),[i,s]=Hi(r,!1);return Bt(i)?[[i,t],s]:[void 0,n]}function Fv(n){if(!dd(n))return;const[e]=n;return e}function H4(n){if(!dd(n))return;const[,e]=n,t=Z(e)?xme(e):void 0;return Z(t)?t:void 0}function G4(n){if(!dd(n))return;const[,e]=n,t=Z(e)?Sme(e):void 0;return Z(t)?t:void 0}const pi=60,Mh=25;var xn=(n=>(n[n.ERROR=0]="ERROR",n[n.LOADER=1]="LOADER",n[n.BOARD=2]="BOARD",n[n.OBJECT=3]="OBJECT",n[n.TERRAIN=4]="TERRAIN",n[n.CHARSET=5]="CHARSET",n[n.PALETTE=6]="PALETTE",n))(xn||{});function W4(n,e){const t=n??Gn.ISWALK,r=e??Gn.ISWALK;switch(t){case Gn.ISWALK:return r!==Gn.ISWALK;case Gn.ISSWIM:return r!==Gn.ISSWIM;case Gn.ISSOLID:return!0;case Gn.ISBULLET:return r!==Gn.ISWALK&&r!==Gn.ISSWIM}}function CI(n,e,t){const r=n==null?void 0:n.objects[t];if(Z(r))return r;if(Z(e)){const i=Jm(n,"player"),s={x:e.x??0,y:e.y??0};$4(s,i)}}function Jm(n,e){var r,i;return[...((i=(r=n==null?void 0:n.named)==null?void 0:r[e])==null?void 0:i.values())??[]].map(s=>typeof s=="string"?n==null?void 0:n.objects[s]:n==null?void 0:n.terrain[s]).filter(Z)}function j4(n,e){const t=Fv(e),r=H4(e),i=G4(e);return n.filter(s=>!(Z(t)&&cM(s)!==t||Z(r)&&yde(s)!==r||Z(i)&&xde(s)!==i)).filter(Z)}function H1(n,e){return Z(n)?e.map(t=>{var r;if(typeof t=="string"){const i=n.objects[t];if(Z(i))return i;const s=Jm(n,Kt(t));if(s.length)return s}else if(Ic(t)&&t.x>=0&&t.x=0&&t.y(eT(),this?this.unpack(e,t):rm.prototype.unpack.call(RI,e,t)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof t=="object"?(oo=t.end||e.length,ue=t.start||0):(ue=0,oo=t>-1?t:e.length),wa=0,Ol=null,si=null,We=e;try{tn=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw We=null,e instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof rm){if(Fn=this,this.structures)return an=this.structures,J0(t);(!an||an.length>0)&&(an=[])}else Fn=RI,(!an||an.length>0)&&(an=[]);return J0(t)}unpackMultiple(e,t){let r,i=0;try{Fl=!0;let s=e.length,o=this?this.unpack(e,s):ux.unpack(e,s);if(t){if(t(o,i,ue)===!1)return;for(;uer.slice(0)));for(let r=0,i=e.length;r=32&&(s.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in t||[])if(r>=0){let i=e[r],s=t[r];s&&(i&&((e.restoreStructures||(e.restoreStructures=[]))[r]=i),e[r]=s)}return this.structures=e}decode(e,t){return this.unpack(e,t)}}function J0(n){try{if(!Fn.trusted&&!Fl){let t=an.sharedLength||0;t=32&&kI?(e=kI(We,ue,oo,Fn),We=null,!(n&&n.lazy)&&e&&(e=e.toJSON()),ue=oo):e=yr(),si&&(ue=si.postBundlePosition,si=null),Fl&&(an.restoreStructures=null),ue==oo)an&&an.restoreStructures&&NI(),an=null,We=null,Fc&&(Fc=null);else{if(ue>oo)throw new Error("Unexpected end of MessagePack data");if(!Fl){let t;try{t=JSON.stringify(e,(r,i)=>typeof i=="bigint"?`${i}n`:i).slice(0,100)}catch(r){t="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+t)}}return e}catch(e){throw an&&an.restoreStructures&&NI(),eT(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||ue>oo)&&(e.incomplete=!0),e}}function NI(){for(let n in an.restoreStructures)an[n]=an.restoreStructures[n];an.restoreStructures=null}function yr(){let n=We[ue++];if(n<160)if(n<128){if(n<64)return n;{let e=an[n&63]||Fn.getStructures&&Y4()[n&63];return e?(e.read||(e.read=sM(e,n&63)),e.read()):n}}else if(n<144)if(n-=128,Fn.mapsAsObjects){let e={};for(let t=0;t=ue)return Ol.slice(ue-to,(ue+=e)-to);if(wa==0&&oo<140){let t=e<16?oM(e):Z4(e);if(t!=null)return t}return Qb(e)}else{let e;switch(n){case 192:return null;case 193:return si?(e=yr(),e>0?si[1].slice(si.position1,si.position1+=e):si[0].slice(si.position0,si.position0-=e)):X4;case 194:return!1;case 195:return!0;case 196:if(e=We[ue++],e===void 0)throw new Error("Unexpected end of buffer");return G1(e);case 197:return e=tn.getUint16(ue),ue+=2,G1(e);case 198:return e=tn.getUint32(ue),ue+=4,G1(e);case 199:return Au(We[ue++]);case 200:return e=tn.getUint16(ue),ue+=2,Au(e);case 201:return e=tn.getUint32(ue),ue+=4,Au(e);case 202:if(e=tn.getFloat32(ue),Fn.useFloat32>2){let t=aM[(We[ue]&127)<<1|We[ue+1]>>7];return ue+=4,(t*e+(e>0?.5:-.5)>>0)/t}return ue+=4,e;case 203:return e=tn.getFloat64(ue),ue+=8,e;case 204:return We[ue++];case 205:return e=tn.getUint16(ue),ue+=2,e;case 206:return e=tn.getUint32(ue),ue+=4,e;case 207:return Fn.int64AsType==="number"?(e=tn.getUint32(ue)*4294967296,e+=tn.getUint32(ue+4)):Fn.int64AsType==="string"?e=tn.getBigUint64(ue).toString():Fn.int64AsType==="auto"?(e=tn.getBigUint64(ue),e<=BigInt(2)<=BigInt(-2)<=ue?Ol.slice(ue-to,(ue+=e)-to):ede(e);case 218:return e=tn.getUint16(ue),ue+=2,wa>=ue?Ol.slice(ue-to,(ue+=e)-to):tde(e);case 219:return e=tn.getUint32(ue),ue+=4,wa>=ue?Ol.slice(ue-to,(ue+=e)-to):nde(e);case 220:return e=tn.getUint16(ue),ue+=2,OI(e);case 221:return e=tn.getUint32(ue),ue+=4,OI(e);case 222:return e=tn.getUint16(ue),ue+=2,LI(e);case 223:return e=tn.getUint32(ue),ue+=4,LI(e);default:if(n>=224)return n-256;if(n===void 0){let t=new Error("Unexpected end of MessagePack data");throw t.incomplete=!0,t}throw new Error("Unknown MessagePack token "+n)}}}const Qfe=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function sM(n,e){function t(){if(t.count++>K4){let i=n.read=new Function("r","return function(){return "+(Fn.freezeData?"Object.freeze":"")+"({"+n.map(s=>s==="__proto__"?"__proto_:r()":Qfe.test(s)?s+":r()":"["+JSON.stringify(s)+"]:r()").join(",")+"})}")(yr);return n.highByte===0&&(n.read=II(e,n.read)),i()}let r={};for(let i=0,s=n.length;ifunction(){let t=We[ue++];if(t===0)return e();let r=n<32?-(n+(t<<5)):n+(t<<5),i=an[r]||Y4()[r];if(!i)throw new Error("Record id is not defined for "+r);return i.read||(i.read=sM(i,n)),i.read()};function Y4(){let n=tF(()=>(We=null,Fn.getStructures()));return an=Fn._mergeStructures(n,an)}var Qb=Qm,ede=Qm,tde=Qm,nde=Qm;function Qm(n){let e;if(n<16&&(e=oM(n)))return e;if(n>64&&Jb)return Jb.decode(We.subarray(ue,ue+=n));const t=ue+n,r=[];for(e="";ue65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c)}else r.push(i);r.length>=4096&&(e+=ri.apply(String,r),r.length=0)}return r.length>0&&(e+=ri.apply(String,r)),e}function OI(n){let e=new Array(n);for(let t=0;t0){ue=e;return}t[r]=i}return ri.apply(String,t)}function oM(n){if(n<4)if(n<2){if(n===0)return"";{let e=We[ue++];if((e&128)>1){ue-=1;return}return ri(e)}}else{let e=We[ue++],t=We[ue++];if((e&128)>0||(t&128)>0){ue-=2;return}if(n<3)return ri(e,t);let r=We[ue++];if((r&128)>0){ue-=3;return}return ri(e,t,r)}else{let e=We[ue++],t=We[ue++],r=We[ue++],i=We[ue++];if((e&128)>0||(t&128)>0||(r&128)>0||(i&128)>0){ue-=4;return}if(n<6){if(n===4)return ri(e,t,r,i);{let s=We[ue++];if((s&128)>0){ue-=5;return}return ri(e,t,r,i,s)}}else if(n<8){let s=We[ue++],o=We[ue++];if((s&128)>0||(o&128)>0){ue-=6;return}if(n<7)return ri(e,t,r,i,s,o);let a=We[ue++];if((a&128)>0){ue-=7;return}return ri(e,t,r,i,s,o,a)}else{let s=We[ue++],o=We[ue++],a=We[ue++],c=We[ue++];if((s&128)>0||(o&128)>0||(a&128)>0||(c&128)>0){ue-=8;return}if(n<10){if(n===8)return ri(e,t,r,i,s,o,a,c);{let l=We[ue++];if((l&128)>0){ue-=9;return}return ri(e,t,r,i,s,o,a,c,l)}}else if(n<12){let l=We[ue++],u=We[ue++];if((l&128)>0||(u&128)>0){ue-=10;return}if(n<11)return ri(e,t,r,i,s,o,a,c,l,u);let h=We[ue++];if((h&128)>0){ue-=11;return}return ri(e,t,r,i,s,o,a,c,l,u,h)}else{let l=We[ue++],u=We[ue++],h=We[ue++],d=We[ue++];if((l&128)>0||(u&128)>0||(h&128)>0||(d&128)>0){ue-=12;return}if(n<14){if(n===12)return ri(e,t,r,i,s,o,a,c,l,u,h,d);{let m=We[ue++];if((m&128)>0){ue-=13;return}return ri(e,t,r,i,s,o,a,c,l,u,h,d,m)}}else{let m=We[ue++],g=We[ue++];if((m&128)>0||(g&128)>0){ue-=14;return}if(n<15)return ri(e,t,r,i,s,o,a,c,l,u,h,d,m,g);let v=We[ue++];if((v&128)>0){ue-=15;return}return ri(e,t,r,i,s,o,a,c,l,u,h,d,m,g,v)}}}}}function PI(){let n=We[ue++],e;if(n<192)e=n-160;else switch(n){case 217:e=We[ue++];break;case 218:e=tn.getUint16(ue),ue+=2;break;case 219:e=tn.getUint32(ue),ue+=4;break;default:throw new Error("Expected string")}return Qm(e)}function G1(n){return Fn.copyBuffers?Uint8Array.prototype.slice.call(We,ue,ue+=n):We.subarray(ue,ue+=n)}function Au(n){let e=We[ue++];if(As[e]){let t;return As[e](We.subarray(ue,t=ue+=n),r=>{ue=r;try{return yr()}finally{ue=t}})}else throw new Error("Unknown extension type "+e)}var DI=new Array(4096);function J4(){let n=We[ue++];if(n>=160&&n<192){if(n=n-160,wa>=ue)return Ol.slice(ue-to,(ue+=n)-to);if(!(wa==0&&oo<180))return Qb(n)}else return ue--,Q4(yr());let e=(n<<5^(n>1?tn.getUint16(ue):n>0?We[ue]:0))&4095,t=DI[e],r=ue,i=ue+n-3,s,o=0;if(t&&t.bytes==n){for(;r{let t=yr().map(Q4),r=n;e!==void 0&&(n=n<32?-((e<<5)+n):(e<<5)+n,t.highByte=e);let i=an[n];return i&&(i.isShared||Fl)&&((an.restoreStructures||(an.restoreStructures=[]))[n]=i),an[n]=t,t.read=sM(t,r),t.read()};As[0]=()=>{};As[0].noBuffer=!0;As[66]=n=>{let e=n.length,t=BigInt(n[0]&128?n[0]-256:n[0]);for(let r=1;r{let n=yr();return(rde[n[0]]||Error)(n[1],{cause:n[2]})};As[105]=n=>{if(Fn.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=tn.getUint32(ue-4);Fc||(Fc=new Map);let t=We[ue],r;t>=144&&t<160||t==220||t==221?r=[]:r={};let i={target:r};Fc.set(e,i);let s=yr();return i.used?Object.assign(r,s):(i.target=s,s)};As[112]=n=>{if(Fn.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=tn.getUint32(ue-4),t=Fc.get(e);return t.used=!0,t.target};As[115]=()=>new Set(yr());const eF=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(n=>n+"Array");let ide=typeof globalThis=="object"?globalThis:window;As[116]=n=>{let e=n[0],t=eF[e];if(!t){if(e===16){let r=new ArrayBuffer(n.length-1);return new Uint8Array(r).set(n.subarray(1)),r}throw new Error("Could not find typed array for code "+e)}return new ide[t](Uint8Array.prototype.slice.call(n,1).buffer)};As[120]=()=>{let n=yr();return new RegExp(n[0],n[1])};const sde=[];As[98]=n=>{let e=(n[0]<<24)+(n[1]<<16)+(n[2]<<8)+n[3],t=ue;return ue+=e-n.length,si=sde,si=[PI(),PI()],si.position0=0,si.position1=0,si.postBundlePosition=ue,ue=t,yr()};As[255]=n=>n.length==4?new Date((n[0]*16777216+(n[1]<<16)+(n[2]<<8)+n[3])*1e3):n.length==8?new Date(((n[0]<<22)+(n[1]<<14)+(n[2]<<6)+(n[3]>>2))/1e6+((n[3]&3)*4294967296+n[4]*16777216+(n[5]<<16)+(n[6]<<8)+n[7])*1e3):n.length==12?new Date(((n[0]<<24)+(n[1]<<16)+(n[2]<<8)+n[3])/1e6+((n[4]&128?-281474976710656:0)+n[6]*1099511627776+n[7]*4294967296+n[8]*16777216+(n[9]<<16)+(n[10]<<8)+n[11])*1e3):new Date("invalid");function tF(n){let e=oo,t=ue,r=to,i=wa,s=Ol,o=Fc,a=si,c=new Uint8Array(We.slice(0,oo)),l=an,u=an.slice(0,an.length),h=Fn,d=Fl,m=n();return oo=e,ue=t,to=r,wa=i,Ol=s,Fc=o,si=a,We=c,Fl=d,an=l,an.splice(0,an.length,...u),Fn=h,tn=new DataView(We.buffer,We.byteOffset,We.byteLength),m}function eT(){We=null,Fc=null,an=null}const aM=new Array(147);for(let n=0;n<256;n++)aM[n]=+("1e"+Math.floor(45.15-n*.30103));var ux=new rm({useRecords:!1});ux.unpack;ux.unpackMultiple;ux.unpack;let ode=new Float32Array(1);new Uint8Array(ode.buffer,0,4);let F_;try{F_=new TextEncoder}catch{}let tT,nF;const hx=typeof Buffer<"u",Q0=hx?function(n){return Buffer.allocUnsafeSlow(n)}:Uint8Array,rF=hx?Buffer:Uint8Array,FI=hx?4294967296:2144337920;let ye,lp,Pn,pe=0,Li,Qn=null,ade;const cde=21760,lde=/[\u0080-\uFFFF]/,hf=Symbol("record-id");class ude extends rm{constructor(e){super(e),this.offset=0;let t,r,i,s,o=rF.prototype.utf8Write?function(P,w){return ye.utf8Write(P,w,ye.byteLength-w)}:F_&&F_.encodeInto?function(P,w){return F_.encodeInto(P,ye.subarray(w)).written}:!1,a=this;e||(e={});let c=e&&e.sequential,l=e.structures||e.saveStructures,u=e.maxSharedStructures;if(u==null&&(u=l?32:0),u>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let h=e.maxOwnStructures;h==null&&(h=l?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let d=u>32||h+u>64,m=u+64,g=u+h+64;if(g>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let v=[],y=0,_=0;this.pack=this.encode=function(P,w){if(ye||(ye=new Q0(8192),Pn=ye.dataView||(ye.dataView=new DataView(ye.buffer,0,8192)),pe=0),Li=ye.length-10,Li-pe<2048?(ye=new Q0(ye.length),Pn=ye.dataView||(ye.dataView=new DataView(ye.buffer,0,ye.length)),Li=ye.length-10,pe=0):pe=pe+7&2147483640,t=pe,w&gde&&(pe+=w&255),s=a.structuredClone?new Map:null,a.bundleStrings&&typeof P!="string"?(Qn=[],Qn.size=1/0):Qn=null,i=a.structures,i){i.uninitialized&&(i=a._mergeStructures(a.getStructures()));let V=i.sharedLength||0;if(V>u)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let B=0;Bj.offset>Y.offset?1:-1),z=B.length,W=-1;for(;V&&z>0;){let j=B[--z].offset+t;jV.position+t?W>=0&&(W+=6):(W>=0&&(Pn.setUint32(V.position+t,Pn.getUint32(V.position+t)+W),W=-1),V=V.previous,z++)}W>=0&&V&&Pn.setUint32(V.position+t,Pn.getUint32(V.position+t)+W),pe+=B.length*6,pe>Li&&C(pe),a.offset=pe;let K=fde(ye.subarray(t,pe),B);return s=null,K}return a.offset=pe,w&pde?(ye.start=t,ye.end=pe,ye):ye.subarray(t,pe)}catch(V){throw H=V,V}finally{if(i&&(S(),r&&a.saveStructures)){let V=i.sharedLength||0,B=ye.subarray(t,pe),z=dde(i,a);if(!H)return a.saveStructures(z,z.isCompatible)===!1?a.pack(P,w):(a.lastNamedStructuresLength=V,ye.length>1073741824&&(ye=null),B)}ye.length>1073741824&&(ye=null),w&mde&&(pe=t)}};const S=()=>{_<10&&_++;let P=i.sharedLength||0;if(i.length>P&&!c&&(i.length=P),y>1e4)i.transitions=null,_=0,y=0,v.length>0&&(v=[]);else if(v.length>0&&!c){for(let w=0,H=v.length;w{var w=P.length;w<16?ye[pe++]=144|w:w<65536?(ye[pe++]=220,ye[pe++]=w>>8,ye[pe++]=w&255):(ye[pe++]=221,Pn.setUint32(pe,w),pe+=4);for(let H=0;H{pe>Li&&(ye=C(pe));var w=typeof P,H;if(w==="string"){let V=P.length;if(Qn&&V>=4&&V<4096){if((Qn.size+=V)>cde){let K,j=(Qn[0]?Qn[0].length*3+Qn[1].length:0)+10;pe+j>Li&&(ye=C(pe+j));let Y;Qn.position?(Y=Qn,ye[pe]=200,pe+=3,ye[pe++]=98,K=pe-t,pe+=4,VI(t,T,0),Pn.setUint16(K+t-3,pe-t-K)):(ye[pe++]=214,ye[pe++]=98,K=pe-t,pe+=4),Qn=["",""],Qn.previous=Y,Qn.size=0,Qn.position=K}let W=lde.test(P);Qn[W?0:1]+=P,ye[pe++]=193,T(W?-V:V);return}let B;V<32?B=1:V<256?B=2:V<65536?B=3:B=5;let z=V*3;if(pe+z>Li&&(ye=C(pe+z)),V<64||!o){let W,K,j,Y=pe+B;for(W=0;W>6|192,ye[Y++]=K&63|128):(K&64512)===55296&&((j=P.charCodeAt(W+1))&64512)===56320?(K=65536+((K&1023)<<10)+(j&1023),W++,ye[Y++]=K>>18|240,ye[Y++]=K>>12&63|128,ye[Y++]=K>>6&63|128,ye[Y++]=K&63|128):(ye[Y++]=K>>12|224,ye[Y++]=K>>6&63|128,ye[Y++]=K&63|128);H=Y-pe-B}else H=o(P,pe+B);H<32?ye[pe++]=160|H:H<256?(B<2&&ye.copyWithin(pe+2,pe+1,pe+1+H),ye[pe++]=217,ye[pe++]=H):H<65536?(B<3&&ye.copyWithin(pe+3,pe+2,pe+2+H),ye[pe++]=218,ye[pe++]=H>>8,ye[pe++]=H&255):(B<5&&ye.copyWithin(pe+5,pe+3,pe+3+H),ye[pe++]=219,Pn.setUint32(pe,H),pe+=4),pe+=H}else if(w==="number")if(P>>>0===P)P<32||P<128&&this.useRecords===!1||P<64&&!this.randomAccessStructure?ye[pe++]=P:P<256?(ye[pe++]=204,ye[pe++]=P):P<65536?(ye[pe++]=205,ye[pe++]=P>>8,ye[pe++]=P&255):(ye[pe++]=206,Pn.setUint32(pe,P),pe+=4);else if(P>>0===P)P>=-32?ye[pe++]=256+P:P>=-128?(ye[pe++]=208,ye[pe++]=P+256):P>=-32768?(ye[pe++]=209,Pn.setInt16(pe,P),pe+=2):(ye[pe++]=210,Pn.setInt32(pe,P),pe+=4);else{let V;if((V=this.useFloat32)>0&&P<4294967296&&P>=-2147483648){ye[pe++]=202,Pn.setFloat32(pe,P);let B;if(V<4||(B=P*aM[(ye[pe]&127)<<1|ye[pe+1]>>7])>>0===B){pe+=4;return}else pe--}ye[pe++]=203,Pn.setFloat64(pe,P),pe+=8}else if(w==="object"||w==="function")if(!P)ye[pe++]=192;else{if(s){let B=s.get(P);if(B){if(!B.id){let z=s.idsToInsert||(s.idsToInsert=[]);B.id=z.push(B)}ye[pe++]=214,ye[pe++]=112,Pn.setUint32(pe,B.id),pe+=4;return}else s.set(P,{offset:pe-t})}let V=P.constructor;if(V===Object)O(P);else if(V===Array)E(P);else if(V===Map)if(this.mapAsEmptyObject)ye[pe++]=128;else{H=P.size,H<16?ye[pe++]=128|H:H<65536?(ye[pe++]=222,ye[pe++]=H>>8,ye[pe++]=H&255):(ye[pe++]=223,Pn.setUint32(pe,H),pe+=4);for(let[B,z]of P)T(B),T(z)}else{for(let B=0,z=tT.length;B(ye=j,j=null,pe+=re,pe>Li&&C(pe),{target:ye,targetView:Pn,position:pe-re}),T)}finally{j&&(ye=j,Pn=Y,pe=ge,Li=ye.length-10)}Q&&(Q.length+pe>Li&&C(Q.length+pe),pe=hde(Q,ye,pe,K.type));return}}if(Array.isArray(P))E(P);else{if(P.toJSON){const B=P.toJSON();if(B!==P)return T(B)}if(w==="function")return T(this.writeFunction&&this.writeFunction(P));O(P)}}}else if(w==="boolean")ye[pe++]=P?195:194;else if(w==="bigint"){if(P=-(BigInt(1)<0)ye[pe++]=207,Pn.setBigUint64(pe,P);else if(this.largeBigIntToFloat)ye[pe++]=203,Pn.setFloat64(pe,Number(P));else{if(this.largeBigIntToString)return T(P.toString());if(this.useBigIntExtension&&P-(BigInt(2)**BigInt(1023))){ye[pe++]=199,pe++,ye[pe++]=66;let V=[],B;do{let z=P&BigInt(255);B=(z&BigInt(128))===(P>=BigInt(8)}while(!((P===BigInt(0)||P===BigInt(-1))&&B));ye[pe-2]=V.length;for(let z=V.length;z>0;)ye[pe++]=Number(V[--z]);return}else throw new RangeError(P+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}pe+=8}else if(w==="undefined")this.encodeUndefinedAsNil?ye[pe++]=192:(ye[pe++]=212,ye[pe++]=0,ye[pe++]=0);else throw new Error("Unknown type: "+w)},k=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?P=>{let w;if(this.skipValues){w=[];for(let B in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(B))&&!this.skipValues.includes(P[B])&&w.push(B)}else w=Object.keys(P);let H=w.length;H<16?ye[pe++]=128|H:H<65536?(ye[pe++]=222,ye[pe++]=H>>8,ye[pe++]=H&255):(ye[pe++]=223,Pn.setUint32(pe,H),pe+=4);let V;if(this.coercibleKeyAsNumber)for(let B=0;B{ye[pe++]=222;let w=pe-t;pe+=2;let H=0;for(let V in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(V))&&(T(V),T(P[V]),H++);if(H>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');ye[w+++t]=H>>8,ye[w+t]=H&255},R=this.useRecords===!1?k:e.progressiveRecords&&!d?P=>{let w,H=i.transitions||(i.transitions=Object.create(null)),V=pe++-t,B;for(let z in P)if(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(z)){if(w=H[z],w)H=w;else{let W=Object.keys(P),K=H;H=i.transitions;let j=0;for(let Y=0,ge=W.length;Y{let w,H=i.transitions||(i.transitions=Object.create(null)),V=0;for(let z in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(z))&&(w=H[z],w||(w=H[z]=Object.create(null),V++),H=w);let B=H[hf];B?B>=96&&d?(ye[pe++]=((B-=96)&31)+96,ye[pe++]=B>>5):ye[pe++]=B:I(H,H.__keys__||Object.keys(P),V);for(let z in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(z))&&T(P[z])},M=typeof this.useRecords=="function"&&this.useRecords,O=M?P=>{M(P)?R(P):k(P)}:R,C=P=>{let w;if(P>16777216){if(P-t>FI)throw new Error("Packed buffer would be larger than maximum buffer size");w=Math.min(FI,Math.round(Math.max((P-t)*(P>67108864?1.25:2),4194304)/4096)*4096)}else w=(Math.max(P-t<<2,ye.length-1)>>12)+1<<12;let H=new Q0(w);return Pn=H.dataView||(H.dataView=new DataView(H.buffer,0,w)),P=Math.min(P,ye.length),ye.copy?ye.copy(H,0,t,P):H.set(ye.slice(t,P)),pe-=t,t=0,Li=H.length-10,ye=H},I=(P,w,H)=>{let V=i.nextId;V||(V=64),V=g&&(V=m),i.nextId=V+1);let B=w.highByte=V>=96&&d?V-96>>5:-1;P[hf]=V,P.__keys__=w,i[V-64]=w,V=0?(ye[pe++]=(V&31)+96,ye[pe++]=B):ye[pe++]=V):(B>=0?(ye[pe++]=213,ye[pe++]=114,ye[pe++]=(V&31)+96,ye[pe++]=B):(ye[pe++]=212,ye[pe++]=114,ye[pe++]=V),H&&(y+=_*H),v.length>=h&&(v.shift()[hf]=0),v.push(P),T(w))},U=(P,w,H,V)=>{let B=ye,z=pe,W=Li,K=t;ye=lp,pe=0,t=0,ye||(lp=ye=new Q0(8192)),Li=ye.length-10,I(P,w,V),lp=ye;let j=pe;if(ye=B,pe=z,Li=W,t=K,j>1){let Y=pe+j-1;Y>Li&&C(Y);let ge=H+t;ye.copyWithin(ge+j,ge+1,pe),ye.set(lp.slice(0,j),ge),pe=Y}else ye[H+t]=lp[0]},L=P=>{let w=ade(P,ye,t,pe,i,C,(H,V,B)=>{if(B)return r=!0;pe=V;let z=ye;return T(H),S(),z!==ye?{position:pe,targetView:Pn,target:ye}:pe},this);if(w===0)return O(P);pe=w}}useBuffer(e){ye=e,ye.dataView||(ye.dataView=new DataView(ye.buffer,ye.byteOffset,ye.byteLength)),pe=0}set position(e){pe=e}get position(){return pe}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}}nF=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,q4];tT=[{pack(n,e,t){let r=n.getTime()/1e3;if((this.useTimestamp32||n.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:i,targetView:s,position:o}=e(6);i[o++]=214,i[o++]=255,s.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:i,targetView:s,position:o}=e(10);i[o++]=215,i[o++]=255,s.setUint32(o,n.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),s.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),t(this.onInvalidDate());let{target:i,targetView:s,position:o}=e(3);i[o++]=212,i[o++]=255,i[o++]=255}else{let{target:i,targetView:s,position:o}=e(15);i[o++]=199,i[o++]=12,i[o++]=255,s.setUint32(o,n.getMilliseconds()*1e6),s.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(n,e,t){if(this.setAsEmptyObject)return e(0),t({});let r=Array.from(n),{target:i,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(i[s++]=212,i[s++]=115,i[s++]=0),t(r)}},{pack(n,e,t){let{target:r,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),t([n.name,n.message,n.cause])}},{pack(n,e,t){let{target:r,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),t([n.source,n.flags])}},{pack(n,e){this.moreTypes?BI(n,16,e):zI(hx?Buffer.from(n):new Uint8Array(n),e)}},{pack(n,e){let t=n.constructor;t!==rF&&this.moreTypes?BI(n,eF.indexOf(t.name),e):zI(n,e)}},{pack(n,e){let{target:t,position:r}=e(1);t[r]=193}}];function BI(n,e,t,r){let i=n.byteLength;if(i+1<256){var{target:s,position:o}=t(4+i);s[o++]=199,s[o++]=i+1}else if(i+1<65536){var{target:s,position:o}=t(5+i);s[o++]=200,s[o++]=i+1>>8,s[o++]=i+1&255}else{var{target:s,position:o,targetView:a}=t(7+i);s[o++]=201,a.setUint32(o,i+1),o+=4}s[o++]=116,s[o++]=e,n.buffer||(n=new Uint8Array(n)),s.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength),o)}function zI(n,e){let t=n.byteLength;var r,i;if(t<256){var{target:r,position:i}=e(t+2);r[i++]=196,r[i++]=t}else if(t<65536){var{target:r,position:i}=e(t+3);r[i++]=197,r[i++]=t>>8,r[i++]=t&255}else{var{target:r,position:i,targetView:s}=e(t+5);r[i++]=198,s.setUint32(i,t),i+=4}r.set(n,i)}function hde(n,e,t,r){let i=n.length;switch(i){case 1:e[t++]=212;break;case 2:e[t++]=213;break;case 4:e[t++]=214;break;case 8:e[t++]=215;break;case 16:e[t++]=216;break;default:i<256?(e[t++]=199,e[t++]=i):i<65536?(e[t++]=200,e[t++]=i>>8,e[t++]=i&255):(e[t++]=201,e[t++]=i>>24,e[t++]=i>>16&255,e[t++]=i>>8&255,e[t++]=i&255)}return e[t++]=r,e.set(n,t),t+=i,t}function fde(n,e){let t,r=e.length*6,i=n.length-r;for(;t=e.pop();){let s=t.offset,o=t.id;n.copyWithin(s+r,s,i),r-=6;let a=s+r;n[a++]=214,n[a++]=105,n[a++]=o>>24,n[a++]=o>>16&255,n[a++]=o>>8&255,n[a++]=o&255,i=s}return n}function VI(n,e,t){if(Qn.length>0){Pn.setUint32(Qn.position+n,pe+t-Qn.position-n),Qn.stringsPosition=pe-n;let r=Qn;Qn=null,e(r[0]),e(r[1])}}function dde(n,e){return n.isCompatible=t=>{let r=!t||(e.lastNamedStructuresLength||0)===t.length;return r||e._mergeStructures(t),r},n}let iF=new ude({useRecords:!1});iF.pack;iF.pack;const pde=512,mde=1024,gde=2048;function HI(){return{id:gr()}}function _de(){return new Array(pi*Mh).map(()=>{})}function vde(n=_9){const e={terrain:_de(),objects:{},id:""};return n(e)}function cM(n){var e;return Kt((n==null?void 0:n.name)??((e=n==null?void 0:n.kinddata)==null?void 0:e.name)??"object")}function yde(n){var e;return(n==null?void 0:n.color)??((e=n==null?void 0:n.kinddata)==null?void 0:e.color)??wn.BLACK}function xde(n){var e;return(n==null?void 0:n.bg)??((e=n==null?void 0:n.kinddata)==null?void 0:e.bg)??wn.BLACK}function Bv(n,e){if(!Z(n)||!fo(e))return;const{color:t,bg:r}=Eme(e);Z(t)&&(n.color=t),Z(r)&&(n.bg=r)}function Sde(n,e){if(!Z(n)||!Z(e)||!Z(e.x)||!Z(e.y)||e.x<0||e.x>=pi||e.y<0||e.y>=Mh)return;const t={...e},r=e.x+e.y*pi;return n.terrain[r]=t,e}function Ede(n,e){if(!Z(n)||!Z(e))return;const t={...e,id:e.id??gr()};return n.objects[t.id]=t,t}function sF(n,e,t){return Sde(n,{...e,kind:t})}function oF(n,e,t,r){return Ede(n,{...e,id:void 0,kind:t})}function zv(n,e){if(n)return n.objects[e]}function nT(n,e,t,r,i){if(!Z(n)||!Z(e))return{x:0,y:0};const s={x:e.x??0,y:e.y??0},o={x:e.lx??s.x,y:e.ly??s.y},a=uf(o,s),c=pi-1,l=Mh-1;for(let u=0;u(n[n.CATEGORY=0]="CATEGORY",n[n.COLLISION=1]="COLLISION",n[n.COLOR=2]="COLOR",n[n.KIND=3]="KIND",n[n.DIR=4]="DIR",n[n.NUMBER=5]="NUMBER",n[n.STRING=6]="STRING",n[n.NUMBER_OR_STRING=7]="NUMBER_OR_STRING",n[n.MAYBE_CATEGORY=8]="MAYBE_CATEGORY",n[n.MAYBE_COLLISION=9]="MAYBE_COLLISION",n[n.MAYBE_COLOR=10]="MAYBE_COLOR",n[n.MAYBE_KIND=11]="MAYBE_KIND",n[n.MAYBE_DIR=12]="MAYBE_DIR",n[n.MAYBE_NUMBER=13]="MAYBE_NUMBER",n[n.MAYBE_STRING=14]="MAYBE_STRING",n[n.MAYBE_NUMBER_OR_STRING=15]="MAYBE_NUMBER_OR_STRING",n[n.ANY=16]="ANY",n))(Ie||{});function ni(n,e){throw new Error(`Invalid arg, expected: ${n} but got ${JSON.stringify(e)}`)}function Ve(n,e,t){var o,a,c,l;const r=se.words;se.words=n;const i=[];let s=e;for(let u=0;u(WI(1,n,e),0)).command("synth",(n,e)=>{for(let t=1;t<=8;++t)fa(t,e);return 0}).command("synth1",(n,e)=>(fa(1,e),0)).command("synth2",(n,e)=>(fa(2,e),0)).command("synth3",(n,e)=>(fa(3,e),0)).command("synth4",(n,e)=>(fa(4,e),0)).command("synth5",(n,e)=>(fa(5,e),0)).command("synth6",(n,e)=>(fa(6,e),0)).command("synth7",(n,e)=>(fa(7,e),0)).command("synth8",(n,e)=>(fa(8,e),0)).command("bgplay",(n,e)=>(WI(0,n,e),0)).command("bgsynth",(n,e)=>(fa(0,e),0)).command("tts",(n,e)=>{const[t,r]=Ve(e,0,[Ie.STRING,Ie.MAYBE_STRING]);return H9("audio",r??"",t),0}),lM=ex(32,126).map(n=>String.fromCharCode(n));function nn(n){return Ws({...n,name:`token_${n.name}`})}function xo(n,e=!1){return nn(e?{name:n,pattern:new RegExp(n.toLowerCase(),"i"),longer_alt:Yi,group:Wr.SKIPPED}:{name:n,pattern:new RegExp(n.toLowerCase(),"i"),longer_alt:Yi})}const im=nn({name:"newline",line_breaks:!0,start_chars_hint:[` +`,"\r"],pattern:/\n|\r\n?/}),Mde=nn({name:"whitespace",pattern:/ +/,group:Wr.SKIPPED}),Cde=nn({name:"whitespace",pattern:/\s+/,line_breaks:!0,group:Wr.SKIPPED}),uM=nn({name:"stat",pattern:/@.*/,start_chars_hint:["@"]}),yf=nn({name:"command",pattern:/#/,start_chars_hint:["#"]});let fF=!1;function Rde(n,e,t){if(!fF)return null;const[r]=t.slice(-1);if(r&&r.tokenType!==im)return null;let i=e;for(;n[i]===" ";)i++;if("@#/?':!".includes(n[i]))return null;let s=e+1;for(;s"@#/?':!".includes(n)===!1)}),pF=nn({name:"comment",pattern:/'.*/,start_chars_hint:["'"]}),mF=nn({name:"label",pattern:/:[^;:\n]*/,start_chars_hint:[":"]}),gF=nn({name:"hyperlink",pattern:/!/,start_chars_hint:["!"]}),_F=nn({name:"hyperlinktext",pattern:/;[^;\n]*/,start_chars_hint:[";"]}),Yi=nn({name:"stringliteral",pattern:/[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/,start_chars_hint:lM}),vF=nn({name:"stringliteraldouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),yF=nn({name:"numberliteral",pattern:/-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?/}),xF=nn({name:"iseq",pattern:/=|is|eq|equal/,longer_alt:Yi}),SF=nn({name:"isnoteq",pattern:/!=|not ?eq|not ?equal/,longer_alt:Yi}),EF=nn({name:"islessthan",pattern:/<|below/,longer_alt:Yi}),bF=nn({name:"isgreaterthan",pattern:/>|above/,longer_alt:Yi}),TF=nn({name:"islessthanorequal",pattern:/<=|below ?or ?eq|below ?or ?equal/,longer_alt:Yi}),wF=nn({name:"isgreaterthanorequal",pattern:/>=|above ?or ?eq|above ?or ?equal/,longer_alt:Yi}),iT=nn({name:"or",pattern:/or/i,longer_alt:Yi}),sT=nn({name:"not",pattern:/not/i,longer_alt:Yi}),oT=nn({name:"and",pattern:/and/i,longer_alt:Yi}),aT=nn({name:"plus",pattern:/\+/}),cT=nn({name:"minus",pattern:/-/}),AF=nn({name:"power",pattern:/\*\*/}),MF=nn({name:"multiply",pattern:/\*/}),lT=nn({name:"divide",pattern:/\//}),CF=nn({name:"moddivide",pattern:/%/}),RF=nn({name:"floordivide",pattern:/%%/}),kF=nn({name:"query",pattern:/\?/}),NF=nn({name:"lparen",pattern:/\(/,push_mode:"ignore_newlines"}),IF=nn({name:"rparen",pattern:/\)/,pop_mode:!0}),OF=nn({name:"command_play",pattern:/(play|bgplay) .*/,start_chars_hint:lM,longer_alt:Yi}),LF=xo("debugger"),uT=xo("if"),z_=xo("do"),kde=xo("to",!0),hT=xo("done"),Nde=xo("then",!0),fT=xo("else"),PF=xo("while"),DF=xo("repeat"),UF=xo("waitfor"),FF=nn({name:"foreach",pattern:/foreach|for/,longer_alt:Yi}),BF=xo("break"),zF=xo("continue");function VF(n){return[...n,yF,xF,SF,TF,EF,wF,bF,iT,sT,oT,aT,cT,AF,MF,lT,RF,CF,kF,NF,IF,vF,Yi]}const HF=VF([dF,uM,OF,yf,pF,mF,gF,_F,im,Mde,BF,zF,LF,hT,z_,fT,FF,uT,DF,Nde,kde,UF,PF]),Ide=new Wr({defaultMode:"use_newlines",modes:{use_newlines:HF,ignore_newlines:VF([Cde])}},{skipValidations:!ja,ensureOptimizations:ja});function GF(n){fF=!0;const e=Ide.tokenize(n||` +`),[t]=(cn(e.tokens)?e.tokens:[]).slice(-1);return t&&t.tokenType.name!=="Newline"&&e.tokens.push(Ym(im,` +`,t.startOffset,t.endOffset??NaN,t.startLine??NaN,t.endLine??NaN,t.startColumn??NaN,t.endColumn??NaN)),e}function WF(n,e=!0){const[t,...r]=n;switch(Kt(t)){default:return e?{type:pt.OBJECT,values:n}:{type:pt.CONST,values:n};case"loader":return{type:pt.LOADER,values:r};case"board":return{type:pt.BOARD,values:r};case"object":return{type:pt.OBJECT,values:r};case"terrain":return{type:pt.TERRAIN,values:r};case"charset":return{type:pt.CHARSET,values:r};case"palette":return{type:pt.PALETTE,values:r};case"rn":case"range":return{type:pt.RANGE,values:r};case"sl":case"select":return{type:pt.SELECT,values:r};case"nm":case"number":return{type:pt.NUMBER,values:r};case"tx":case"text":return{type:pt.TEXT,values:r};case"ln":case"link":return{type:pt.LINK,values:r};case"hk":case"hotkey":return{type:pt.HOTKEY,values:r};case"scroll":return{type:pt.SCROLL,values:r};case"copyit":return{type:pt.COPYIT,values:r}}}function io(n){switch(n){case pt.LOADER:return"loader";case pt.BOARD:return"board";case pt.OBJECT:return"object";case pt.TERRAIN:return"terrain";case pt.CHARSET:return"charset";case pt.PALETTE:return"palette";case pt.CONST:return"const";case pt.RANGE:return"range";case pt.SELECT:return"select";case pt.NUMBER:return"number";case pt.TEXT:return"text";case pt.LINK:return"link";case pt.HOTKEY:return"hotkey";case pt.SCROLL:return"scroll";case pt.COPYIT:return"copyit"}}function Ode(n,e){return{id:gr(),code:n,...e}}function Lde(n){const e={...hM(n)};return Object.keys(e).forEach(t=>{switch(t){case"type":case"name":delete e[t];break}}),e}function hM(n){var r;if(!Z(n))return{};if(Z((r=n.stats)==null?void 0:r.type))return n.stats;n.stats={};const e=GF(n.code);let t=!0;for(let i=0;ii.id===e||t===Oc(i))}function XF(n,e,t){if(!Z(n))return;const r=Kt(t);return n.pages.find(s=>fM(s)===e&&(s.id===t||r===Oc(s)))}function Pde(n,e){if(!Z(n)||!Z(e))return!1;const t=eg(n,e.id);return Z(t)?!1:(n.pages.push(e),!0)}function Dde(n,e){const t=eg(n,e);if(Z(n)&&Z(t)){const r=Kt(e);return n.pages=n.pages.filter(i=>i.id!==e&&r!==Oc(i)),t}}function qc(n,e){if(Z(e)&&Z(e.kind))return Z(e.kinddata)||(e.kinddata=Z(e.id)?dM(n,e.kind):KF(n,e.kind)),e.kinddata}function Ude(n,e){const t=qc(n,e);return{char:(e==null?void 0:e.char)??(t==null?void 0:t.char)??1,color:(e==null?void 0:e.color)??(t==null?void 0:t.color)??wn.WHITE,bg:(e==null?void 0:e.bg)??(t==null?void 0:t.bg)??wn.ONBORROW}}function dM(n,e){const t=e??"",r=XF(n,xn.OBJECT,t);if(Z(r)){const i=$F(r);return{...rw(i),name:t,code:r.code}}}function KF(n,e){const t=e??"",r=XF(n,xn.TERRAIN,t);if(Z(r)){const i=$F(r);return{...rw(i),name:t,code:r.code}}}function Fde(n,e){return n?(n.flags[e]=n.flags[e]??{},n.flags[e]):{}}function Bde(n,e){n&&delete n.flags[e]}function zde(n,e,t,r){const i=zv(e,(t==null?void 0:t.id)??"");if(!Z(n)||!Z(e)||!Z(i)||!Z(i.x)||!Z(i.y)||!Z(e.lookup)||r.x<0||r.x>=pi||r.y<0||r.y>=Mh||i.x-r.x===0&&i.y-r.y===0)return!0;const s=r.x+r.y*pi,o=qc(n,i),a=i.collision??(o==null?void 0:o.collision),c=zv(e,e.lookup[s]??"");if(Z(c))return!0;const l=e.terrain[s];if(Z(l)){const u=qc(n,l),h=l.collision??(u==null?void 0:u.collision);if(W4(a,h))return!0}return!1}function Vde(n,e,t,r){const i=zv(e,(t==null?void 0:t.id)??"");if(!Z(n)||!Z(e)||!Z(i)||!Z(i.x)||!Z(i.y)||!Z(e.lookup)||r.x<0||r.x>=pi||r.y<0||r.y>=Mh)return{kind:"edge",collision:Gn.ISSOLID,x:r.x,y:r.y};if(i.x-r.x===0&&i.y-r.y===0)return;const s=i.x+i.y*pi,o=r.x+r.y*pi,a=qc(n,i),c=i.collision??(a==null?void 0:a.collision),l=zv(e,e.lookup[o]??"");if(Z(l))return{...l};const u=e.terrain[o];if(Z(u)){const h=qc(n,u),d=u.collision??(h==null?void 0:h.collision);if(W4(c,d))return{...u,x:r.x,y:r.y}}i.x=r.x,i.y=r.y,Z(i.removed)||(e.lookup[s]=void 0,e.lookup[o]=i.id??"")}function pd(n,e){const t=qc(n,e);return Z(e==null?void 0:e.id)&&Z(e.x)&&Z(e.y)?Kt(e.name??(t==null?void 0:t.name)??"object"):Kt((e==null?void 0:e.name)??(t==null?void 0:t.name)??"terrain")}function dT(n,e,t,r){if(!Z(n)||!Z(e)||!Z(e.named)||!Z(t))return;const i=pd(n,t);e.named[i]||(e.named[i]=new Set),e.named[i].add((t==null?void 0:t.id)??r??"")}function Hde(n,e,t){if(!(!Z(n)||!Z(e)||!Z(e.lookup)||!Z(t==null?void 0:t.id))&&!Z(t.removed)){const r=t.x??0,i=t.y??0;e.lookup[r+i*pi]=t.id}}function pT(n,e){if(!Z(n)||!Z(e)||Z(e.lookup)&&Z(e.named))return;const t=new Array(pi*Mh).fill(void 0),r={},i=Object.values(e.objects);for(let a=0;a=pi&&(s=0,++o)}e.lookup=t,e.named=r}function pM(n,e,t){return pd(n,e)!=="player"&&Z(e)?(e.removed=t,!0):!1}function fx(n,e,t){var r;if(Z(n)&&Z(e)&&Z(t==null?void 0:t.id)){if(Z(e.lookup)&&Z(t.x)&&Z(t.y)){const s=t.x+t.y*pi;e.lookup[s]===t.id&&e.lookup.splice(s,1)}const i=pd(n,t);Z((r=e.named)==null?void 0:r[i])&&Z(t.id)&&e.named[i].delete(t.id)}}function Gde(n,e,t,r){if(Z(n)&&Z(e)&&Z(t)){const[i,s]=t,o=dM(n,i);if(Z(o)&&Z(o.name)){const a=oF(e,r,i);return Bv(a,s),dT(n,e,a),a}}}function mT(n,e,t,r){if(Z(n)&&Z(e)&&Z(t)){const[i,s]=t,o=KF(n,i);if(Z(o)){const c=sF(e,r,i);Bv(c,s);const l=r.x+r.y*pi;return dT(n,e,c,l),c}const a=dM(n,i);if(Z(a)&&Z(a.name)){const c=oF(e,r,i);return Bv(c,s),Hde(n,e,c),dT(n,e,c),c}}}function t_(n,e,t,r){const i=Bt(e)?e:e.id,s=Bt(e)?void 0:{x:e.x??0,y:e.y??0},o=Bt(t)?t:t.id,a=i??s;Z(o)&&Z(a)&&n.send(o,r,a)}function Wde(n,e,t,r){Z(t==null?void 0:t.id)?(t.headless=!0,fx(n,e,t)):sF(e,r,"empty")}function $I(n,e,t,r,i){const s=Vde(e,t,r,i);if(Z(s)){t_(n,s,n.id(),"thud"),r.kind===Ir.PLAYER?t_(n,n.id(),s,"touch"):r.collision===Gn.ISBULLET?t_(n,n.id(),s,"shot"):t_(n,n.id(),s,"bump");const o=qc(e,s);return(s.destructible??(o==null?void 0:o.destructible))&&Wde(e,t,s,i),!1}return!0}function qI(n,e,t){if(!Ic(se.element))return 0;const[r,i]=Ve(e,0,[Ie.DIR,Ie.MAYBE_KIND]),s=i??["bullet"],o=Gde(se.book,se.board,s,{x:se.element.x,y:se.element.y});if(Z(o)){o.arg=t,o.collision=Gn.ISBULLET,o.stepx=r.x-se.element.x,o.stepy=r.y-se.element.y;const a=qc(se.book,o),c=o.code??(a==null?void 0:a.code)??"";_me(se.book,se.board,o,c,1),o.x===se.element.x&&o.y===se.element.y?o.headless=!0:n.bucket(o.id)}return n.yield(),0}const jde=al().command("change",(n,e)=>{if(!Z(se.book)||!Z(se.board))return 0;const[t,r]=Ve(e,0,[Ie.KIND,Ie.KIND]);pT(se.book,se.board);const i=Fv(t)??"",s=Jm(se.board,i),o=j4(s,t),a=Fv(r),c=H4(r),l=G4(r);return o.forEach(u=>{if(pd(se.book,u)===a)Z(c)&&(u.color=c),Z(l)&&(u.bg=l);else{if(Z(u.id)&&(fx(se.book,se.board,u),!pM(se.book,u,se.timestamp)))return;Ic(u)&&mT(se.book,se.board,r,u)}}),0}).command("put",(n,e)=>{if(!Z(se.book)||!Z(se.board))return 0;const[t,r]=Ve(e,0,[Ie.DIR,Ie.KIND]);return pT(se.book,se.board),mT(se.book,se.board,r,t),0}).command("shootwith",(n,e)=>{const[t,r]=Ve(e,0,[Ie.ANY]);return qI(n,e.slice(r),t)}).command("shoot",qI).command("throwstar",()=>0);function ff(n=""){YL("cli",n,se.player)}const $de=al().command("send",(n,e)=>{const[t,r]=Ve(e,0,[Ie.STRING,Ie.ANY]);switch(t){case"helpmenu":Mc("cli","H E L P"),sn("cli","#help controls","zss controls and inputs"),un("cli","!helpcontrols;read help controls"),un("cli",""),sn("cli","#help text","text formatting"),un("cli","!helptext;read help text"),un("cli",""),sn("cli","#help developer","developer commands"),un("cli","!helpdeveloper;read help developer"),un("cli",""),sn("cli","#help player","player settings"),un("cli","!helpplayer;read help player"),_c("cli","keyboard input"),sn("cli","?","open console"),sn("cli","esc","close console"),sn("cli","tab","move console"),sn("cli","up / down arrow keys","navigate console items"),sn("cli","left / right arrow keys","change console items"),sn("cli","enter","interact with console items"),sn("cli","alt + arrow keys","skip words and console lines"),sn("cli",`${hue} + up / down arrow keys`,"input history");break;case"helpcontrols":Mc("cli","zss controls and inputs"),_c("cli","keyboard input"),sn("cli","arrow keys","move"),sn("cli","shift + arrow keys","shoot"),sn("cli","enter","ok / accept"),sn("cli","escape","cancel / close"),sn("cli","tab","menu / action"),_c("cli","mouse input"),vn("cli","todo ???"),_c("cli","controller input"),sn("cli","left stick","move"),sn("cli","right stick","aim"),sn("cli","a","ok / accept"),sn("cli","b","cancel / close"),sn("cli","y","menu / action"),sn("cli","x","shoot"),sn("cli","triggers","shoot");break;case"helptext":Mc("cli","text formatting"),_c("cli","typography"),vn("cli","plain text"),vn("cli","$centering text"),vn("cli",'"\\"@quoted strings for special chars\\""'),vn("cli","$$0-255 for ascii chars $159$176$240"),vn("cli",`use color names like ${Os("red","$$red")} to change foreground color`),vn("cli",`use color names like ${D2("ongreen","$$ongreen")} to change background color`),vn("cli",`use clear ${D2("onclear","to change background to")} transparent`),_c("cli","hyperlinks"),vn("cli",`${Os("white",'"!hotkey"')} message shortcut;${Os("gray","Label")}`),vn("cli",`${Os("white",'"!range"')} flag [labelmin] [labelmax];${Os("gray","Input Label")}`),vn("cli",`${Os("white",'"!select"')} flag ...list of values;${Os("gray","Input Label")}`),vn("cli",`${Os("white",'"!number"')} flag [minvalue] [maxvalue];${Os("gray","Input Label")}`),vn("cli",`${Os("white",'"!text"')} flag;${Os("gray","Input Label")}`),vn("cli",`${Os("white",'"!copyit"')} flag;${Os("gray","Input Label")}`);break;case"helpdeveloper":Mc("cli","developer commands"),sn("cli","#books","list books in memory"),sn("cli","#pages","list pages in opened book"),sn("cli","@[pagetype:]page name","create & edit a new codepage in the currently opened book"),sn("cli","#trash","list books and pages from open book you can delete"),sn("cli","#save","flush state to register");break;case"helpplayer":Mc("cli","player settings"),vn("cli","todo");break;default:lo("$2",`${t} ${r??""}`);break}return 0}).command("stat",(n,e)=>{let t;const[r,...i]=e.map(ai),s=i.join(" ");switch(Kt(r)){case io(pt.LOADER):t=Ru(Ir.CONTENT,s,xn.LOADER);break;default:t=Ru(Ir.CONTENT,[r,...i].join(" "),xn.OBJECT);break;case io(pt.BOARD):t=Ru(Ir.CONTENT,s,xn.BOARD);break;case io(pt.OBJECT):t=Ru(Ir.CONTENT,s,xn.OBJECT);break;case io(pt.TERRAIN):t=Ru(Ir.CONTENT,s,xn.TERRAIN);break;case io(pt.CHARSET):t=Ru(Ir.CONTENT,s,xn.CHARSET);break;case io(pt.PALETTE):t=Ru(Ir.CONTENT,s,xn.PALETTE);break}return Z(t)&&n.command("pageopen",t.id),0}).command("text",(n,e)=>{const t=e.map(ai).join(" ");return lo("$2",t),0}).command("hyperlink",(n,e)=>{const[t,...r]=e,i=ai(t),s=r.map(ai).join(" ");return lo("$2",`!${s};${i}`),0}).command("dev",()=>(ff(),F9("cli",se.player),0)).command("share",()=>(ff(),B9("cli",se.player),0)).command("bookcreate",(n,e)=>{const[t]=Ve(e,0,[Ie.MAYBE_STRING]),r=gB(t);return Z(r)&&n.command("bookopen",r.id),0}).command("bookopen",(n,e)=>{const[t]=Ve(e,0,[Ie.STRING]),r=md(t);return Z(r)?(vn("cli",`opened [book] ${r.name}`),ET(Ir.MAIN,r.id),n.command("pages")):An("cli","bookopen",`book ${t} not found`,se.player),0}).command("booktrash",(n,e)=>{const[t]=Ve(e,0,[Ie.STRING]),r=Tp(Ir.MAIN),i=md(t);return Z(i)&&(r===i&&ET(Ir.MAIN,""),mme(t),vn("cli",`trashed [book] ${i.name}`),ff(),n.command("pages")),0}).command("pageopen",(n,e)=>{const[t]=Ve(e,0,[Ie.STRING]),r=Bc(Ir.MAIN);if(!Z(r))return 0;const i=eg(r,t);if(Z(i)){const s=Oc(i),o=e_(i);vn("cli",`opened [${o}] ${s}`),ED(KL(r.id,i.id),i.code);const a=e_(i);$9("cli",r.id,i.id,a,`${s} - ${r.name}`,se.player)}else An("cli","pageopen",`page ${t} not found`,se.player);return 0}).command("pagetrash",(n,e)=>{const[t]=Ve(e,0,[Ie.STRING]),r=Bc(Ir.MAIN),i=Dde(r,t);if(Z(t)){const s=Oc(i),o=e_(i);vn("cli",`trashed [${o}] ${s}`),ff(),n.command("pages")}return 0}).command("help",(n,e)=>{const t=e.map(ai).join(" ")||"menu";return n.command(`help${t}`),0}).command("books",()=>{_c("cli","books");const n=Tp(Ir.MAIN);sn("cli","main",`${(n==null?void 0:n.name)??"empty"} $GREEN${(n==null?void 0:n.id)??""}`);const e=Tp(Ir.CONTENT);sn("cli","content",`${(e==null?void 0:e.name)??"empty"} ${(e==null?void 0:e.id)??""}`),lw("cli",7);const t=ST();return t.length?t.forEach(r=>{un("cli",`!bookopen ${r.id};${r.name}`)}):vn("cli","no books found"),un("cli","!bookcreate;create a new book"),0}).command("pages",()=>{_c("cli","pages");const n=Bc(Ir.MAIN);return Z(n)&&(sn("cli","main",`${n.name} $GREEN${n.id}`),n.pages.length?n.pages.forEach(e=>{const t=Oc(e),r=e_(e);un("cli",`!pageopen ${e.id};[${r}] ${t}`)}):(un("cli",""),vn("cli","no pages found"),vn("cli","use @ to create a page"),vn("cli","@board name of board"),vn("cli","@object name of object"),vn("cli","@terrain name of terrain"),vn("cli","You can omit the type and it will default to object"),vn("cli","@object name of object"),vn("cli","@name of object"))),0}).command("trash",()=>{_c("cli","$REDTRASH"),vn("cli","books");const n=ST();n.length&&(n.forEach(t=>{un("cli",`!booktrash ${t.id};$REDTRASH ${t.name}`)}),un("cli",""));const e=Tp(Ir.MAIN);return Z(e)&&(vn("cli",`pages in open ${e.name} book`),e.pages.forEach(t=>{const r=Oc(t);un("cli",`!pagetrash ${t.id};$REDTRASH ${r}`)}),un("cli","")),0}).command("save",()=>(ff(),0)).command("savewith",(n,e)=>{const[t]=Ve(e,0,[Ie.STRING]);return ff(t),0}).command("nuke",()=>(V9("cli",se.player),0)).command("joincode",()=>($L("cli",se.player),0));function qde(n){const e=aF[n];if(Z(e))return e;const t=uF[n];if(Z(t))return t;const r=mx[n];if(Z(r))return r;const i=B4[n];if(Z(i))return i}const Xde=al({get(n,e){const t=qde(e);return Z(t)?[!0,t]:[!1,void 0]}}),Kde=new Set(["inputmove","inputalt","inputctrl","inputshift","inputok","inputcancel","inputmenu"]),XI=new Set(["player","pushable","collision","destructible","p1","p2","p3","cycle","stepx","stepy","sender","arg"]),Yde=["NORTH","SOUTH","WEST","EAST"];function Zde(n){const e=sm(n);if(gt(e.inputcurrent)||(e.inputcurrent=0),cn(e.inputqueue)||(e.inputqueue=[]),e.inputcurrent>0)return e;const[t]=e.inputqueue,[r=Ue.NONE,i=0]=t??[Ue.NONE,0];switch(e.inputmove=[],e.inputok=0,e.inputcancel=0,e.inputmenu=0,e.inputalt=i&P3?1:0,e.inputctrl=i&D3?1:0,e.inputshift=i&U3?1:0,r){case Ue.MOVE_UP:case Ue.MOVE_DOWN:case Ue.MOVE_LEFT:case Ue.MOVE_RIGHT:e.inputmove=[Yde[r-Ue.MOVE_UP]];break;case Ue.OK_BUTTON:e.inputok=1;break;case Ue.CANCEL_BUTTON:e.inputcancel=1;break;case Ue.MENU_BUTTON:e.inputmenu=1;break}return e.inputcurrent=r,e.inputqueue=e.inputqueue.filter(s=>{const[o]=s;return o!==Ue.NONE&&o!==r}),e}const Jde=al({get(n,e){var s,o;if(se.isplayer&&Kde.has(e)){const a=Zde(((s=se.element)==null?void 0:s.id)??"")[e];return[Z(a),a]}const t=(o=se.element)==null?void 0:o[e];if(Z(t)||XI.has(e))return[!0,t];const i=sm(se.player)[e];return[Z(i),i]},set(n,e,t){var s;const r=(s=se.element)==null?void 0:s[e];if(Z(r)||XI.has(e))return Z(se.element)&&(se.element[e]=t),[!0,t];const i=sm(se.player);return i[e]=t,[!0,t]},everytick(n){var e,t;Z((e=se.element)==null?void 0:e.x)&&Z(se.element.y)&&Z(se.element.stepx)&&Z(se.element.stepy)&&$I(n,se.book,se.board,se.element,{x:se.element.x+se.element.stepx,y:se.element.y+se.element.stepy})===!1&&(se.element.stepx=0,se.element.stepy=0),(t=se.element)!=null&&t.headless&&n.command("die")}}).command("become",(n,e)=>{var i,s;const t={x:((i=se.element)==null?void 0:i.x)??0,y:((s=se.element)==null?void 0:s.y)??0},[r]=Ve(e,0,[Ie.KIND]);return pT(se.book,se.board),fx(se.book,se.board,se.element),pM(se.book,se.element,se.timestamp)&&mT(se.book,se.board,r,t),n.endofprogram(),0}).command("bind",()=>0).command("char",(n,e)=>{const[t]=Ve(e,0,[Ie.NUMBER]);return Z(se.element)&&(se.element.char=t),0}).command("color",(n,e)=>{const[t]=Ve(e,0,[Ie.COLOR]);return Z(se.element)&&Z(t)&&Bv(se.element,t),0}).command("go",(n,e)=>{if(Z(se.element)){const[t]=Ve(e,0,[Ie.DIR]);if($I(n,se.book,se.board,se.element,t),n.yield(),se.element.x===t.x&&se.element.y===t.y)return 0}return 1}).command("try",(n,e)=>{const[,t]=Ve(e,0,[Ie.DIR]);return n.command("go",...e)&&t{if(!Z(se.element))return 0;const[t]=Ve(e,0,[Ie.DIR]),r=se.element.x??0,i=se.element.y??0;return se.element.stepx=t.x-r,se.element.stepy=t.y-i,0}),Qde=al().command("clear",(n,e)=>(e.forEach(t=>n.set(ai(t),0)),0)).command("set",(n,e)=>{const[t,r]=Ve(e,0,[Ie.STRING,Ie.ANY]);return n.set(t,r),0}).command("take",(n,e)=>{const[t,r,i]=Ve(e,0,[Ie.STRING,Ie.MAYBE_NUMBER]),s=n.get(t),o=r??1;if(!gt(s))return 1;const a=s-o;return a<0?(i{const[t,r,i]=Ve(e,0,[Ie.STRING,Ie.MAYBE_NUMBER]),s=n.get(t),o=gt(s)?s:0,a=r??1;if(!gt(a))return 0;const c=s===void 0?1:0;return c&&i0&&y<_.lastIndexOf(" ")?c.low.call(g):g})},sentence:function(m,g,v){return m=l.lower(m).replace(a.sentence,function(y,_,S){return _+c.up.call(S)}),g&&g.forEach(function(y){m=m.replace(new RegExp("\\b"+l.lower(y)+"\\b","g"),c.cap)}),v&&v.forEach(function(y){m=m.replace(new RegExp("(\\b"+l.lower(y)+"\\. +)(\\w)"),function(_,S,E){return S+c.low.call(E)})}),m}};u.squish=u.pascal,l.default=l;for(var h in u)l.type(h,u[h]);var d=typeof d=="function"?d:function(){};d(n.exports?n.exports=l:this.Case=l)}).call(No)})(YF);var epe=YF.exports;const tpe=$a(epe),kl={};function ZF(){return{layers:[],panels:[],reset:!0,focus:"scroll"}}function JF(n){n.text=[],Object.values(kl[n.id]??{}).forEach(e=>e==null?void 0:e()),kl[n.id]={}}function QF(n){const e=n.panels.find(t=>t.name===n.focus);if(!e){const t={id:gr(),name:n.focus,edge:Ti.RIGHT,size:20,text:[]};return n.panels.push(t),n.reset=!1,t}return e}const npe=new Set(["hk","hotkey","rn","range","sl","select","nm","number","tx","text"]),rpe=new Set(["rn","range","sl","select","nm","number","tx","text"]),ipe=new Set(["tx","text"]),spe={rn:1,range:1,sl:0,select:0,nm:0,number:0,tx:"",text:""},gT={};let ope=n=>{let e=gT[n];return Z(e)||(gT[n]=e=ZF()),e};function dx(n){return ope(n)}function ape(n,e,t){Object.values(kl).forEach(r=>{if(r[e]!==void 0){const i=Rd(n.id(),e);gt(t)&&Pl(i,t),Bt(t)&&YX(i,t)}})}function cpe(n){let e="";const t=dx(n);return t.panels=t.panels.filter(r=>{if(r.edge===Ti.SCROLL){const[i]=r.text;return Bt(i)&&r.text.length===1&&(e=i),r.text.length>1}return!0}),e}function W1(n,e,t,r,i){const s=dx(n),o=r,a=i??tpe.capital(e),c=s.panels.find(l=>l.name===a);if(c)s.reset=!0,s.focus=a,gt(o)&&(c.size=o);else switch(t){case Ti.START:{gT[n]=ZF();break}case Ti.LEFT:case Ti.RIGHT:case Ti.TOP:case Ti.BOTTOM:case Ti.SCROLL:{const l={id:gr(),name:a,edge:t,size:o??Ele[t],text:[]};s.panels.push(l),s.focus=a;break}}}function lpe(n,e){const t=dx(n),r=QF(t);t.reset&&(t.reset=!1,JF(r)),r.text.push(e)}function upe(n,e,t,r,i){const s=dx(n),o=QF(s);s.reset&&(s.reset=!1,JF(o));const a=Kt(r),c=[e.id(),t,...npe.has(a)?[a]:["hyperlink",r],...i],l=c[2];if(rpe.has(l)){const u=`${c[3]??""}`;kl[o.id]=kl[o.id]??{};const h=e.get(u)??spe[l];if(kl[o.id][u]===void 0){const d=Rd(e.id(),u);gt(h)&&KX(d,h),Bt(h)&&ED(d,h),ipe.has(l)?kl[o.id][u]=JX(d,m=>{Z(m)&&m!==e.get(u)&&e.set(u,m)}):kl[o.id][u]=ZX(d,m=>{Z(m)&&m!==e.get(u)&&e.set(u,m)})}}o.text.push(c)}const hpe=al({get(){return[!1,void 0]},set(n,e,t){return ape(n,e,t),[!1,void 0]},tick(){var e;const n=((e=se.element)==null?void 0:e.name)??"scroll";W1(se.player,"scroll",Ti.SCROLL,void 0,n)},everytick(){const n=cpe(se.player);if(n&&Z(se.element)){se.element.tickertext=n,se.element.tickertime=se.timestamp;const e=Ude(se.book,se.element);lo(`$${wn[e.color]}$${e.char}`,n)}}}).command("send",(n,e)=>{var u,h;const[t,r]=Ve(e,0,[Ie.STRING,Ie.ANY]),[i,s]=t.split(":"),o=Z(s)?i:"self",a=s??i;function c(d){d.forEach(m=>{Z(m.id)&&n.send(m.id,a,r)})}const l=Kt(o);switch(l){case"all":for(const d of Object.keys(((u=se.board)==null?void 0:u.objects)??{}))n.send(d,a,r);break;case"self":n.message({id:gr(),sender:n.id(),target:a,data:r});break;case"others":for(const d of Object.keys(((h=se.board)==null?void 0:h.objects)??{}))d!==n.id()&&n.send(d,a,r);break;default:{c(H1(se.board,[o]));const d=n.get(l);cn(d)?c(H1(se.board,d)):c(H1(se.board,[d]));break}}return 0}).command("stat",(n,e)=>{const t=WF(e.map(ai));switch(t.type){case pt.OBJECT:Z(se.element)&&(se.element.name=t.values.join(" "));break}return 0}).command("text",(n,e)=>{const t=e.map(ai).join("");return lpe(se.player,t),0}).command("hyperlink",(n,e)=>{const[t,r,...i]=e,s=ai(t),o=ai(r);return upe(se.player,n,s,o,i),0}).command("gadget",(n,e)=>{const[t]=Ve(e,0,[Ie.STRING]),r=Sle[Kt(t)];if(r===Ti.SCROLL){const[i,s]=Ve(e,1,[Ie.MAYBE_STRING,Ie.MAYBE_NUMBER]);W1(se.player,t,r,s,i)}else if(Z(r)){const[i,s]=Ve(e,1,[Ie.MAYBE_NUMBER,Ie.MAYBE_STRING]);W1(se.player,t,r,i,s)}return 0}),fpe=al().command("idle",n=>(n.yield(),0)).command("end",n=>(n.endofprogram(),0)).command("endwith",(n,e)=>{const[t]=Ve(e,0,[Ie.ANY]);return n.set("arg",t),n.command("end")}).command("lock",n=>(n.lock(n.id()),0)).command("restore",(n,e)=>(n.restore(ai(e[0])),0)).command("unlock",n=>(n.unlock(),0)).command("zap",(n,e)=>(n.zap(ai(e[0])),0)).command("cycle",(n,e)=>{if(Z(se.element)){const[t]=Ve(e,0,[Ie.NUMBER]);se.element.cycle=Nn(Math.round(t),1,255)}return 0}).command("die",n=>{var e;return(e=se.element)!=null&&e.headless&&fx(se.book,se.board,se.element),pM(se.book,se.element,se.timestamp),n.endofprogram(),0}).command("endgame",()=>(Y9("element",se.player),0)).command("run",(n,e)=>{const[t]=Ve(e,0,[Ie.STRING]);return Hv(t),0}).command("runwith",(n,e)=>{const[t,r]=Ve(e,0,[Ie.ANY,Ie.STRING]);return n.set("arg",t),Hv(r),0});function KI(n,e){if(!Z(n))return;const t=Kt(e),r=t.endsWith("le");switch(t){case"float32":case"float32le":{const i=n.dataview.getFloat32(n.cursor,r);return n.cursor+=4,i}case"float64":case"float64le":{const i=n.dataview.getFloat64(n.cursor,r);return n.cursor+=8,i}case"int8":case"int8le":{const i=n.dataview.getInt8(n.cursor);return n.cursor+=1,i}case"int16":case"int16le":{const i=n.dataview.getInt16(n.cursor,r);return n.cursor+=2,i}case"int32":case"int32le":{const i=n.dataview.getInt32(n.cursor,r);return n.cursor+=4,i}case"int64":case"int64le":{const i=n.dataview.getBigInt64(n.cursor,r);return n.cursor+=8,i}case"uint8":case"uint8le":{const i=n.dataview.getUint8(n.cursor);return n.cursor+=1,i}case"uint16":case"uint16le":{const i=n.dataview.getUint16(n.cursor,r);return n.cursor+=2,i}case"uint32":case"uint32le":{const i=n.dataview.getUint32(n.cursor,r);return n.cursor+=4,i}case"uint64":case"uint64le":{const i=n.dataview.getBigUint64(n.cursor,r);return n.cursor+=8,i}}}const dpe=(n,e)=>{const t=vB(n.id());if(!Z(t))return 0;const[r]=Ve(e,0,[Ie.STRING]),i=Kt(r);switch(i){case"seek":{const[s]=Ve(e,1,[Ie.NUMBER]);t.cursor=s;break}case"float32":case"float32le":case"float64":case"float64le":case"int8":case"int8le":case"int16":case"int16le":case"int32":case"int32le":case"int64":case"int64le":case"uint8":case"uint8le":case"uint16":case"uint16le":case"uint32":case"uint32le":case"uint64":case"uint64le":{const[s]=Ve(e,1,[Ie.STRING]);n.set(s,KI(t,i));break}case"text":{const[s,o]=Ve(e,1,[Ie.STRING,Ie.STRING]),a=KI(t,s);if(gt(a)&&Bt(o)){const c=new Uint8Array(t.bytes.buffer,t.cursor,a),u=new TextDecoder("utf-8").decode(c);n.set(o,u),t.cursor+=a}break}}return 0},ppe=al({get(n,e){const t=vB(n.id());if(Z(t))switch(Kt(e)){case"filename":return[Z(t.filename),t.filename];case"cursor":return[Z(t.cursor),t.cursor]}return[!1,void 0]}}).command("send",(n,e)=>{const[t,r]=Ve(e,0,[Ie.STRING,Ie.ANY]);return n.message({id:gr(),sender:n.id(),target:t,data:r}),0}).command("stat",()=>0).command("text",(n,e)=>{const t=e.map(ai).join(" ");return lo("$2",t),0}).command("hyperlink",(n,e)=>{const[t,...r]=e,i=ai(t),s=r.map(ai).join(" ");return lo("$2",`!${s};${i}`),0}).command("load",(n,e)=>{const t=e.map(ai).join(" "),r=n.get(t)??t;return Bc(Ir.CONTENT,r),0}).command("reload",(n,e)=>{const t=e.map(ai).join(" "),r=n.get(t)??t,i=Bc(Ir.CONTENT,r);return i.pages=[],0}).command("bin",dpe);var mM=(n=>(n[n.ERROR=0]="ERROR",n[n.CLI=1]="CLI",n[n.LOADER=2]="LOADER",n[n.CODE_PAGE=3]="CODE_PAGE",n))(mM||{});const mpe={audio:Ade,board:jde,cli:$de,const:Xde,element:Jde,flags:Qde,gadget:hpe,lifecycle:fpe,loader:ppe},j1=["const","flags","audio","board","lifecycle","element"],gpe={0:[],1:["cli",...j1],2:["loader",...j1],3:["gadget",...j1]},_pe={0:new Map,1:new Map,2:new Map,3:new Map};function tg(n){return(gpe[n]??[]).map(t=>mpe[t]).filter(Z)}function vpe(n,e){const t=_pe[n];if(!t.has(e)){let r;const i=tg(n);for(let s=0;s>>=rB,i>0&&(r|=Tpe),t+=Epe.encode(r);while(i>0);return t};var ng={};(function(n){function e(R,M,O){if(M in R)return R[M];if(arguments.length===3)return O;throw new Error('"'+M+'" is a required argument.')}n.getArg=e;const t=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(R){const M=R.match(t);return M?{scheme:M[1],auth:M[2],host:M[3],port:M[4],path:M[5]}:null}n.urlParse=i;function s(R){let M="";return R.scheme&&(M+=R.scheme+":"),M+="//",R.auth&&(M+=R.auth+"@"),R.host&&(M+=R.host),R.port&&(M+=":"+R.port),R.path&&(M+=R.path),M}n.urlGenerate=s;const o=32;function a(R){const M=[];return function(O){for(let I=0;Io&&M.pop(),C}}const c=a(function(M){let O=M;const C=i(M);if(C){if(!C.path)return M;O=C.path}const I=n.isAbsolute(O),U=[];let L=0,P=0;for(;;)if(L=P,P=O.indexOf("/",L),P===-1){U.push(O.slice(L));break}else for(U.push(O.slice(L,P));P=0;P--){const H=U[P];H==="."?U.splice(P,1):H===".."?w++:w>0&&(H===""?(U.splice(P+1,w),w=0):(U.splice(P,2),w--))}return O=U.join("/"),O===""&&(O=I?"/":"."),C?(C.path=O,s(C)):O});n.normalize=c;function l(R,M){R===""&&(R="."),M===""&&(M=".");const O=i(M),C=i(R);if(C&&(R=C.path||"/"),O&&!O.scheme)return C&&(O.scheme=C.scheme),s(O);if(O||M.match(r))return M;if(C&&!C.host&&!C.path)return C.host=M,s(C);const I=M.charAt(0)==="/"?M:c(R.replace(/\/+$/,"")+"/"+M);return C?(C.path=I,s(C)):I}n.join=l,n.isAbsolute=function(R){return R.charAt(0)==="/"||t.test(R)};function u(R,M){R===""&&(R="."),R=R.replace(/\/$/,"");let O=0;for(;M.indexOf(R+"/")!==0;){const C=R.lastIndexOf("/");if(C<0||(R=R.slice(0,C),R.match(/^([^\/]+:\/)?\/*$/)))return M;++O}return Array(O+1).join("../")+M.substr(R.length+1)}n.relative=u;const h=function(){return!("__proto__"in Object.create(null))}();function d(R){return R}function m(R){return v(R)?"$"+R:R}n.toSetString=h?d:m;function g(R){return v(R)?R.slice(1):R}n.fromSetString=h?d:g;function v(R){if(!R)return!1;const M=R.length;if(M<9||R.charCodeAt(M-1)!==95||R.charCodeAt(M-2)!==95||R.charCodeAt(M-3)!==111||R.charCodeAt(M-4)!==116||R.charCodeAt(M-5)!==111||R.charCodeAt(M-6)!==114||R.charCodeAt(M-7)!==112||R.charCodeAt(M-8)!==95||R.charCodeAt(M-9)!==95)return!1;for(let O=M-10;O>=0;O--)if(R.charCodeAt(O)!==36)return!1;return!0}function y(R,M,O){let C=S(R.source,M.source);return C!==0||(C=R.originalLine-M.originalLine,C!==0)||(C=R.originalColumn-M.originalColumn,C!==0||O)||(C=R.generatedColumn-M.generatedColumn,C!==0)||(C=R.generatedLine-M.generatedLine,C!==0)?C:S(R.name,M.name)}n.compareByOriginalPositions=y;function _(R,M,O){let C=R.generatedLine-M.generatedLine;return C!==0||(C=R.generatedColumn-M.generatedColumn,C!==0||O)||(C=S(R.source,M.source),C!==0)||(C=R.originalLine-M.originalLine,C!==0)||(C=R.originalColumn-M.originalColumn,C!==0)?C:S(R.name,M.name)}n.compareByGeneratedPositionsDeflated=_;function S(R,M){return R===M?0:R===null?1:M===null?-1:R>M?1:-1}function E(R,M){let O=R.generatedLine-M.generatedLine;return O!==0||(O=R.generatedColumn-M.generatedColumn,O!==0)||(O=S(R.source,M.source),O!==0)||(O=R.originalLine-M.originalLine,O!==0)||(O=R.originalColumn-M.originalColumn,O!==0)?O:S(R.name,M.name)}n.compareByGeneratedPositionsInflated=E;function T(R){return JSON.parse(R.replace(/^\)]}'[^\n]*\n/,""))}n.parseSourceMapInput=T;function k(R,M,O){if(M=M||"",R&&(R[R.length-1]!=="/"&&M[0]!=="/"&&(R+="/"),M=R+M),O){const C=i(O);if(!C)throw new Error("sourceMapURL could not be parsed");if(C.path){const I=C.path.lastIndexOf("/");I>=0&&(C.path=C.path.substring(0,I+1))}M=l(s(C),M)}return c(M)}n.computeSourceURL=k})(ng);var gM={};let Ape=class sB{constructor(){this._array=[],this._set=new Map}static fromArray(e,t){const r=new sB;for(let i=0,s=e.length;i=0)return t;throw new Error('"'+e+'" is not in the set.')}at(e){if(e>=0&&et||r==t&&s>=i||aB.compareByGeneratedPositionsInflated(n,e)<=0}let Cpe=class{constructor(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}unsortedForEach(e,t){this._array.forEach(e,t)}add(e){Mpe(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))}toArray(){return this._sorted||(this._array.sort(aB.compareByGeneratedPositionsInflated),this._sorted=!0),this._array}};oB.MappingList=Cpe;const up=tB,Mr=ng,n_=gM.ArraySet,Rpe=oB.MappingList;let cB=class lB{constructor(e){e||(e={}),this._file=Mr.getArg(e,"file",null),this._sourceRoot=Mr.getArg(e,"sourceRoot",null),this._skipValidation=Mr.getArg(e,"skipValidation",!1),this._sources=new n_,this._names=new n_,this._mappings=new Rpe,this._sourcesContents=null}static fromSourceMap(e){const t=e.sourceRoot,r=new lB({file:e.file,sourceRoot:t});return e.eachMapping(function(i){const s={generated:{line:i.generatedLine,column:i.generatedColumn}};i.source!=null&&(s.source=i.source,t!=null&&(s.source=Mr.relative(t,s.source)),s.original={line:i.originalLine,column:i.originalColumn},i.name!=null&&(s.name=i.name)),r.addMapping(s)}),e.sources.forEach(function(i){let s=i;t!==null&&(s=Mr.relative(t,i)),r._sources.has(s)||r._sources.add(s);const o=e.sourceContentFor(i);o!=null&&r.setSourceContent(i,o)}),r}addMapping(e){const t=Mr.getArg(e,"generated"),r=Mr.getArg(e,"original",null);let i=Mr.getArg(e,"source",null),s=Mr.getArg(e,"name",null);this._skipValidation||this._validateMapping(t,r,i,s),i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),s!=null&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:i,name:s})}setSourceContent(e,t){let r=e;this._sourceRoot!=null&&(r=Mr.relative(this._sourceRoot,r)),t!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[Mr.toSetString(r)]=t):this._sourcesContents&&(delete this._sourcesContents[Mr.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))}applySourceMap(e,t,r){let i=t;if(t==null){if(e.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);i=e.file}const s=this._sourceRoot;s!=null&&(i=Mr.relative(s,i));const o=this._mappings.toArray().length>0?new n_:this._sources,a=new n_;this._mappings.unsortedForEach(function(c){if(c.source===i&&c.originalLine!=null){const h=e.originalPositionFor({line:c.originalLine,column:c.originalColumn});h.source!=null&&(c.source=h.source,r!=null&&(c.source=Mr.join(r,c.source)),s!=null&&(c.source=Mr.relative(s,c.source)),c.originalLine=h.line,c.originalColumn=h.column,h.name!=null&&(c.name=h.name))}const l=c.source;l!=null&&!o.has(l)&&o.add(l);const u=c.name;u!=null&&!a.has(u)&&a.add(u)},this),this._sources=o,this._names=a,e.sources.forEach(function(c){const l=e.sourceContentFor(c);l!=null&&(r!=null&&(c=Mr.join(r,c)),s!=null&&(c=Mr.relative(s,c)),this.setSourceContent(c,l))},this)}_validateMapping(e,t,r,i){if(t&&typeof t.line!="number"&&typeof t.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!t&&!r&&!i)){if(!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:t,name:i}))}}_serializeMappings(){let e=0,t=1,r=0,i=0,s=0,o=0,a="",c,l,u,h;const d=this._mappings.toArray();for(let m=0,g=d.length;m0){if(!Mr.compareByGeneratedPositionsInflated(l,d[m-1]))continue;c+=","}c+=up.encode(l.generatedColumn-e),e=l.generatedColumn,l.source!=null&&(h=this._sources.indexOf(l.source),c+=up.encode(h-o),o=h,c+=up.encode(l.originalLine-1-i),i=l.originalLine-1,c+=up.encode(l.originalColumn-r),r=l.originalColumn,l.name!=null&&(u=this._names.indexOf(l.name),c+=up.encode(u-s),s=u)),a+=c}return a}_generateSourcesContent(e,t){return e.map(function(r){if(!this._sourcesContents)return null;t!=null&&(r=Mr.relative(t,r));const i=Mr.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null},this)}toJSON(){const e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e}toString(){return JSON.stringify(this.toJSON())}};cB.prototype._version=3;eB.SourceMapGenerator=cB;var uB={};(function(n){n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2;function e(t,r,i,s,o,a){const c=Math.floor((r-t)/2)+t,l=o(i,s[c],!0);return l===0?c:l>0?r-c>1?e(c,r,i,s,o,a):a==n.LEAST_UPPER_BOUND?r1?e(t,c,i,s,o,a):a==n.LEAST_UPPER_BOUND?c:t<0?-1:t}n.search=function(r,i,s,o){if(i.length===0)return-1;let a=e(-1,i.length,r,i,s,o||n.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&s(i[a],i[a-1],!0)===0;)--a;return a}})(uB);var Sp={exports:{}};const kpe={},Npe=Object.freeze(Object.defineProperty({__proto__:null,default:kpe},Symbol.toStringTag,{value:"Module"})),JI=_z(Npe),Ipe=(function(){return typeof window<"u"&&this===window}).call();if(Ipe){let n=null;Sp.exports=function(){if(typeof n=="string")return fetch(n).then(t=>t.arrayBuffer());if(n instanceof ArrayBuffer)return Promise.resolve(n);throw new Error("You must provide the string URL or ArrayBuffer contents of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer")},Sp.exports.initialize=e=>n=e}else{const n=JI,e=JI;Sp.exports=function(){return new Promise((r,i)=>{const s=e.join(__dirname,"mappings.wasm");n.readFile(s,null,(o,a)=>{if(o){i(o);return}r(a.buffer)})})},Sp.exports.initialize=t=>{console.debug("SourceMapConsumer.initialize is a no-op when running in node.js")}}var hB=Sp.exports;const Ope=hB;function Lpe(){this.generatedLine=0,this.generatedColumn=0,this.lastGeneratedColumn=null,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}let hp=null;var Ppe=function(){if(hp)return hp;const e=[];return hp=Ope().then(t=>WebAssembly.instantiate(t,{env:{mapping_callback(r,i,s,o,a,c,l,u,h,d){const m=new Lpe;m.generatedLine=r+1,m.generatedColumn=i,s&&(m.lastGeneratedColumn=o-1),a&&(m.source=c,m.originalLine=l+1,m.originalColumn=u,h&&(m.name=d)),e[e.length-1](m)},start_all_generated_locations_for(){console.time("all_generated_locations_for")},end_all_generated_locations_for(){console.timeEnd("all_generated_locations_for")},start_compute_column_spans(){console.time("compute_column_spans")},end_compute_column_spans(){console.timeEnd("compute_column_spans")},start_generated_location_for(){console.time("generated_location_for")},end_generated_location_for(){console.timeEnd("generated_location_for")},start_original_location_for(){console.time("original_location_for")},end_original_location_for(){console.timeEnd("original_location_for")},start_parse_mappings(){console.time("parse_mappings")},end_parse_mappings(){console.timeEnd("parse_mappings")},start_sort_by_generated_location(){console.time("sort_by_generated_location")},end_sort_by_generated_location(){console.timeEnd("sort_by_generated_location")},start_sort_by_original_location(){console.time("sort_by_original_location")},end_sort_by_original_location(){console.timeEnd("sort_by_original_location")}}})).then(t=>({exports:t.instance.exports,withMappingCallback:(r,i)=>{e.push(r);try{i()}finally{e.pop()}}})).then(null,t=>{throw hp=null,t}),hp};const vt=ng,$1=uB,Vv=gM.ArraySet,Dpe=hB,Upe=Ppe,_M=Symbol("smcInternal");class _r{constructor(e,t){return e==_M?Promise.resolve(this):Bpe(e,t)}static initialize(e){Dpe.initialize(e["lib/mappings.wasm"])}static fromSourceMap(e,t){return zpe(e,t)}static async with(e,t,r){const i=await new _r(e,t);try{return await r(i)}finally{i.destroy()}}_parseMappings(e,t){throw new Error("Subclasses must implement _parseMappings")}eachMapping(e,t,r){throw new Error("Subclasses must implement eachMapping")}allGeneratedPositionsFor(e){throw new Error("Subclasses must implement allGeneratedPositionsFor")}destroy(){throw new Error("Subclasses must implement destroy")}}_r.prototype._version=3;_r.GENERATED_ORDER=1;_r.ORIGINAL_ORDER=2;_r.GREATEST_LOWER_BOUND=1;_r.LEAST_UPPER_BOUND=2;class rg extends _r{constructor(e,t){return super(_M).then(r=>{let i=e;typeof e=="string"&&(i=vt.parseSourceMapInput(e));const s=vt.getArg(i,"version");let o=vt.getArg(i,"sources");const a=vt.getArg(i,"names",[]);let c=vt.getArg(i,"sourceRoot",null);const l=vt.getArg(i,"sourcesContent",null),u=vt.getArg(i,"mappings"),h=vt.getArg(i,"file",null);if(s!=r._version)throw new Error("Unsupported version: "+s);return c&&(c=vt.normalize(c)),o=o.map(String).map(vt.normalize).map(function(d){return c&&vt.isAbsolute(c)&&vt.isAbsolute(d)?vt.relative(c,d):d}),r._names=Vv.fromArray(a.map(String),!0),r._sources=Vv.fromArray(o,!0),r._absoluteSources=r._sources.toArray().map(function(d){return vt.computeSourceURL(c,d,t)}),r.sourceRoot=c,r.sourcesContent=l,r._mappings=u,r._sourceMapURL=t,r.file=h,r._computedColumnSpans=!1,r._mappingsPtr=0,r._wasm=null,Upe().then(d=>(r._wasm=d,r))})}_findSourceIndex(e){let t=e;if(this.sourceRoot!=null&&(t=vt.relative(this.sourceRoot,t)),this._sources.has(t))return this._sources.indexOf(t);for(let r=0;r{a.source!==null&&(a.source=this._sources.at(a.source),a.source=vt.computeSourceURL(o,a.source,this._sourceMapURL),a.name!==null&&(a.name=this._names.at(a.name))),e.call(i,a)},()=>{switch(s){case _r.GENERATED_ORDER:this._wasm.exports.by_generated_location(this._getMappingsPtr());break;case _r.ORIGINAL_ORDER:this._wasm.exports.by_original_location(this._getMappingsPtr());break;default:throw new Error("Unknown order of iteration.")}})}allGeneratedPositionsFor(e){let t=vt.getArg(e,"source");const r=vt.getArg(e,"line"),i=e.column||0;if(t=this._findSourceIndex(t),t<0)return[];if(r<1)throw new Error("Line numbers must be >= 1");if(i<0)throw new Error("Column numbers must be >= 0");const s=[];return this._wasm.withMappingCallback(o=>{let a=o.lastGeneratedColumn;this._computedColumnSpans&&a===null&&(a=1/0),s.push({line:o.generatedLine,column:o.generatedColumn,lastColumn:a})},()=>{this._wasm.exports.all_generated_locations_for(this._getMappingsPtr(),t,r-1,"column"in e,i)}),s}destroy(){this._mappingsPtr!==0&&(this._wasm.exports.free_mappings(this._mappingsPtr),this._mappingsPtr=0)}computeColumnSpans(){this._computedColumnSpans||(this._wasm.exports.compute_column_spans(this._getMappingsPtr()),this._computedColumnSpans=!0)}originalPositionFor(e){const t={generatedLine:vt.getArg(e,"line"),generatedColumn:vt.getArg(e,"column")};if(t.generatedLine<1)throw new Error("Line numbers must be >= 1");if(t.generatedColumn<0)throw new Error("Column numbers must be >= 0");let r=vt.getArg(e,"bias",_r.GREATEST_LOWER_BOUND);r==null&&(r=_r.GREATEST_LOWER_BOUND);let i;if(this._wasm.withMappingCallback(s=>i=s,()=>{this._wasm.exports.original_location_for(this._getMappingsPtr(),t.generatedLine-1,t.generatedColumn,r)}),i&&i.generatedLine===t.generatedLine){let s=vt.getArg(i,"source",null);s!==null&&(s=this._sources.at(s),s=vt.computeSourceURL(this.sourceRoot,s,this._sourceMapURL));let o=vt.getArg(i,"name",null);return o!==null&&(o=this._names.at(o)),{source:s,line:vt.getArg(i,"originalLine",null),column:vt.getArg(i,"originalColumn",null),name:o}}return{source:null,line:null,column:null,name:null}}hasContentsOfAllSources(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1}sourceContentFor(e,t){if(!this.sourcesContent)return null;const r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];let i=e;this.sourceRoot!=null&&(i=vt.relative(this.sourceRoot,i));let s;if(this.sourceRoot!=null&&(s=vt.urlParse(this.sourceRoot))){const o=i.replace(/^file:\/\//,"");if(s.scheme=="file"&&this._sources.has(o))return this.sourcesContent[this._sources.indexOf(o)];if((!s.path||s.path=="/")&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(t)return null;throw new Error('"'+i+'" is not in the SourceMap.')}generatedPositionFor(e){let t=vt.getArg(e,"source");if(t=this._findSourceIndex(t),t<0)return{line:null,column:null,lastColumn:null};const r={source:t,originalLine:vt.getArg(e,"line"),originalColumn:vt.getArg(e,"column")};if(r.originalLine<1)throw new Error("Line numbers must be >= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");let i=vt.getArg(e,"bias",_r.GREATEST_LOWER_BOUND);i==null&&(i=_r.GREATEST_LOWER_BOUND);let s;if(this._wasm.withMappingCallback(o=>s=o,()=>{this._wasm.exports.generated_location_for(this._getMappingsPtr(),r.source,r.originalLine-1,r.originalColumn,i)}),s&&s.source===r.source){let o=s.lastGeneratedColumn;return this._computedColumnSpans&&o===null&&(o=1/0),{line:vt.getArg(s,"generatedLine",null),column:vt.getArg(s,"generatedColumn",null),lastColumn:o}}return{line:null,column:null,lastColumn:null}}}rg.prototype.consumer=_r;class Fpe extends _r{constructor(e,t){return super(_M).then(r=>{let i=e;typeof e=="string"&&(i=vt.parseSourceMapInput(e));const s=vt.getArg(i,"version"),o=vt.getArg(i,"sections");if(s!=r._version)throw new Error("Unsupported version: "+s);r._sources=new Vv,r._names=new Vv,r.__generatedMappings=null,r.__originalMappings=null,r.__generatedMappingsUnsorted=null,r.__originalMappingsUnsorted=null;let a={line:-1,column:0};return Promise.all(o.map(c=>{if(c.url)throw new Error("Support for url field in sections not implemented.");const l=vt.getArg(c,"offset"),u=vt.getArg(l,"line"),h=vt.getArg(l,"column");if(u({generatedOffset:{generatedLine:u+1,generatedColumn:h+1},consumer:m}))})).then(c=>(r._sections=c,r))})}get _generatedMappings(){return this.__generatedMappings||this._sortGeneratedMappings(),this.__generatedMappings}get _originalMappings(){return this.__originalMappings||this._sortOriginalMappings(),this.__originalMappings}get _generatedMappingsUnsorted(){return this.__generatedMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappingsUnsorted}get _originalMappingsUnsorted(){return this.__originalMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappingsUnsorted}_sortGeneratedMappings(){const e=this._generatedMappingsUnsorted;e.sort(vt.compareByGeneratedPositionsDeflated),this.__generatedMappings=e}_sortOriginalMappings(){const e=this._originalMappingsUnsorted;e.sort(vt.compareByOriginalPositions),this.__originalMappings=e}get sources(){const e=[];for(let t=0;ta.push(c));for(let c=0;c= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");const i=[];let s=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",vt.compareByOriginalPositions,$1.LEAST_UPPER_BOUND);if(s>=0){let o=this._originalMappings[s];if(e.column===void 0){const a=o.originalLine;for(;o&&o.originalLine===a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:vt.getArg(o,"generatedLine",null),column:vt.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}else{const a=o.originalColumn;for(;o&&o.originalLine===t&&o.originalColumn==a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:vt.getArg(o,"generatedLine",null),column:vt.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}}return i}destroy(){for(let e=0;e=0;t--)this.prepend(e[t]);else if(e[df]||typeof e=="string")this.children.unshift(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this}walk(e){let t;for(let r=0,i=this.children.length;r0){for(t=[],r=0;r{this.MANY(()=>this.SUBRULE(this.line))}));yt(this,"line",this.RULED("line",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt)},{ALT:()=>this.CONSUME(im)}])}));yt(this,"stmt",this.RULED("stmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.short_commands)),this.MANY(()=>this.SUBRULE(this.commands))}}])}));yt(this,"inline",this.RULED("inline",()=>{this.SUBRULE(this.instmt)}));yt(this,"instmt",this.RULED("instmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}])}));yt(this,"stmt_label",this.RULED("stmt_label",()=>{this.CONSUME(mF)}));yt(this,"stmt_stat",this.RULED("stmt_stat",()=>{this.CONSUME(uM)}));yt(this,"stmt_text",this.RULED("stmt_text",()=>{this.OR([{ALT:()=>this.CONSUME(dF)}])}));yt(this,"stmt_comment",this.RULED("stmt_comment",()=>{this.CONSUME(pF)}));yt(this,"stmt_hyperlink",this.RULED("stmt_hyperlink",()=>{this.CONSUME(gF),this.SUBRULE(this.words),this.CONSUME(_F)}));yt(this,"stmt_command",this.RULED("stmt_command",()=>{this.CONSUME(yf),this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}));yt(this,"short_commands",this.RULED("short_commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)}])}));yt(this,"commands",this.RULED("commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.words)},{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)},{ALT:()=>this.SUBRULE(this.command_play)},{ALT:()=>this.SUBRULE(this.structured_cmd)}])}));yt(this,"structured_cmd",this.RULED("structured_cmd",()=>{this.OR([{ALT:()=>this.SUBRULE(this.command_debugger)},{ALT:()=>this.SUBRULE(this.command_if)},{ALT:()=>this.SUBRULE(this.command_while)},{ALT:()=>this.SUBRULE(this.command_repeat)},{ALT:()=>this.SUBRULE(this.command_waitfor)},{ALT:()=>this.SUBRULE(this.command_foreach)},{ALT:()=>this.SUBRULE(this.command_break)},{ALT:()=>this.SUBRULE(this.command_continue)}])}));yt(this,"short_go",this.RULED("short_go",()=>{this.CONSUME(lT),this.SUBRULE(this.words)}));yt(this,"short_try",this.RULED("short_try",()=>{this.CONSUME(kF),this.SUBRULE(this.words)}));yt(this,"command_debugger",this.RULED("command_debugger",()=>{this.CONSUME(LF)}));yt(this,"command_if",this.RULED("command_if",()=>{this.CONSUME(uT),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_if_block))}));yt(this,"command_if_block",this.RULED("command_if_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(z_),this.MANY(()=>this.SUBRULE(this.line)),this.MANY2({GATE:this.BACKTRACK(this.command_else_if),DEF:()=>this.SUBRULE(this.command_else_if)}),this.OPTION(()=>this.SUBRULE(this.command_else)),this.MANY3(()=>this.CONSUME3(im)),this.CONSUME4(yf),this.CONSUME4(hT)}}])}));yt(this,"command_block",this.RULED("command_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(z_),this.MANY(()=>this.SUBRULE(this.line)),this.CONSUME(yf),this.CONSUME(hT)}}])}));yt(this,"command_fork",this.RULED("command_fork",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(z_),this.MANY({GATE:this.BACKTRACK(this.line),DEF:()=>this.SUBRULE(this.line)})}}])}));yt(this,"command_else_if",this.RULED("command_else_if",()=>{this.CONSUME(yf),this.CONSUME(fT),this.CONSUME(uT),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_fork))}));yt(this,"command_else",this.RULED("command_else",()=>{this.CONSUME(yf),this.CONSUME(fT),this.OPTION(()=>this.SUBRULE(this.command_fork))}));yt(this,"command_while",this.RULED("command_while",()=>{this.CONSUME(PF),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));yt(this,"command_repeat",this.RULED("command_repeat",()=>{this.CONSUME(DF),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));yt(this,"command_waitfor",this.RULED("command_waitfor",()=>{this.CONSUME(UF),this.SUBRULE(this.words)}));yt(this,"command_foreach",this.RULED("command_foreach",()=>{this.CONSUME(FF),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));yt(this,"command_break",this.RULED("command_break",()=>{this.CONSUME(BF)}));yt(this,"command_continue",this.RULED("command_continue",()=>{this.CONSUME(zF)}));yt(this,"command_play",this.RULED("command_play",()=>{this.CONSUME(OF)}));yt(this,"expr",this.RULED("expr",()=>{this.SUBRULE1(this.and_test),this.MANY(()=>{this.CONSUME(iT),this.SUBRULE2(this.and_test)})}));yt(this,"and_test",this.RULED("and_test",()=>{this.SUBRULE1(this.not_test),this.MANY(()=>{this.CONSUME(oT),this.SUBRULE2(this.not_test)})}));yt(this,"not_test",this.RULED("not_test",()=>{this.OR([{ALT:()=>{this.CONSUME(sT),this.SUBRULE1(this.not_test)}},{ALT:()=>this.SUBRULE2(this.comparison)}])}));yt(this,"comparison",this.RULED("comparison",()=>{this.SUBRULE1(this.arith_expr),this.MANY(()=>{this.SUBRULE(this.comp_op),this.SUBRULE2(this.arith_expr)})}));yt(this,"comp_op",this.RULED("comp_op",()=>{this.OR([{ALT:()=>this.CONSUME(xF)},{ALT:()=>this.CONSUME(SF)},{ALT:()=>this.CONSUME(EF)},{ALT:()=>this.CONSUME(bF)},{ALT:()=>this.CONSUME(TF)},{ALT:()=>this.CONSUME(wF)}])}));yt(this,"expr_value",this.RULED("expr_value",()=>{this.SUBRULE1(this.and_test_value),this.MANY(()=>{this.CONSUME(iT),this.SUBRULE2(this.and_test_value)})}));yt(this,"and_test_value",this.RULED("and_test_value",()=>{this.SUBRULE1(this.not_test_value),this.MANY(()=>{this.CONSUME(oT),this.SUBRULE2(this.not_test_value)})}));yt(this,"not_test_value",this.RULED("not_test_value",()=>{this.OR([{ALT:()=>{this.CONSUME(sT),this.SUBRULE1(this.not_test_value)}},{ALT:()=>this.SUBRULE2(this.arith_expr)}])}));yt(this,"arith_expr",this.RULED("arith_expr",()=>{this.SUBRULE1(this.term),this.MANY(()=>this.SUBRULE2(this.arith_expr_item))}));yt(this,"arith_expr_item",this.RULED("arith_expr_item",()=>{this.OR([{ALT:()=>this.CONSUME(aT)},{ALT:()=>this.CONSUME(cT)}]),this.SUBRULE(this.term)}));yt(this,"term",this.RULED("term",()=>{this.SUBRULE1(this.factor),this.MANY(()=>this.SUBRULE2(this.term_item))}));yt(this,"term_item",this.RULED("term_item",()=>{this.OR([{ALT:()=>this.CONSUME(MF)},{ALT:()=>this.CONSUME(lT)},{ALT:()=>this.CONSUME(CF)},{ALT:()=>this.CONSUME(RF)}]),this.SUBRULE(this.factor)}));yt(this,"factor",this.RULED("factor",()=>{this.OR1([{ALT:()=>{this.OR2([{ALT:()=>this.CONSUME(aT)},{ALT:()=>this.CONSUME(cT)}]),this.SUBRULE(this.factor)}},{ALT:()=>this.SUBRULE(this.power)}])}));yt(this,"power",this.RULED("power",()=>{this.SUBRULE(this.token),this.OPTION(()=>{this.CONSUME(AF),this.SUBRULE(this.factor)})}));yt(this,"words",this.RULED("words",()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.expr))}));yt(this,"token",this.RULED("token",()=>{this.OR([{ALT:()=>this.CONSUME(vF)},{ALT:()=>this.CONSUME(Yi)},{ALT:()=>this.CONSUME(yF)},{ALT:()=>{this.CONSUME(NF),this.SUBRULE(this.expr),this.CONSUME(IF)}}])}));this.performSelfAnalysis()}PEEK(t,r,...i){console.info(t,i.map(s=>[s.image,s.tokenType]),r)}RULED(t,r,i){const s=$pe.some(o=>t.includes(o));return this.RULE(t,()=>{const a=(QI++).toString().padStart(3),c=s?"font-weight: bold;":"";if(eO&&!this.RECORDING_PHASE){const l=[this.LA(1),this.LA(2),this.LA(3)].map(u=>`[${u.tokenType.name} ${u.image.replaceAll(` +`,"\\n")}]`);console.info(`${a}%c> ${t} ${l.join(" ")}`,c)}r(),eO&&!this.RECORDING_PHASE&&console.info(`${a}%c< ${t} `,c),QI--},i)}}const Cf=new qpe;if(sle){const n=Cf.getGAstProductions(),e=Xfe(n);console.info(e)}const Xpe=Cf.getBaseCstVisitorConstructor();var Ke=(n=>(n[n.PROGRAM=0]="PROGRAM",n[n.API=1]="API",n[n.LINE=2]="LINE",n[n.MARK=3]="MARK",n[n.GOTO=4]="GOTO",n[n.COUNT=5]="COUNT",n[n.TEXT=6]="TEXT",n[n.LABEL=7]="LABEL",n[n.HYPERLINK=8]="HYPERLINK",n[n.STAT=9]="STAT",n[n.MOVE=10]="MOVE",n[n.COMMAND=11]="COMMAND",n[n.LITERAL=12]="LITERAL",n[n.IF=13]="IF",n[n.IF_CHECK=14]="IF_CHECK",n[n.IF_BLOCK=15]="IF_BLOCK",n[n.ELSE_IF=16]="ELSE_IF",n[n.ELSE=17]="ELSE",n[n.WHILE=18]="WHILE",n[n.BREAK=19]="BREAK",n[n.CONTINUE=20]="CONTINUE",n[n.REPEAT=21]="REPEAT",n[n.WAITFOR=22]="WAITFOR",n[n.FOREACH=23]="FOREACH",n[n.OR=24]="OR",n[n.AND=25]="AND",n[n.NOT=26]="NOT",n[n.COMPARE=27]="COMPARE",n[n.COMPARE_ITEM=28]="COMPARE_ITEM",n[n.OPERATOR=29]="OPERATOR",n[n.OPERATOR_ITEM=30]="OPERATOR_ITEM",n[n.EXPR=31]="EXPR",n))(Ke||{}),Iu=(n=>(n[n.IS_EQ=0]="IS_EQ",n[n.IS_NOT_EQ=1]="IS_NOT_EQ",n[n.IS_LESS_THAN=2]="IS_LESS_THAN",n[n.IS_GREATER_THAN=3]="IS_GREATER_THAN",n[n.IS_LESS_THAN_OR_EQ=4]="IS_LESS_THAN_OR_EQ",n[n.IS_GREATER_THAN_OR_EQ=5]="IS_GREATER_THAN_OR_EQ",n))(Iu||{}),pa=(n=>(n[n.EMPTY=0]="EMPTY",n[n.PLUS=1]="PLUS",n[n.MINUS=2]="MINUS",n[n.POWER=3]="POWER",n[n.MULTIPLY=4]="MULTIPLY",n[n.DIVIDE=5]="DIVIDE",n[n.MOD_DIVIDE=6]="MOD_DIVIDE",n[n.FLOOR_DIVIDE=7]="FLOOR_DIVIDE",n[n.UNI_PLUS=8]="UNI_PLUS",n[n.UNI_MINUS=9]="UNI_MINUS",n))(pa||{}),V_=(n=>(n[n.NUMBER=0]="NUMBER",n[n.STRING=1]="STRING",n[n.TEMPLATE=2]="TEMPLATE",n))(V_||{});function Kpe(n){return!!(n!=null&&n.tokenType)}function Ec(n,e){const[t]=n??[];return((t==null?void 0:t.image)??e).trimStart().replaceAll(/^"|"$/g,"")}class Ype extends Xpe{constructor(){super();yt(this,"unique",0);ja&&this.validateVisitor()}getnodelocation(t){const r=Object.values(t).flat().filter(i=>!!i).map(i=>i&&Kpe(i)?{startLine:i.startLine,startColumn:i.startColumn,startOffset:i.startOffset,endLine:i.endLine,endColumn:i.endColumn,endOffset:i.endOffset}:i!=null&&i.location?{...i.location}:{startLine:0,startColumn:0,startOffset:0,endLine:0,endColumn:0,endOffset:0}).filter(i=>i.startLine!==0&&i.endLine!==0);return{startLine:Math.min(...r.map(i=>i.startLine??1)),startColumn:Math.min(...r.map(i=>i.startColumn??1)),startOffset:Math.min(...r.map(i=>i.startOffset??1)),endLine:Math.max(...r.map(i=>i.endLine??1)),endColumn:Math.max(...r.map(i=>i.endColumn??1)),endOffset:Math.max(...r.map(i=>i.endOffset??1))}}createcodenode(t,r){return[{...r,...this.getnodelocation(t),lineindex:0}]}createstringnode(t,r){return this.createcodenode(t,{type:12,literal:1,value:r})}createmarknode(t,r,i){return this.createlinenode(t,this.createcodenode(t,{type:3,id:r,comment:i}))}creategotonode(t,r,i){return this.createlinenode(t,this.createcodenode(t,{type:4,id:r,comment:i}))}createlinenode(t,r){return this.createcodenode(t,{type:2,stmts:r})}createapinode(t,r,i){return this.createlinenode(t,this.createcodenode(t,{type:1,words:i,method:r}))}createlogicnode(t,r,i,s){return this.createlinenode(t,this.createcodenode(t,{type:14,skip:i,words:s,method:r}))}createcountnode(t){return this.createcodenode(t,{type:5,index:this.unique++})}go(t){return Array.isArray(t)?t.map(r=>this.visit(r)).flat():Z(t)?[this.visit(t)].flat():[]}program(t){return this.unique=0,this.createcodenode(t,{type:0,lines:[this.createlinenode(t,this.createcodenode(t,{type:7,active:!0,name:"restart"})),this.go(t.line)].flat()})}line(t){return t.stmt?this.go(t.stmt):[]}stmt(t){return t.stmt_label?this.go(t.stmt_label):t.stmt_stat?this.go(t.stmt_stat):t.stmt_text?this.go(t.stmt_text):t.stmt_comment?this.go(t.stmt_comment):t.stmt_command?this.go(t.stmt_command):t.stmt_hyperlink?this.go(t.stmt_hyperlink):t.short_commands?[this.go(t.short_commands),this.go(t.commands)].flat():[]}inline(t){return this.go(t.instmt)}instmt(t){return t.stmt_label?this.go(t.stmt_label):t.stmt_stat?this.go(t.stmt_stat):t.stmt_text?this.go(t.stmt_text):t.stmt_comment?this.go(t.stmt_comment):t.stmt_command?this.go(t.stmt_command):t.stmt_hyperlink?this.go(t.stmt_hyperlink):t.commands?this.go(t.commands):[]}stmt_label(t){return this.createlinenode(t,this.createcodenode(t,{type:7,active:!0,name:Ec(t.token_label,":").slice(1).trim()}))}stmt_stat(t){return this.createlinenode(t,this.createcodenode(t,{type:9,value:Ec(t.token_stat,"@").slice(1)}))}stmt_text(t){return this.createlinenode(t,this.createcodenode(t,{type:6,value:Ec(t.token_text,"")}))}stmt_comment(t){return this.createlinenode(t,this.createcodenode(t,{type:7,active:!1,name:Ec(t.token_comment,"'").slice(1).trim()}))}stmt_hyperlink(t){return this.createlinenode(t,this.createcodenode(t,{type:8,link:this.go(t.words),text:Ec(t.token_hyperlinktext,";").slice(1)}))}stmt_command(t){return t.commands?this.go(t.commands):[]}short_commands(t){return t.short_go?this.go(t.short_go):t.short_try?this.go(t.short_try):[]}commands(t){return t.words?this.createlinenode(t,this.createcodenode(t,{type:11,words:this.go(t.words)})):t.short_go?this.go(t.short_go):t.short_try?this.go(t.short_try):t.command_play?this.go(t.command_play):t.structured_cmd?this.go(t.structured_cmd):[]}structured_cmd(t){return t.command_if?this.go(t.command_if):t.command_while?this.go(t.command_while):t.command_repeat?this.go(t.command_repeat):t.command_waitfor?this.go(t.command_waitfor):t.command_foreach?this.go(t.command_foreach):t.command_break?this.go(t.command_break):t.command_continue?this.go(t.command_continue):[]}short_go(t){return t.token_divide?this.createlinenode(t,this.createcodenode(t,{type:10,wait:!0,words:this.go(t.words)})):[]}short_try(t){return t.token_query?this.createlinenode(t,this.createcodenode(t,{type:10,wait:!1,words:this.go(t.words)})):[]}command_if(t){const[r]=this.createlogicnode(t,"if","",this.go(t.words)),[i]=this.go(t.command_if_block)??[];return this.createcodenode(t,{type:13,check:r,block:i})}command_if_block(t){const r=gr(),i=gr();return this.createcodenode(t,{type:15,skip:r,done:i,lines:[this.go(t.inline),this.go(t.line),this.creategotonode(t,i,"end of if"),this.createmarknode(t,r,"alt logic")].flat(),altlines:[this.go(t.command_else_if),this.go(t.command_else),this.createmarknode(t,i,"end of if")].flat()})}command_block(t){return[this.go(t.inline),this.go(t.line)].flat()}command_fork(t){return[this.go(t.inline),this.go(t.line)].flat()}command_else_if(t){const r=gr(),i=gr();return this.createcodenode(t,{type:16,done:i,lines:[this.createlogicnode(t,"if",r,this.go(t.words)),this.go(t.command_fork),this.creategotonode(t,i,"end of if"),this.createmarknode(t,r,"skip")].flat()})}command_else(t){return this.createcodenode(t,{type:17,lines:this.go(t.command_fork)})}command_while(t){const r=gr(),i=gr();return this.createcodenode(t,{type:18,loop:r,done:i,lines:[this.createmarknode(t,r,"start of while"),this.createlogicnode(t,"if",i,this.go(t.words)),this.go(t.command_block),this.creategotonode(t,r,"loop of while"),this.createmarknode(t,i,"end of while")].flat()})}command_repeat(t){const r=gr(),i=gr(),o=[this.createcountnode(t),this.go(t.words)].flat();return this.createcodenode(t,{type:21,loop:r,done:i,lines:[this.createapinode(t,"repeatstart",o),this.createmarknode(t,r,"start of repeat"),this.createlogicnode(t,"repeat",i,o),this.go(t.command_block),this.creategotonode(t,r,"loop of repeat"),this.createmarknode(t,i,"end of repeat")].flat()})}command_foreach(t){const r=gr(),i=gr(),o=[this.createcountnode(t),this.go(t.words)].flat();return this.createcodenode(t,{type:23,loop:r,done:i,lines:[this.createapinode(t,"foreachstart",o),this.createmarknode(t,r,"start of foreach"),this.createlogicnode(t,"foreach",i,o),this.go(t.command_block),this.creategotonode(t,r,"loop of foreach"),this.createmarknode(t,i,"end of foreach")].flat()})}command_waitfor(t){return this.createcodenode(t,{type:22,words:this.go(t.words)})}command_break(t){return this.createcodenode(t,{type:19,goto:0})}command_continue(t){return this.createcodenode(t,{type:20,goto:0})}command_play(t){const r=Ec(t.token_command_play,""),i=r.replace("bgplay","").replace("play","").trim(),s=r.includes("bgplay");return this.createlinenode(t,this.createcodenode(t,{type:11,words:[this.createstringnode(t,s?"bgplay":"play"),this.createstringnode(t,i)].flat()}))}expr(t){return t.and_test.length===1?this.go(t.and_test):this.createcodenode(t,{type:24,items:this.go(t.and_test)})}and_test(t){return t.not_test.length===1?this.go(t.not_test):this.createcodenode(t,{type:25,items:this.go(t.not_test)})}not_test(t){return t.comparison?this.go(t.comparison):t.not_test?this.createcodenode(t,{type:26,items:this.go(t.not_test)}):[]}comparison(t){if(t.arith_expr.length===1)return this.go(t.arith_expr);const[r,i]=this.go(t.arith_expr),[s]=this.go(t.comp_op);return this.createcodenode(t,{type:27,lhs:r,compare:s,rhs:i})}comp_op(t){return t.token_iseq?this.createcodenode(t,{type:28,method:0}):t.token_isnoteq?this.createcodenode(t,{type:28,method:1}):t.token_islessthan?this.createcodenode(t,{type:28,method:2}):t.token_isgreaterthan?this.createcodenode(t,{type:28,method:3}):t.token_isgreaterthanorequal?this.createcodenode(t,{type:28,method:4}):t.token_isgreaterthanorequal?this.createcodenode(t,{type:28,method:5}):[]}expr_value(t){return t.and_test_value.length===1?this.go(t.and_test_value):this.createcodenode(t,{type:24,items:this.go(t.and_test_value)})}and_test_value(t){return t.not_test_value.length===1?this.go(t.not_test_value):this.createcodenode(t,{type:25,items:this.go(t.not_test_value)})}not_test_value(t){return t.arith_expr?this.go(t.arith_expr):t.not_test_value?this.createcodenode(t,{type:26,items:this.go(t.not_test_value)}):[]}arith_expr(t){const r=this.go(t.term);return t.arith_expr_item?this.createcodenode(t,{type:29,lhs:r[0],items:this.go(t.arith_expr_item)}):r}arith_expr_item(t){return this.createcodenode(t,{type:30,operator:t.token_plus?1:2,rhs:this.go(t.term)[0]})}term(t){return t.term_item?this.createcodenode(t,{type:29,lhs:this.go(t.factor)[0],items:this.go(t.term_item)}):this.go(t.factor)}term_item(t){let r=0;return t.token_multiply&&(r=4),t.token_divide&&(r=5),t.token_moddivide&&(r=6),t.token_floordivide&&(r=7),this.createcodenode(t,{type:30,operator:r,rhs:this.go(t.factor)[0]})}factor(t){if(t.power)return this.go(t.power);let r=0;return t.token_plus&&(r=8),t.token_minus&&(r=9),this.createcodenode(t,{type:29,lhs:void 0,items:this.createcodenode(t,{type:30,operator:r,rhs:this.go(t.factor)[0]})})}power(t){const r=this.go(t.token);return t.factor?this.createcodenode(t,{type:29,lhs:r[0],items:this.createcodenode(t,{type:30,operator:3,rhs:this.go(t.factor)[0]})}):r}words(t){return this.go(t.expr)}token(t){if(t.token_stringliteraldouble){const r=Ec(t.token_stringliteraldouble,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(t,{type:12,literal:2,value:r})}if(t.token_stringliteral){const r=Ec(t.token_stringliteral,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(t,{type:12,literal:1,value:r})}if(t.token_numberliteral){const r=parseFloat(Ec(t.token_numberliteral,"0"));return this.createcodenode(t,{type:12,literal:0,value:r})}return t.token_lparen?this.createcodenode(t,{type:31,words:this.go(t.expr)}):[]}}const Zpe=new Ype,us={labels:{},internal:0,lineindex:0,linelookup:{},isfirststat:!1},px="zss.js";function on(n,e){return new jpe(n.startLine??1,n.startColumn??1,px,e)}function vT(n){return n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function q1(n){return`'${vT(n)}'`}function H_(n){if(n.startsWith('"'))return H_(n.replaceAll(/(^"|"$)/g,""));const e=gx(n);return e.errors.length?n:`['${e.tokens.map(r=>r.tokenType===EM?`', api.get('${vT(r.image.substring(1))}'), '`:vT(r.image)).join("")}'].join('')`}function Mu(n){return n.filter(e=>e!==void 0).map(En)}function tO(n){return on(n,"")}function Jpe(n,e){const t=[];return n.forEach(r=>{t.push(r,e)}),t.pop(),t}function Or(n,e,t){return on(n,[`api.${e}(`,...Jpe(t,", "),")"])}function Qpe(n){if(n.type===Ke.COMPARE&&n.compare.type===Ke.COMPARE_ITEM)switch(n.compare.method){case Iu.IS_EQ:return Or(n,"isEq",[En(n.lhs),En(n.rhs)]);case Iu.IS_NOT_EQ:return Or(n,"isNotEq",[En(n.lhs),En(n.rhs)]);case Iu.IS_LESS_THAN:return Or(n,"isLessThan",[En(n.lhs),En(n.rhs)]);case Iu.IS_GREATER_THAN:return Or(n,"isGreaterThan",[En(n.lhs),En(n.rhs)]);case Iu.IS_LESS_THAN_OR_EQ:return Or(n,"isLessThanOrEq",[En(n.lhs),En(n.rhs)]);case Iu.IS_GREATER_THAN_OR_EQ:return Or(n,"isGreaterThanOrEq",[En(n.lhs),En(n.rhs)])}return on(n,"")}function Cu(n,e,t){return n.prepend(`api.${e}(`),n.add([", ",En(t),")"])}function nO(n,e,t){return n.prepend(`api.${e}(`),n.add([En(t),")"])}function eme(n,e){if(n.type===Ke.OPERATOR_ITEM)switch(n.operator){case pa.PLUS:return Cu(e,"opPlus",n.rhs);case pa.MINUS:return Cu(e,"opMinus",n.rhs);case pa.POWER:return Cu(e,"opPower",n.rhs);case pa.MULTIPLY:return Cu(e,"opMultiply",n.rhs);case pa.DIVIDE:return Cu(e,"opDivide",n.rhs);case pa.MOD_DIVIDE:return Cu(e,"opModDivide",n.rhs);case pa.FLOOR_DIVIDE:return Cu(e,"opFloorDivide",n.rhs);case pa.UNI_PLUS:return nO(e,"opUniPlus",n.rhs);case pa.UNI_MINUS:return nO(e,"opUniMinus",n.rhs)}return on(n,"")}function tme(n){if(n.type===Ke.OPERATOR){const e=n.lhs?En(n.lhs):on(n,"");return n.items.forEach(t=>eme(t,e)),e}return on(n,"")}function i_(n,e){return on(n,[Or(n,"jump",[`${e}`]),"; continue;"])}function bc(n){return us.linelookup[n??""]??-1}function yT(n,e){us.linelookup[n]=e}function Ep(n,e,t){for(let r=0;rr.add(En(i))),dB(t.altlines,Ke.ELSE_IF,bc(t.done)),t.altlines.forEach(i=>r.add(En(i))),r}return on(n,En(n.check))}case Ke.IF_CHECK:{const t=bc(n.skip);return t===-1?on(n,[" ",Or(n,n.method,Mu(n.words)),`; +`]):on(n,[" if (!",Or(n,n.method,Mu(n.words)),") { ",i_(n,t),` } +`])}case Ke.ELSE_IF:case Ke.ELSE:{const t=on(n,"");return n.lines.forEach(r=>t.add(En(r))),t}case Ke.WHILE:{const t=bc(n.loop),r=bc(n.done),i=on(n,"");return Ep(n.lines,Ke.IF_CHECK,n.done),n.lines.forEach(s=>{switch(s.type){case Ke.BREAK:s.goto=r;break;case Ke.CONTINUE:s.goto=t;break}i.add(En(s))}),i}case Ke.REPEAT:{const t=bc(n.loop),r=bc(n.done),i=on(n,"");return Ep(n.lines,Ke.IF_CHECK,n.done),n.lines.forEach(s=>{switch(s.type){case Ke.BREAK:s.goto=r;break;case Ke.CONTINUE:s.goto=t;break}i.add(En(s))}),i}case Ke.WAITFOR:{const t=on(n,"");return t.add([" if (!",Or(n,"if",Mu(n.words)),`) { api.i(${n.lineindex-1}); } +`]),t}case Ke.FOREACH:{const t=bc(n.loop),r=bc(n.done),i=on(n,"");return Ep(n.lines,Ke.IF_CHECK,n.done),n.lines.forEach(s=>{switch(s.type){case Ke.BREAK:s.goto=r;break;case Ke.CONTINUE:s.goto=t;break}i.add(En(s))}),i}case Ke.BREAK:return on(n,[" ",i_(n,n.goto),` +`]);case Ke.CONTINUE:return on(n,[" ",i_(n,n.goto),` +`]);case Ke.OR:return Or(n,"or",n.items.map(En));case Ke.AND:return Or(n,"and",n.items.map(En));case Ke.NOT:return Or(n,"not",n.items.map(En));case Ke.COMPARE:return Qpe(n);case Ke.OPERATOR:return tme(n);case Ke.EXPR:return Or(n,"expr",n.words.map(En));default:return console.error("",n.type,n),tO(n)}}function ma(n){if(Z(n))switch(n.type===Ke.LINE&&++us.lineindex,n.lineindex=us.lineindex,n.type){case Ke.PROGRAM:n.lines.forEach(ma);break;case Ke.LINE:n.stmts.forEach(ma);break;case Ke.MARK:yT(n.id,n.lineindex);break;case Ke.IF:ma(n.check),ma(n.block);break;case Ke.IF_BLOCK:n.lines.forEach(ma),n.altlines.forEach(ma);break;case Ke.ELSE_IF:n.lines.forEach(ma);break;case Ke.ELSE:case Ke.WHILE:case Ke.REPEAT:case Ke.FOREACH:n.lines.forEach(ma);break;case Ke.MOVE:case Ke.COMMAND:case Ke.WAITFOR:case Ke.IF_CHECK:n.words.forEach(ma);break}}function nme(n){return us.labels={},us.internal=1,us.lineindex=0,us.isfirststat=!0,ma(n),{...En(n).toStringWithSourceMap({file:`${px}.map`}),...us}}const rme={HALT_AT_COUNT:256};function ime(n){return cn(n)?n.length>0?1:0:n??0}function ai(n){return`${n??""}`}function sme(n){return`${n}_chip`}function ome(n,e,t){var c,l;const r=sme(n),i=sm(r);let s;cn(i.lb)||(i.lb=rw(Object.entries(t.labels??{})),i.lk="",i.mg=void 0,i.ec=1,i.lc=0,i.ys=0,i.ps=0,i.es=(((c=t.errors)==null?void 0:c.length)??0)!==0?1:0);function o(u,h){se.words=h;const d=vpe(e,u);return Z(d)?d(a,h):u!=="send"?o("send",[u,...h]):0}const a={halt(){pme(r)},id(){return n},senderid(u=n){return`vm:${u??n}`},set(u,h){const[d,m]=xpe(e,a,u,h);if(d)return m},get(u){const[h,d]=ype(e,a,u);if(h)return d},bucket(u){const h=a.get("bucket");cn(h)?h.push(u):a.set("bucket",[u])},tick(u){const h=gt(i.ps)?i.ps:0,d=h%u===0;if(i.ps=h+1,d===!1)return!1;if(a.shouldtick()===!1)return YI(e,a),!1;i.lc=0,i.ys=0,se.get=a.get,Spe(e,a);try{const m=s==null?void 0:s.next();m!=null&&m.done&&(An("chip","crash","generator logic unexpectedly exited"),i.es=1)}catch(m){An("chip","crash",m.message),i.es=1}return YI(e,a),!0},isended(){return i.es===1},shouldtick(){return i.es===0||a.hm()!==0},shouldhalt(){return gt(i.lc)?++i.lc>rme.HALT_AT_COUNT:!0},hm(){if(cn(i.mg)&&cn(i.lb)){const[,u]=i.mg;if(Z(u))for(let h=0;hgt(g)&&g>0)??0}}return 0},yield(){i.ys=1},jump(u){i.ec=u},sy(){return!!i.ys||a.shouldhalt()},emit(u,h,d){Pt.emit(u,a.senderid(),h,d)},send(u,h,d,m){Pt.emit(`${a.senderid(u)}:${h}`,n,d,m)},lock(u){i.lk=u},unlock(){i.lk=""},message(u){i.lk&&u.sender!==i.lk||(i.mg=[u.id,u.target,u.data,u.sender,u.player])},zap(u){if(cn(i.lb))for(let h=0;hv>0);g>=0&&(m[g]*=-1)}}},restore(u){if(cn(i.lb))for(let h=0;hm.fileName===px);return{line:(d==null?void 0:d.lineNumber)??0,column:(d==null?void 0:d.columnNumber)??0}},text(u){return o("text",[u])},stat(...u){return o("stat",u)},hyperlink(...u){return o("hyperlink",u)},command(...u){if(u.length===0)return 0;const[h,...d]=u;return o(ai(h),d)},if(...u){const[h,d]=Ve(u,0,[Ie.ANY]),m=ime(h);return m&&d0,v=i[d];return g&&cn(v)&&a.command(...v),g?1:0},foreachstart(u,...h){const[d,m,g,v]=Ve(h,0,[Ie.STRING,Ie.NUMBER,Ie.NUMBER,Ie.MAYBE_NUMBER]);let y=Math.min(m,g),_=Math.max(m,g);const S=(v??0)||1;if(S<0){const E=y;y=_,_=E}return a.set(d,y-S),0},foreach(u,...h){const[d,m,g,v,y]=Ve(h,0,[Ie.STRING,Ie.NUMBER,Ie.NUMBER,Ie.MAYBE_NUMBER]);let _=Math.min(m,g),S=Math.max(m,g);const E=(v??0)||1;if(E<0){const R=_;_=S,S=R}let T=a.get(d);!gt(T)||T<_||T>S?T=_:T+=E;const k=T<=S?1:0;return k&&(a.set(d,T),ym?1:0},isLessThanOrEq(u,h){const[d]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return d<=m?1:0},isGreaterThanOrEq(u,h){const[d]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return d>=m?1:0},opPlus(u,h){const[d]=Ve([u],0,[Ie.ANY]),[m]=Ve([h],0,[Ie.ANY]);return d+m},opMinus(u,h){const[d]=Ve([u],0,[Ie.ANY]),[m]=Ve([h],0,[Ie.ANY]);return d-m},opPower(u,h){const[d]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return Math.pow(d,m)},opMultiply(u,h){const[d]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return d*m},opDivide(u,h){const[d]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return d/m},opModDivide(u,h){const[d]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return d%m},opFloorDivide(u,h){const[d]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return Math.floor(d/m)},opUniPlus(u){const[h]=Ve([u],0,[Ie.NUMBER]);return+h},opUniMinus(u){const[h]=Ve([u],0,[Ie.NUMBER]);return-h}};return s=(l=t.code)==null?void 0:l.call(t,a),a}function s_(n){throw new Error('Could not dynamically require "'+n+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var ame={exports:{}};/*! + +JSZip v3.10.1 - A JavaScript class for generating and reading zip files + + +(c) 2009-2016 Stuart Knightley +Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. + +JSZip uses the library pako released under the MIT license : +https://github.com/nodeca/pako/blob/main/LICENSE +*/(function(n,e){(function(t){n.exports=t()})(function(){return function t(r,i,s){function o(l,u){if(!i[l]){if(!r[l]){var h=typeof s_=="function"&&s_;if(!u&&h)return h(l,!0);if(a)return a(l,!0);var d=new Error("Cannot find module '"+l+"'");throw d.code="MODULE_NOT_FOUND",d}var m=i[l]={exports:{}};r[l][0].call(m.exports,function(g){var v=r[l][1][g];return o(v||g)},m,m.exports,t,r,i,s)}return i[l].exports}for(var a=typeof s_=="function"&&s_,c=0;c>2,m=(3&l)<<4|u>>4,g=1>6:64,v=2>4,u=(15&d)<<4|(m=a.indexOf(c.charAt(v++)))>>2,h=(3&m)<<6|(g=a.indexOf(c.charAt(v++))),S[y++]=l,m!==64&&(S[y++]=u),g!==64&&(S[y++]=h);return S}},{"./support":30,"./utils":32}],2:[function(t,r,i){var s=t("./external"),o=t("./stream/DataWorker"),a=t("./stream/Crc32Probe"),c=t("./stream/DataLengthProbe");function l(u,h,d,m,g){this.compressedSize=u,this.uncompressedSize=h,this.crc32=d,this.compression=m,this.compressedContent=g}l.prototype={getContentWorker:function(){var u=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},l.createWorkerFrom=function(u,h,d){return u.pipe(new a).pipe(new c("uncompressedSize")).pipe(h.compressWorker(d)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=l},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,r,i){var s=t("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,r,i){var s=t("./utils"),o=function(){for(var a,c=[],l=0;l<256;l++){a=l;for(var u=0;u<8;u++)a=1&a?3988292384^a>>>1:a>>>1;c[l]=a}return c}();r.exports=function(a,c){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(l,u,h,d){var m=o,g=d+h;l^=-1;for(var v=d;v>>8^m[255&(l^u[v])];return-1^l}(0|c,a,a.length,0):function(l,u,h,d){var m=o,g=d+h;l^=-1;for(var v=d;v>>8^m[255&(l^u.charCodeAt(v))];return-1^l}(0|c,a,a.length,0):0}},{"./utils":32}],5:[function(t,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(t,r,i){var s=null;s=typeof Promise<"u"?Promise:t("lie"),r.exports={Promise:s}},{lie:37}],7:[function(t,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=t("pako"),a=t("./utils"),c=t("./stream/GenericWorker"),l=s?"uint8array":"array";function u(h,d){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=d,this.meta={}}i.magic="\b\0",a.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(l,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(d){h.push({data:d,meta:h.meta})}},i.compressWorker=function(h){return new u("Deflate",h)},i.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,r,i){function s(m,g){var v,y="";for(v=0;v>>=8;return y}function o(m,g,v,y,_,S){var E,T,k=m.file,R=m.compression,M=S!==l.utf8encode,O=a.transformTo("string",S(k.name)),C=a.transformTo("string",l.utf8encode(k.name)),I=k.comment,U=a.transformTo("string",S(I)),L=a.transformTo("string",l.utf8encode(I)),P=C.length!==k.name.length,w=L.length!==I.length,H="",V="",B="",z=k.dir,W=k.date,K={crc32:0,compressedSize:0,uncompressedSize:0};g&&!v||(K.crc32=m.crc32,K.compressedSize=m.compressedSize,K.uncompressedSize=m.uncompressedSize);var j=0;g&&(j|=8),M||!P&&!w||(j|=2048);var Y=0,ge=0;z&&(Y|=16),_==="UNIX"?(ge=798,Y|=function(re,be){var Ae=re;return re||(Ae=be?16893:33204),(65535&Ae)<<16}(k.unixPermissions,z)):(ge=20,Y|=function(re){return 63&(re||0)}(k.dosPermissions)),E=W.getUTCHours(),E<<=6,E|=W.getUTCMinutes(),E<<=5,E|=W.getUTCSeconds()/2,T=W.getUTCFullYear()-1980,T<<=4,T|=W.getUTCMonth()+1,T<<=5,T|=W.getUTCDate(),P&&(V=s(1,1)+s(u(O),4)+C,H+="up"+s(V.length,2)+V),w&&(B=s(1,1)+s(u(U),4)+L,H+="uc"+s(B.length,2)+B);var Q="";return Q+=` +\0`,Q+=s(j,2),Q+=R.magic,Q+=s(E,2),Q+=s(T,2),Q+=s(K.crc32,4),Q+=s(K.compressedSize,4),Q+=s(K.uncompressedSize,4),Q+=s(O.length,2),Q+=s(H.length,2),{fileRecord:h.LOCAL_FILE_HEADER+Q+O+H,dirRecord:h.CENTRAL_FILE_HEADER+s(ge,2)+Q+s(U.length,2)+"\0\0\0\0"+s(Y,4)+s(y,4)+O+H+U}}var a=t("../utils"),c=t("../stream/GenericWorker"),l=t("../utf8"),u=t("../crc32"),h=t("../signature");function d(m,g,v,y){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=v,this.encodeFileName=y,this.streamFiles=m,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(d,c),d.prototype.push=function(m){var g=m.meta.percent||0,v=this.entriesCount,y=this._sources.length;this.accumulate?this.contentBuffer.push(m):(this.bytesWritten+=m.data.length,c.prototype.push.call(this,{data:m.data,meta:{currentFile:this.currentFile,percent:v?(g+100*(v-y-1))/v:100}}))},d.prototype.openedSource=function(m){this.currentSourceOffset=this.bytesWritten,this.currentFile=m.file.name;var g=this.streamFiles&&!m.file.dir;if(g){var v=o(m,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:v.fileRecord,meta:{percent:0}})}else this.accumulate=!0},d.prototype.closedSource=function(m){this.accumulate=!1;var g=this.streamFiles&&!m.file.dir,v=o(m,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(v.dirRecord),g)this.push({data:function(y){return h.DATA_DESCRIPTOR+s(y.crc32,4)+s(y.compressedSize,4)+s(y.uncompressedSize,4)}(m),meta:{percent:100}});else for(this.push({data:v.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},d.prototype.flush=function(){for(var m=this.bytesWritten,g=0;g=this.index;c--)l=(l<<8)+this.byteAt(c);return this.index+=a,l},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},r.exports=o},{"../utils":32}],19:[function(t,r,i){var s=t("./Uint8ArrayReader");function o(a){s.call(this,a)}t("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(t,r,i){var s=t("./DataReader");function o(a){s.call(this,a)}t("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(t,r,i){var s=t("./ArrayReader");function o(a){s.call(this,a)}t("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(t,r,i){var s=t("../utils"),o=t("../support"),a=t("./ArrayReader"),c=t("./StringReader"),l=t("./NodeBufferReader"),u=t("./Uint8ArrayReader");r.exports=function(h){var d=s.getTypeOf(h);return s.checkSupport(d),d!=="string"||o.uint8array?d==="nodebuffer"?new l(h):o.uint8array?new u(s.transformTo("uint8array",h)):new a(s.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(t,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(t,r,i){var s=t("./GenericWorker"),o=t("../utils");function a(c){s.call(this,"ConvertWorker to "+c),this.destType=c}o.inherits(a,s),a.prototype.processChunk=function(c){this.push({data:o.transformTo(this.destType,c.data),meta:c.meta})},r.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(t,r,i){var s=t("./GenericWorker"),o=t("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}t("../utils").inherits(a,s),a.prototype.processChunk=function(c){this.streamInfo.crc32=o(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(t,r,i){var s=t("../utils"),o=t("./GenericWorker");function a(c){o.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}s.inherits(a,o),a.prototype.processChunk=function(c){if(c){var l=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=l+c.data.length}o.prototype.processChunk.call(this,c)},r.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(t,r,i){var s=t("../utils"),o=t("./GenericWorker");function a(c){o.call(this,"DataWorker");var l=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){l.dataIsReady=!0,l.data=u,l.max=u&&u.length||0,l.type=s.getTypeOf(u),l.isPaused||l._tickAndRepeat()},function(u){l.error(u)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,l=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,l);break;case"uint8array":c=this.data.subarray(this.index,l);break;case"array":case"nodebuffer":c=this.data.slice(this.index,l)}return this.index=l,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(t,r,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var c=0;c "+o:o}},r.exports=s},{}],29:[function(t,r,i){var s=t("../utils"),o=t("./ConvertWorker"),a=t("./GenericWorker"),c=t("../base64"),l=t("../support"),u=t("../external"),h=null;if(l.nodestream)try{h=t("../nodejs/NodejsStreamOutputAdapter")}catch{}function d(g,v){return new u.Promise(function(y,_){var S=[],E=g._internalType,T=g._outputType,k=g._mimeType;g.on("data",function(R,M){S.push(R),v&&v(M)}).on("error",function(R){S=[],_(R)}).on("end",function(){try{var R=function(M,O,C){switch(M){case"blob":return s.newBlob(s.transformTo("arraybuffer",O),C);case"base64":return c.encode(O);default:return s.transformTo(M,O)}}(T,function(M,O){var C,I=0,U=null,L=0;for(C=0;C"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!t("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(t,r,i){for(var s=t("./utils"),o=t("./support"),a=t("./nodejsUtils"),c=t("./stream/GenericWorker"),l=new Array(256),u=0;u<256;u++)l[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;l[254]=l[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function d(){c.call(this,"utf-8 encode")}i.utf8encode=function(m){return o.nodebuffer?a.newBufferFrom(m,"utf-8"):function(g){var v,y,_,S,E,T=g.length,k=0;for(S=0;S>>6:(y<65536?v[E++]=224|y>>>12:(v[E++]=240|y>>>18,v[E++]=128|y>>>12&63),v[E++]=128|y>>>6&63),v[E++]=128|63&y);return v}(m)},i.utf8decode=function(m){return o.nodebuffer?s.transformTo("nodebuffer",m).toString("utf-8"):function(g){var v,y,_,S,E=g.length,T=new Array(2*E);for(v=y=0;v>10&1023,T[y++]=56320|1023&_)}return T.length!==y&&(T.subarray?T=T.subarray(0,y):T.length=y),s.applyFromCharCode(T)}(m=s.transformTo(o.uint8array?"uint8array":"array",m))},s.inherits(h,c),h.prototype.processChunk=function(m){var g=s.transformTo(o.uint8array?"uint8array":"array",m.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var v=g;(g=new Uint8Array(v.length+this.leftOver.length)).set(this.leftOver,0),g.set(v,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var y=function(S,E){var T;for((E=E||S.length)>S.length&&(E=S.length),T=E-1;0<=T&&(192&S[T])==128;)T--;return T<0||T===0?E:T+l[S[T]]>E?T:E}(g),_=g;y!==g.length&&(o.uint8array?(_=g.subarray(0,y),this.leftOver=g.subarray(y,g.length)):(_=g.slice(0,y),this.leftOver=g.slice(y,g.length))),this.push({data:i.utf8decode(_),meta:m.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=h,s.inherits(d,c),d.prototype.processChunk=function(m){this.push({data:i.utf8encode(m.data),meta:m.meta})},i.Utf8EncodeWorker=d},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,r,i){var s=t("./support"),o=t("./base64"),a=t("./nodejsUtils"),c=t("./external");function l(v){return v}function u(v,y){for(var _=0;_>8;this.dir=!!(16&this.externalFileAttributes),m==0&&(this.dosPermissions=63&this.externalFileAttributes),m==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var m=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=m.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=m.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=m.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=m.readInt(4))}},readExtraFields:function(m){var g,v,y,_=m.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});m.index+4<_;)g=m.readInt(2),v=m.readInt(2),y=m.readData(v),this.extraFields[g]={id:g,length:v,value:y};m.setIndex(_)},handleUTF8:function(){var m=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=l.utf8decode(this.fileName),this.fileCommentStr=l.utf8decode(this.fileComment);else{var g=this.findExtraFieldUnicodePath();if(g!==null)this.fileNameStr=g;else{var v=o.transformTo(m,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(v)}var y=this.findExtraFieldUnicodeComment();if(y!==null)this.fileCommentStr=y;else{var _=o.transformTo(m,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(_)}}},findExtraFieldUnicodePath:function(){var m=this.extraFields[28789];if(m){var g=s(m.value);return g.readInt(1)!==1||c(this.fileName)!==g.readInt(4)?null:l.utf8decode(g.readData(m.length-5))}return null},findExtraFieldUnicodeComment:function(){var m=this.extraFields[25461];if(m){var g=s(m.value);return g.readInt(1)!==1||c(this.fileComment)!==g.readInt(4)?null:l.utf8decode(g.readData(m.length-5))}return null}},r.exports=d},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(t,r,i){function s(g,v,y){this.name=g,this.dir=y.dir,this.date=y.date,this.comment=y.comment,this.unixPermissions=y.unixPermissions,this.dosPermissions=y.dosPermissions,this._data=v,this._dataBinary=y.binary,this.options={compression:y.compression,compressionOptions:y.compressionOptions}}var o=t("./stream/StreamHelper"),a=t("./stream/DataWorker"),c=t("./utf8"),l=t("./compressedObject"),u=t("./stream/GenericWorker");s.prototype={internalStream:function(g){var v=null,y="string";try{if(!g)throw new Error("No output type specified.");var _=(y=g.toLowerCase())==="string"||y==="text";y!=="binarystring"&&y!=="text"||(y="string"),v=this._decompressWorker();var S=!this._dataBinary;S&&!_&&(v=v.pipe(new c.Utf8EncodeWorker)),!S&&_&&(v=v.pipe(new c.Utf8DecodeWorker))}catch(E){(v=new u("error")).error(E)}return new o(v,y,"")},async:function(g,v){return this.internalStream(g).accumulate(v)},nodeStream:function(g,v){return this.internalStream(g||"nodebuffer").toNodejsStream(v)},_compressWorker:function(g,v){if(this._data instanceof l&&this._data.compression.magic===g.magic)return this._data.getCompressedWorker();var y=this._decompressWorker();return this._dataBinary||(y=y.pipe(new c.Utf8EncodeWorker)),l.createWorkerFrom(y,g,v)},_decompressWorker:function(){return this._data instanceof l?this._data.getContentWorker():this._data instanceof u?this._data:new a(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],d=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},m=0;m>>6:(m<65536?d[y++]=224|m>>>12:(d[y++]=240|m>>>18,d[y++]=128|m>>>12&63),d[y++]=128|m>>>6&63),d[y++]=128|63&m);return d},i.buf2binstring=function(h){return u(h,h.length)},i.binstring2buf=function(h){for(var d=new s.Buf8(h.length),m=0,g=d.length;m>10&1023,S[g++]=56320|1023&v)}return u(S,g)},i.utf8border=function(h,d){var m;for((d=d||h.length)>h.length&&(d=h.length),m=d-1;0<=m&&(192&h[m])==128;)m--;return m<0||m===0?d:m+c[h[m]]>d?m:d}},{"./common":41}],43:[function(t,r,i){r.exports=function(s,o,a,c){for(var l=65535&s|0,u=s>>>16&65535|0,h=0;a!==0;){for(a-=h=2e3>>1:o>>>1;a[c]=o}return a}();r.exports=function(o,a,c,l){var u=s,h=l+c;o^=-1;for(var d=l;d>>8^u[255&(o^a[d])];return-1^o}},{}],46:[function(t,r,i){var s,o=t("../utils/common"),a=t("./trees"),c=t("./adler32"),l=t("./crc32"),u=t("./messages"),h=0,d=4,m=0,g=-2,v=-1,y=4,_=2,S=8,E=9,T=286,k=30,R=19,M=2*T+1,O=15,C=3,I=258,U=I+C+1,L=42,P=113,w=1,H=2,V=3,B=4;function z(A,ie){return A.msg=u[ie],ie}function W(A){return(A<<1)-(4A.avail_out&&(te=A.avail_out),te!==0&&(o.arraySet(A.output,ie.pending_buf,ie.pending_out,te,A.next_out),A.next_out+=te,ie.pending_out+=te,A.total_out+=te,A.avail_out-=te,ie.pending-=te,ie.pending===0&&(ie.pending_out=0))}function Y(A,ie){a._tr_flush_block(A,0<=A.block_start?A.block_start:-1,A.strstart-A.block_start,ie),A.block_start=A.strstart,j(A.strm)}function ge(A,ie){A.pending_buf[A.pending++]=ie}function Q(A,ie){A.pending_buf[A.pending++]=ie>>>8&255,A.pending_buf[A.pending++]=255&ie}function re(A,ie){var te,X,$=A.max_chain_length,ne=A.strstart,ae=A.prev_length,G=A.nice_match,D=A.strstart>A.w_size-U?A.strstart-(A.w_size-U):0,ee=A.window,he=A.w_mask,ce=A.prev,_e=A.strstart+I,ze=ee[ne+ae-1],Oe=ee[ne+ae];A.prev_length>=A.good_match&&($>>=2),G>A.lookahead&&(G=A.lookahead);do if(ee[(te=ie)+ae]===Oe&&ee[te+ae-1]===ze&&ee[te]===ee[ne]&&ee[++te]===ee[ne+1]){ne+=2,te++;do;while(ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ne<_e);if(X=I-(_e-ne),ne=_e-I,aeD&&--$!=0);return ae<=A.lookahead?ae:A.lookahead}function be(A){var ie,te,X,$,ne,ae,G,D,ee,he,ce=A.w_size;do{if($=A.window_size-A.lookahead-A.strstart,A.strstart>=ce+(ce-U)){for(o.arraySet(A.window,A.window,ce,ce,0),A.match_start-=ce,A.strstart-=ce,A.block_start-=ce,ie=te=A.hash_size;X=A.head[--ie],A.head[ie]=ce<=X?X-ce:0,--te;);for(ie=te=ce;X=A.prev[--ie],A.prev[ie]=ce<=X?X-ce:0,--te;);$+=ce}if(A.strm.avail_in===0)break;if(ae=A.strm,G=A.window,D=A.strstart+A.lookahead,ee=$,he=void 0,he=ae.avail_in,ee=C)for(ne=A.strstart-A.insert,A.ins_h=A.window[ne],A.ins_h=(A.ins_h<=C&&(A.ins_h=(A.ins_h<=C)if(X=a._tr_tally(A,A.strstart-A.match_start,A.match_length-C),A.lookahead-=A.match_length,A.match_length<=A.max_lazy_match&&A.lookahead>=C){for(A.match_length--;A.strstart++,A.ins_h=(A.ins_h<=C&&(A.ins_h=(A.ins_h<=C&&A.match_length<=A.prev_length){for($=A.strstart+A.lookahead-C,X=a._tr_tally(A,A.strstart-1-A.prev_match,A.prev_length-C),A.lookahead-=A.prev_length-1,A.prev_length-=2;++A.strstart<=$&&(A.ins_h=(A.ins_h<A.pending_buf_size-5&&(te=A.pending_buf_size-5);;){if(A.lookahead<=1){if(be(A),A.lookahead===0&&ie===h)return w;if(A.lookahead===0)break}A.strstart+=A.lookahead,A.lookahead=0;var X=A.block_start+te;if((A.strstart===0||A.strstart>=X)&&(A.lookahead=A.strstart-X,A.strstart=X,Y(A,!1),A.strm.avail_out===0)||A.strstart-A.block_start>=A.w_size-U&&(Y(A,!1),A.strm.avail_out===0))return w}return A.insert=0,ie===d?(Y(A,!0),A.strm.avail_out===0?V:B):(A.strstart>A.block_start&&(Y(A,!1),A.strm.avail_out),w)}),new Le(4,4,8,4,Ae),new Le(4,5,16,8,Ae),new Le(4,6,32,32,Ae),new Le(4,4,16,16,Ee),new Le(8,16,32,32,Ee),new Le(8,16,128,128,Ee),new Le(8,32,128,256,Ee),new Le(32,128,258,1024,Ee),new Le(32,258,258,4096,Ee)],i.deflateInit=function(A,ie){return De(A,ie,S,15,8,0)},i.deflateInit2=De,i.deflateReset=it,i.deflateResetKeep=qe,i.deflateSetHeader=function(A,ie){return A&&A.state?A.state.wrap!==2?g:(A.state.gzhead=ie,m):g},i.deflate=function(A,ie){var te,X,$,ne;if(!A||!A.state||5>8&255),ge(X,X.gzhead.time>>16&255),ge(X,X.gzhead.time>>24&255),ge(X,X.level===9?2:2<=X.strategy||X.level<2?4:0),ge(X,255&X.gzhead.os),X.gzhead.extra&&X.gzhead.extra.length&&(ge(X,255&X.gzhead.extra.length),ge(X,X.gzhead.extra.length>>8&255)),X.gzhead.hcrc&&(A.adler=l(A.adler,X.pending_buf,X.pending,0)),X.gzindex=0,X.status=69):(ge(X,0),ge(X,0),ge(X,0),ge(X,0),ge(X,0),ge(X,X.level===9?2:2<=X.strategy||X.level<2?4:0),ge(X,3),X.status=P);else{var ae=S+(X.w_bits-8<<4)<<8;ae|=(2<=X.strategy||X.level<2?0:X.level<6?1:X.level===6?2:3)<<6,X.strstart!==0&&(ae|=32),ae+=31-ae%31,X.status=P,Q(X,ae),X.strstart!==0&&(Q(X,A.adler>>>16),Q(X,65535&A.adler)),A.adler=1}if(X.status===69)if(X.gzhead.extra){for($=X.pending;X.gzindex<(65535&X.gzhead.extra.length)&&(X.pending!==X.pending_buf_size||(X.gzhead.hcrc&&X.pending>$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),j(A),$=X.pending,X.pending!==X.pending_buf_size));)ge(X,255&X.gzhead.extra[X.gzindex]),X.gzindex++;X.gzhead.hcrc&&X.pending>$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),X.gzindex===X.gzhead.extra.length&&(X.gzindex=0,X.status=73)}else X.status=73;if(X.status===73)if(X.gzhead.name){$=X.pending;do{if(X.pending===X.pending_buf_size&&(X.gzhead.hcrc&&X.pending>$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),j(A),$=X.pending,X.pending===X.pending_buf_size)){ne=1;break}ne=X.gzindex$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),ne===0&&(X.gzindex=0,X.status=91)}else X.status=91;if(X.status===91)if(X.gzhead.comment){$=X.pending;do{if(X.pending===X.pending_buf_size&&(X.gzhead.hcrc&&X.pending>$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),j(A),$=X.pending,X.pending===X.pending_buf_size)){ne=1;break}ne=X.gzindex$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),ne===0&&(X.status=103)}else X.status=103;if(X.status===103&&(X.gzhead.hcrc?(X.pending+2>X.pending_buf_size&&j(A),X.pending+2<=X.pending_buf_size&&(ge(X,255&A.adler),ge(X,A.adler>>8&255),A.adler=0,X.status=P)):X.status=P),X.pending!==0){if(j(A),A.avail_out===0)return X.last_flush=-1,m}else if(A.avail_in===0&&W(ie)<=W(te)&&ie!==d)return z(A,-5);if(X.status===666&&A.avail_in!==0)return z(A,-5);if(A.avail_in!==0||X.lookahead!==0||ie!==h&&X.status!==666){var G=X.strategy===2?function(D,ee){for(var he;;){if(D.lookahead===0&&(be(D),D.lookahead===0)){if(ee===h)return w;break}if(D.match_length=0,he=a._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++,he&&(Y(D,!1),D.strm.avail_out===0))return w}return D.insert=0,ee===d?(Y(D,!0),D.strm.avail_out===0?V:B):D.last_lit&&(Y(D,!1),D.strm.avail_out===0)?w:H}(X,ie):X.strategy===3?function(D,ee){for(var he,ce,_e,ze,Oe=D.window;;){if(D.lookahead<=I){if(be(D),D.lookahead<=I&&ee===h)return w;if(D.lookahead===0)break}if(D.match_length=0,D.lookahead>=C&&0D.lookahead&&(D.match_length=D.lookahead)}if(D.match_length>=C?(he=a._tr_tally(D,1,D.match_length-C),D.lookahead-=D.match_length,D.strstart+=D.match_length,D.match_length=0):(he=a._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++),he&&(Y(D,!1),D.strm.avail_out===0))return w}return D.insert=0,ee===d?(Y(D,!0),D.strm.avail_out===0?V:B):D.last_lit&&(Y(D,!1),D.strm.avail_out===0)?w:H}(X,ie):s[X.level].func(X,ie);if(G!==V&&G!==B||(X.status=666),G===w||G===V)return A.avail_out===0&&(X.last_flush=-1),m;if(G===H&&(ie===1?a._tr_align(X):ie!==5&&(a._tr_stored_block(X,0,0,!1),ie===3&&(K(X.head),X.lookahead===0&&(X.strstart=0,X.block_start=0,X.insert=0))),j(A),A.avail_out===0))return X.last_flush=-1,m}return ie!==d?m:X.wrap<=0?1:(X.wrap===2?(ge(X,255&A.adler),ge(X,A.adler>>8&255),ge(X,A.adler>>16&255),ge(X,A.adler>>24&255),ge(X,255&A.total_in),ge(X,A.total_in>>8&255),ge(X,A.total_in>>16&255),ge(X,A.total_in>>24&255)):(Q(X,A.adler>>>16),Q(X,65535&A.adler)),j(A),0=te.w_size&&(ne===0&&(K(te.head),te.strstart=0,te.block_start=0,te.insert=0),ee=new o.Buf8(te.w_size),o.arraySet(ee,ie,he-te.w_size,te.w_size,0),ie=ee,he=te.w_size),ae=A.avail_in,G=A.next_in,D=A.input,A.avail_in=he,A.next_in=0,A.input=ie,be(te);te.lookahead>=C;){for(X=te.strstart,$=te.lookahead-(C-1);te.ins_h=(te.ins_h<>>=C=O>>>24,E-=C,(C=O>>>16&255)===0)H[u++]=65535&O;else{if(!(16&C)){if(!(64&C)){O=T[(65535&O)+(S&(1<>>=C,E-=C),E<15&&(S+=w[c++]<>>=C=O>>>24,E-=C,!(16&(C=O>>>16&255))){if(!(64&C)){O=k[(65535&O)+(S&(1<>>=C,E-=C,(C=u-h)>3,S&=(1<<(E-=I<<3))-1,s.next_in=c,s.next_out=u,s.avail_in=c>>24&255)+(L>>>8&65280)+((65280&L)<<8)+((255&L)<<24)}function S(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function E(L){var P;return L&&L.state?(P=L.state,L.total_in=L.total_out=P.total=0,L.msg="",P.wrap&&(L.adler=1&P.wrap),P.mode=g,P.last=0,P.havedict=0,P.dmax=32768,P.head=null,P.hold=0,P.bits=0,P.lencode=P.lendyn=new s.Buf32(v),P.distcode=P.distdyn=new s.Buf32(y),P.sane=1,P.back=-1,d):m}function T(L){var P;return L&&L.state?((P=L.state).wsize=0,P.whave=0,P.wnext=0,E(L)):m}function k(L,P){var w,H;return L&&L.state?(H=L.state,P<0?(w=0,P=-P):(w=1+(P>>4),P<48&&(P&=15)),P&&(P<8||15=B.wsize?(s.arraySet(B.window,P,w-B.wsize,B.wsize,0),B.wnext=0,B.whave=B.wsize):(H<(V=B.wsize-B.wnext)&&(V=H),s.arraySet(B.window,P,w-H,V,B.wnext),(H-=V)?(s.arraySet(B.window,P,w-H,H,0),B.wnext=H,B.whave=B.wsize):(B.wnext+=V,B.wnext===B.wsize&&(B.wnext=0),B.whave>>8&255,w.check=a(w.check,ne,2,0),Y=j=0,w.mode=2;break}if(w.flags=0,w.head&&(w.head.done=!1),!(1&w.wrap)||(((255&j)<<8)+(j>>8))%31){L.msg="incorrect header check",w.mode=30;break}if((15&j)!=8){L.msg="unknown compression method",w.mode=30;break}if(Y-=4,A=8+(15&(j>>>=4)),w.wbits===0)w.wbits=A;else if(A>w.wbits){L.msg="invalid window size",w.mode=30;break}w.dmax=1<>8&1),512&w.flags&&(ne[0]=255&j,ne[1]=j>>>8&255,w.check=a(w.check,ne,2,0)),Y=j=0,w.mode=3;case 3:for(;Y<32;){if(W===0)break e;W--,j+=H[B++]<>>8&255,ne[2]=j>>>16&255,ne[3]=j>>>24&255,w.check=a(w.check,ne,4,0)),Y=j=0,w.mode=4;case 4:for(;Y<16;){if(W===0)break e;W--,j+=H[B++]<>8),512&w.flags&&(ne[0]=255&j,ne[1]=j>>>8&255,w.check=a(w.check,ne,2,0)),Y=j=0,w.mode=5;case 5:if(1024&w.flags){for(;Y<16;){if(W===0)break e;W--,j+=H[B++]<>>8&255,w.check=a(w.check,ne,2,0)),Y=j=0}else w.head&&(w.head.extra=null);w.mode=6;case 6:if(1024&w.flags&&(W<(re=w.length)&&(re=W),re&&(w.head&&(A=w.head.extra_len-w.length,w.head.extra||(w.head.extra=new Array(w.head.extra_len)),s.arraySet(w.head.extra,H,B,re,A)),512&w.flags&&(w.check=a(w.check,H,re,B)),W-=re,B+=re,w.length-=re),w.length))break e;w.length=0,w.mode=7;case 7:if(2048&w.flags){if(W===0)break e;for(re=0;A=H[B+re++],w.head&&A&&w.length<65536&&(w.head.name+=String.fromCharCode(A)),A&&re>9&1,w.head.done=!0),L.adler=w.check=0,w.mode=12;break;case 10:for(;Y<32;){if(W===0)break e;W--,j+=H[B++]<>>=7&Y,Y-=7&Y,w.mode=27;break}for(;Y<3;){if(W===0)break e;W--,j+=H[B++]<>>=1)){case 0:w.mode=14;break;case 1:if(I(w),w.mode=20,P!==6)break;j>>>=2,Y-=2;break e;case 2:w.mode=17;break;case 3:L.msg="invalid block type",w.mode=30}j>>>=2,Y-=2;break;case 14:for(j>>>=7&Y,Y-=7&Y;Y<32;){if(W===0)break e;W--,j+=H[B++]<>>16^65535)){L.msg="invalid stored block lengths",w.mode=30;break}if(w.length=65535&j,Y=j=0,w.mode=15,P===6)break e;case 15:w.mode=16;case 16:if(re=w.length){if(W>>=5,Y-=5,w.ndist=1+(31&j),j>>>=5,Y-=5,w.ncode=4+(15&j),j>>>=4,Y-=4,286>>=3,Y-=3}for(;w.have<19;)w.lens[ae[w.have++]]=0;if(w.lencode=w.lendyn,w.lenbits=7,te={bits:w.lenbits},ie=l(0,w.lens,0,19,w.lencode,0,w.work,te),w.lenbits=te.bits,ie){L.msg="invalid code lengths set",w.mode=30;break}w.have=0,w.mode=19;case 19:for(;w.have>>16&255,He=65535&$,!((Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>>=Ee,Y-=Ee,w.lens[w.have++]=He;else{if(He===16){for(X=Ee+2;Y>>=Ee,Y-=Ee,w.have===0){L.msg="invalid bit length repeat",w.mode=30;break}A=w.lens[w.have-1],re=3+(3&j),j>>>=2,Y-=2}else if(He===17){for(X=Ee+3;Y>>=Ee)),j>>>=3,Y-=3}else{for(X=Ee+7;Y>>=Ee)),j>>>=7,Y-=7}if(w.have+re>w.nlen+w.ndist){L.msg="invalid bit length repeat",w.mode=30;break}for(;re--;)w.lens[w.have++]=A}}if(w.mode===30)break;if(w.lens[256]===0){L.msg="invalid code -- missing end-of-block",w.mode=30;break}if(w.lenbits=9,te={bits:w.lenbits},ie=l(u,w.lens,0,w.nlen,w.lencode,0,w.work,te),w.lenbits=te.bits,ie){L.msg="invalid literal/lengths set",w.mode=30;break}if(w.distbits=6,w.distcode=w.distdyn,te={bits:w.distbits},ie=l(h,w.lens,w.nlen,w.ndist,w.distcode,0,w.work,te),w.distbits=te.bits,ie){L.msg="invalid distances set",w.mode=30;break}if(w.mode=20,P===6)break e;case 20:w.mode=21;case 21:if(6<=W&&258<=K){L.next_out=z,L.avail_out=K,L.next_in=B,L.avail_in=W,w.hold=j,w.bits=Y,c(L,Q),z=L.next_out,V=L.output,K=L.avail_out,B=L.next_in,H=L.input,W=L.avail_in,j=w.hold,Y=w.bits,w.mode===12&&(w.back=-1);break}for(w.back=0;Le=($=w.lencode[j&(1<>>16&255,He=65535&$,!((Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>qe)])>>>16&255,He=65535&$,!(qe+(Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>>=qe,Y-=qe,w.back+=qe}if(j>>>=Ee,Y-=Ee,w.back+=Ee,w.length=He,Le===0){w.mode=26;break}if(32&Le){w.back=-1,w.mode=12;break}if(64&Le){L.msg="invalid literal/length code",w.mode=30;break}w.extra=15&Le,w.mode=22;case 22:if(w.extra){for(X=w.extra;Y>>=w.extra,Y-=w.extra,w.back+=w.extra}w.was=w.length,w.mode=23;case 23:for(;Le=($=w.distcode[j&(1<>>16&255,He=65535&$,!((Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>qe)])>>>16&255,He=65535&$,!(qe+(Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>>=qe,Y-=qe,w.back+=qe}if(j>>>=Ee,Y-=Ee,w.back+=Ee,64&Le){L.msg="invalid distance code",w.mode=30;break}w.offset=He,w.extra=15&Le,w.mode=24;case 24:if(w.extra){for(X=w.extra;Y>>=w.extra,Y-=w.extra,w.back+=w.extra}if(w.offset>w.dmax){L.msg="invalid distance too far back",w.mode=30;break}w.mode=25;case 25:if(K===0)break e;if(re=Q-K,w.offset>re){if((re=w.offset-re)>w.whave&&w.sane){L.msg="invalid distance too far back",w.mode=30;break}be=re>w.wnext?(re-=w.wnext,w.wsize-re):w.wnext-re,re>w.length&&(re=w.length),Ae=w.window}else Ae=V,be=z-w.offset,re=w.length;for(KM?(C=be[Ae+y[P]],Y[ge+y[P]]):(C=96,0),S=1<>z)+(E-=S)]=O<<24|C<<16|I|0,E!==0;);for(S=1<>=1;if(S!==0?(j&=S-1,j+=S):j=0,P++,--Q[L]==0){if(L===H)break;L=h[d+y[P]]}if(V>>7)]}function ge($,ne){$.pending_buf[$.pending++]=255&ne,$.pending_buf[$.pending++]=ne>>>8&255}function Q($,ne,ae){$.bi_valid>_-ae?($.bi_buf|=ne<<$.bi_valid&65535,ge($,$.bi_buf),$.bi_buf=ne>>_-$.bi_valid,$.bi_valid+=ae-_):($.bi_buf|=ne<<$.bi_valid&65535,$.bi_valid+=ae)}function re($,ne,ae){Q($,ae[2*ne],ae[2*ne+1])}function be($,ne){for(var ae=0;ae|=1&$,$>>>=1,ae<<=1,0<--ne;);return ae>>>1}function Ae($,ne,ae){var G,D,ee=new Array(y+1),he=0;for(G=1;G<=y;G++)ee[G]=he=he+ae[G-1]<<1;for(D=0;D<=ne;D++){var ce=$[2*D+1];ce!==0&&($[2*D]=be(ee[ce]++,ce))}}function Ee($){var ne;for(ne=0;ne>1;1<=ae;ae--)qe($,ee,ae);for(D=_e;ae=$.heap[1],$.heap[1]=$.heap[$.heap_len--],qe($,ee,1),G=$.heap[1],$.heap[--$.heap_max]=ae,$.heap[--$.heap_max]=G,ee[2*D]=ee[2*ae]+ee[2*G],$.depth[D]=($.depth[ae]>=$.depth[G]?$.depth[ae]:$.depth[G])+1,ee[2*ae+1]=ee[2*G+1]=D,$.heap[1]=D++,qe($,ee,1),2<=$.heap_len;);$.heap[--$.heap_max]=$.heap[1],function(Oe,Ge){var Dt,Pe,nt,et,xt,rt,Rt=Ge.dyn_tree,kt=Ge.max_code,bn=Ge.stat_desc.static_tree,le=Ge.stat_desc.has_stree,je=Ge.stat_desc.extra_bits,Ce=Ge.stat_desc.extra_base,Ne=Ge.stat_desc.max_length,$e=0;for(et=0;et<=y;et++)Oe.bl_count[et]=0;for(Rt[2*Oe.heap[Oe.heap_max]+1]=0,Dt=Oe.heap_max+1;Dt>=7;D>>=1)if(1&ze&&ce.dyn_ltree[2*_e]!==0)return o;if(ce.dyn_ltree[18]!==0||ce.dyn_ltree[20]!==0||ce.dyn_ltree[26]!==0)return a;for(_e=32;_e>>3,(ee=$.static_len+3+7>>>3)<=D&&(D=ee)):D=ee=ae+5,ae+4<=D&&ne!==-1?X($,ne,ae,G):$.strategy===4||ee===D?(Q($,2+(G?1:0),3),it($,U,L)):(Q($,4+(G?1:0),3),function(ce,_e,ze,Oe){var Ge;for(Q(ce,_e-257,5),Q(ce,ze-1,5),Q(ce,Oe-4,4),Ge=0;Ge>>8&255,$.pending_buf[$.d_buf+2*$.last_lit+1]=255&ne,$.pending_buf[$.l_buf+$.last_lit]=255&ae,$.last_lit++,ne===0?$.dyn_ltree[2*ae]++:($.matches++,ne--,$.dyn_ltree[2*(w[ae]+h+1)]++,$.dyn_dtree[2*Y(ne)]++),$.last_lit===$.lit_bufsize-1},i._tr_align=function($){Q($,2,3),re($,E,U),function(ne){ne.bi_valid===16?(ge(ne,ne.bi_buf),ne.bi_buf=0,ne.bi_valid=0):8<=ne.bi_valid&&(ne.pending_buf[ne.pending++]=255&ne.bi_buf,ne.bi_buf>>=8,ne.bi_valid-=8)}($)}},{"../utils/common":41}],53:[function(t,r,i){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(t,r,i){(function(s){(function(o,a){if(!o.setImmediate){var c,l,u,h,d=1,m={},g=!1,v=o.document,y=Object.getPrototypeOf&&Object.getPrototypeOf(o);y=y&&y.setTimeout?y:o,c={}.toString.call(o.process)==="[object process]"?function(T){process.nextTick(function(){S(T)})}:function(){if(o.postMessage&&!o.importScripts){var T=!0,k=o.onmessage;return o.onmessage=function(){T=!1},o.postMessage("","*"),o.onmessage=k,T}}()?(h="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",E,!1):o.attachEvent("onmessage",E),function(T){o.postMessage(h+T,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(T){S(T.data)},function(T){u.port2.postMessage(T)}):v&&"onreadystatechange"in v.createElement("script")?(l=v.documentElement,function(T){var k=v.createElement("script");k.onreadystatechange=function(){S(T),k.onreadystatechange=null,l.removeChild(k),k=null},l.appendChild(k)}):function(T){setTimeout(S,0,T)},y.setImmediate=function(T){typeof T!="function"&&(T=new Function(""+T));for(var k=new Array(arguments.length-1),R=0;R"u"?s===void 0?this:s:self)}).call(this,typeof No<"u"?No:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(ame);const pB={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(pB);var eo=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},xf,bp,Ou;class cme{constructor(...e){xf.set(this,new Map),bp.set(this,new Map),Ou.set(this,new Map);for(const t of e)this.define(t)}define(e,t=!1){for(let[r,i]of Object.entries(e)){r=r.toLowerCase(),i=i.map(a=>a.toLowerCase()),eo(this,Ou,"f").has(r)||eo(this,Ou,"f").set(r,new Set);const s=eo(this,Ou,"f").get(r);let o=!0;for(let a of i){const c=a.startsWith("*");if(a=c?a.slice(1):a,s==null||s.add(a),o&&eo(this,bp,"f").set(r,a),o=!1,c)continue;const l=eo(this,xf,"f").get(a);if(l&&l!=r&&!t)throw new Error(`"${r} -> ${a}" conflicts with "${l} -> ${a}". Pass \`force=true\` to override this definition.`);eo(this,xf,"f").set(a,r)}}return this}getType(e){if(typeof e!="string")return null;const t=e.replace(/^.*[/\\]/,"").toLowerCase(),r=t.replace(/^.*\./,"").toLowerCase(),i=t.length{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(const e of eo(this,Ou,"f").values())Object.freeze(e);return this}_getTestState(){return{types:eo(this,xf,"f"),extensions:eo(this,bp,"f")}}}xf=new WeakMap,bp=new WeakMap,Ou=new WeakMap;new cme(pB)._freeze();function xT(n){if(!n||n.type===void 0)return;const e=[{start:n.startOffset,end:n.endOffset??0}];return Object.keys(n).forEach(t=>{if(t!=="parent"){const r=n[t];cn(r)?r.forEach(i=>{e.push(xT(i))}):e.push(xT(r))}}),n.range={start:Math.min(...e.filter(t=>t).map(t=>(t==null?void 0:t.start)??0)),end:Math.max(...e.filter(t=>t).map(t=>(t==null?void 0:t.end)??0))},n.range}function lme(n){const e=GF(`${n} +`);if(e.errors.length>0)return e;Cf.input=e.tokens;const t=Cf.program();if(Cf.errors.length>0)return{tokens:e.tokens,errors:Cf.errors.map(i=>({offset:i.token.startOffset,line:i.token.startLine,column:i.token.startColumn,length:i.token.image.length,message:i.message}))};const[r]=Zpe.go(t);return r?(xT(r),{tokens:e.tokens,cst:t,ast:r}):{tokens:e.tokens,cst:t,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]}}const X1=Object.getPrototypeOf(function*(){}).constructor;function ume(n,e){const t=`compile-${n}`;console.time(t);const r=lme(e);if(console.timeEnd(t),r.errors&&r.errors.length>0)return r;if(!r.ast)return{...r,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]};const i=nme(r.ast);if(i.code){ale&&console.info(i.code);try{return{...r,...i,source:i.code,code:new X1("api",i.code)}}catch(s){return{errors:[{message:`unexpected error ${s.message}`,offset:0,line:0,column:0,length:0}],source:"",code:new X1("api"," ")}}}return{...r,...i,source:"",code:new X1("api"," ")}}function hme(){const n={},e={};function t(i,s){const o=n[s];if(o)return o;const a=ume(i,s);return n[s]=a,a}const r={ids(){return Object.keys(e)},has(i){return Z(e[i])},isended(i){const s=e[i];return Z(s)?s.isended():!0},halt(i){const s=e[i];return Z(s)&&(s.halt(),delete e[i]),!!s},gc(){const i=r.ids();for(let s=0;s[_,S]);g.slice(m-5,m).forEach(([_,S])=>{An("os","build",`$grey${S+1} $grey${_}`)});const[v,y]=g[m]??[];if(Bt(v)&&Z(y)){const _=(d.column??1)-1,S=_+d.length,E=_{An("os","build",_)}),!1}}return!!(l!=null&&l.tick(o))},once(i,s,o,a){const c=r.tick(i,s,1,o,a);return r.halt(i)&&c},message(i){const{target:s,path:o}=WL(i.target),a=e[s];if(Z(a)){const c={...i,target:o};a.message(c)}}};return r}const mB=hme();var Ir=(n=>(n.MAIN="main",n.TITLE="title",n.PLAYER="player",n.CONTENT="content",n.GADGETSTORE="gadgetstore",n.GADGETSYNC="gadgetsync",n))(Ir||{});const Qo={defaultplayer:HL(),software:{main:"",content:""},books:new Map,chips:new Map,loaders:new Map,chipindex:new Map,codepageindex:new Map,binaryfiles:new Map};function ST(){return[...Qo.books.values()]}function fme(){const[n]=Qo.books.values();return n}function md(n){const e=Kt(n);return Qo.books.get(n)??ST().find(t=>t.name===e)}function ET(n,e){Z(md(e))&&(Qo.software[n]=e)}function Tp(n){return md(Qo.software[n])}function gB(n){const e=qF([]);return Bt(n)&&(e.name=n),_B(e),lo("memory",`created [book] ${e.name}`),e}function dme(n){let e=md(n);return Z(e)||(e=qF([]),e.name=n),_B(e),lo("memory",`created [book] ${e.name}`),e}function Bc(n,e){let t=Z(e)?dme(e):Tp(n);return Z(t)||(Z(t)||(t=fme()),Z(t)||(t=gB(e)),Z(t)&&lo("memory",`opened [book] ${t.name} for ${n}`)),ET(n,t.id),t}function Ru(n,e,t){const r=Bc(n);let i=eg(r,e);if(Z(i))return i;const s=jF(t);return i=Ode(s==="object"?`@${e} +`:`@${s} ${e} +`,{}),Pde(r,i),gme(i.id,r.id),YL("memory","",Qo.defaultplayer),i}function sm(n){const e=Bc("main");return Fde(e,n)}function pme(n){const e=Bc("main");return Bde(e,n)}function _B(n){return Qo.books.set(n.id,n),n.id}function mme(n){const e=md(n);e&&Qo.books.delete(e.id)}function gme(n,e){Qo.codepageindex.set(n,e)}function _me(n,e,t,r,i=s$){if(!Z(n)||!Z(e)||!Z(t))return;const s={...se},o=t.id??"";se.book=n,se.board=e,se.element=t,se.isplayer=GL(o),se.player=t.player??Qo.defaultplayer;const a=qc(n,t),c=t.cycle??(a==null?void 0:a.cycle)??i,l=t.id??"",u=cM(t);if(mB.tick(l,mM.CODE_PAGE,gt(c)?c:i,u,r),gt(t==null?void 0:t.tickertime)&&se.timestamp-t.tickertime>JL*5&&(t.tickertime=0,t.tickertext=""),se.isplayer){const h=sm(se.element.id??"");h.inputcurrent=0}DL(s).forEach(h=>{se[h]=s[h]})}function Hv(n){const e=Bc("main"),t=eg(e,n);if(!Z(e)||!Z(t)||!Z(se.element))return;const r=`${n}_run`,i=cM(se.element),s=(t==null?void 0:t.code)??"";mB.once(r,mM.CODE_PAGE,i,s)}function vB(n){return Qo.binaryfiles.get(n)}function Hi(n,e=!0){var r,i,s,o,a;const t=se.words[n];if(lF(t)){const[c,l]=B_(n);if(Z(c))return[c,l]}if(Tde(t)){const[c,l]=hF(n);if(Z(c))return[c,l]}if(xB(t)){const[c,l]=Gv(n);if(Z(c))return[c,l]}if(Bt(t)&&Kt(t)==="rnd"){const[c,l]=Hi(n+1),[u,h]=Hi(l);return gt(c)&>(u)?[gp(c,u),h]:gt(c)?[gp(0,c),l]:[gp(0,1),n+1]}if(V4(t)){const[c,l]=Zb(n);if(Z(c))return[c,l]}if(!Z(t))return[void 0,n];if(Ic(t)||gt(t)||cn(t))return[t,n+1];if(Bt(t)){const c=Kt(t);if(e){const l=(r=se.get)==null?void 0:r.call(se,t);if(Z(l))return[l,n+1]}switch(c){case"aligned":case"alligned":{const l=CI(se.board,se.element,se.player);return!Z(se.element)||!Z(l)?[0,n+1]:[se.element.x===l.x||se.element.y===l.y?1:0,n+1]}case"contact":{const l=CI(se.board,se.element,se.player);if(!Z(se.element)||!Z(l))return[0,n+1];const u=(l.x??0)-(((i=se.element)==null?void 0:i.x)??0),h=(l.y??0)-(((s=se.element)==null?void 0:s.y)??0);return[u===0&&Math.abs(h)<2||h===0&&Math.abs(u)<2?1:0,n+1]}case"blocked":{const[l,u]=Ve(se.words,n+1,[Ie.DIR]);return[zde(se.book,se.board,se.element,l)?1:0,u]}case"any":{const[l,u]=Ve(se.words,n+1,[Ie.KIND]),h=Fv(l)??"",d=Jm(se.board,h);return[j4(d,l).length?1:0,u]}case"rnd":return[gp(0,1),n+1];case"abs":{const[l,u]=Ve(se.words,n+1,[Ie.NUMBER]);return[Math.abs(l),u]}case"ceil":{const[l,u]=Ve(se.words,n+1,[Ie.NUMBER]);return[Math.ceil(l),u]}case"floor":{const[l,u]=Ve(se.words,n+1,[Ie.NUMBER]);return[Math.floor(l),u]}case"round":{const[l,u]=Ve(se.words,n+1,[Ie.NUMBER]);return[Math.round(l),u]}case"min":{const l=[];for(let u=n+1;uwn.WHITE&&nwn[e]).find(e=>Z(e)&&ewn[e]).find(e=>Z(e)&&e>=wn.ONBLACK)}function iO(n){if(fo(n))return n;if(yB(n))return[n];const e=xB(n);if(Z(e))return[e]}function sO(n){const e=se.words[n],t=iO(e);if(fo(t))return[t,n+1];const[r,i]=Hi(n),s=iO(r);return fo(s)?[s,i]:[void 0,n]}function Gv(n){const e=[];let t=n;const[r,i]=sO(n);if(fo(r)&&(e.push(...r),t=i),fo(e)&&!rO(e)){const[s,o]=sO(i);rO(s)&&(t=o)}return e.length?[e,t]:[void 0,n]}function Eme(n){const e={};return n.every(t=>{const r=wn[t];Z(r)&&(rString.fromCharCode(n)),Tme=Ws({name:"Whitespace",pattern:/ +/}),wme=Ws({name:"WhitespaceSkipped",pattern:/ +/,group:Wr.SKIPPED}),vM=Ws({name:"Newline",line_breaks:!0,start_chars_hint:[` +`,"\r"],pattern:/\n|\r\n?/}),yM=Ws({name:"StringLiteral",pattern:/[^ $;\r\n]+/,start_chars_hint:bme}),xM=Ws({name:"StringLiteralDouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),SM=Ws({name:"EscapedDollar",pattern:"$$"}),EM=Ws({name:"MaybeFlag",pattern:/\$[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/}),bM=Ws({name:"NumberLiteral",pattern:/\$-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?\+?/}),TM=Ws({name:"HyperLinkText",pattern:/;[^;\r\n]*/,start_chars_hint:[";"]});function Ame(n,e=""){return Ws({name:e||n,pattern:new RegExp(n.toLowerCase(),"i")})}const Mme=Object.keys(mx),SB=Mme.map(n=>Ame(`\\$(${n})`,n)),Cme=[Tme,vM,...SB,xM,yM,bM,SM,TM,EM],Rme=new Wr(Cme,{skipValidations:!ja,ensureOptimizations:ja}),kme=new Wr([wme,vM,...SB,xM,yM,bM,SM,TM,EM],{skipValidations:!ja,ensureOptimizations:ja});function gx(n,e=!1){return e?kme.tokenize(n):Rme.tokenize(n)}function ig(n,e,t,r,i,s,o,a){return{disablewrap:!1,measureonly:!1,measuredwidth:0,writefullwidth:void 0,x:0,y:0,iseven:!0,active:{color:t,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},reset:{color:t,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},width:n,height:e,char:[],color:[],bg:[],changed(){}}}function _x(n){n.active={...n.reset}}function wM(n,e){const t=e.y;function r(){++e.x;const a=e.active.rightedge??e.width-1;!e.disablewrap&&e.x>a&&(e.x=e.active.leftedge??0,++e.y),e.x>e.measuredwidth&&(e.measuredwidth=e.x)}function i(){return e.x>=(e.active.leftedge??0)&&e.x<=(e.active.rightedge??e.width-1)&&e.y>=(e.active.topedge??0)&&e.y<=(e.active.bottomedge??e.height-1)}function s(a){for(let c=0;ce.measuredwidth&&(e.measuredwidth=e.x+1);const o=e.active.leftedge??0;if(Z(e.writefullwidth)&&(e.x>o||e.y===t)){const c=(e.active.rightedge??e.width-1)-e.x;if(c>0){_x(e);const l=String.fromCharCode(e.writefullwidth).repeat(c),u=e.x+e.y*e.width;yx(u,u+l.length,e.active.color,e.active.bg,e),vx(u,l,e)}}}function Wn(n,e,t){const r=gx(n);r.tokens&&(wM(r.tokens,e),t&&_x(e))}function AM(n,e,t){const r=gx(n);if(!r.tokens)return;const i=ig(e,t,wn.WHITE,wn.BLACK);return i.measureonly=!0,wM(r.tokens,i),i.x>0&&++i.y,i}function vx(n,e,t){let r=0;const i=n+e.length;for(let s=n;s({blink:!1}));setInterval(()=>{bB.setState(n=>({blink:!n.blink}))},333);function rc(){return bB(n=>n.blink)}function TB(){return jA(n=>{function e(){n({render:Math.random()})}return{dither:[],render:0,changed(){setTimeout(e,0)}}})}function Nme(n){n.fill(0)}function K1(n,e,t,r,i,s){if(r<0||r>=e||i<0||i>=t)return-1;n[r+i*e]=s}const wB=ke.createContext(TB());function Ime(n,e,t){const[r]=ke.useState(()=>TB()),i=n*e,s=r.getState();return s.dither.length!==i&&(s.dither=new Array(i).fill(t),s.render=0),r}function AB(){return jA(n=>{function e(){n({render:Math.random()})}return{width:0,height:0,char:[],color:[],bg:[],render:0,changed(){setTimeout(e,0)}}})}function Ome(n,e,t,r){n.char.fill(e),n.color.fill(t),n.bg.fill(r)}function Br(n,e,t,r,i,s){if(r<0||r>=e||i<0||i>=t)return;const o=r+i*e;DL(s).forEach(a=>{const c=s[a];Z(c)&&(n[a][o]=c)})}const MM=ke.createContext(AB());function CM(n,e,t,r,i){const[s]=ke.useState(()=>AB()),o=n*e,a=s.getState();return a.char.length!==o&&(a.width=n,a.height=e,a.char=new Array(o).fill(t),a.color=new Array(o).fill(r),a.bg=new Array(o).fill(i),a.render=0),s}function Lme(){return ke.useContext(MM).getState()}function Pme({item:n,context:e}){return Wn(`${n} +`,e,!0),null}const xx=ke.createContext({sendmessage(){},sendclose(){},didclose(){}}),oO={input:{color:"$white",active:"$yellow"}};function ou(n){return n?oO.input.active:oO.input.color}function po(n,e){return typeof n==typeof e?n:e}function MB(n,e){return`vm:${n}:${e}`}function wp(n,e,t=0,r=""){return`${n.substring(0,e)}${r}${n.substring(e+t)}`}function Dme({chip:n,active:e,label:t,args:r,context:i}){var d;const[s,o,a]=[po(r[0],""),po(r[1],((d=r[1])==null?void 0:d.toString())??""),po(r[2],"")],c=a||` ${o.toUpperCase()} `,l=ou(e);Wn(`${i.iseven?"$black$onltgray":"$black$ondkcyan"}${c}${l}$onclear ${t} +`,i,!0);const u=ke.useContext(xx),h=ke.useCallback(()=>{u.sendmessage(MB(n,s)),u.sendclose()},[n,u,s]);return ve.jsxs(ve.Fragment,{children:[e&&ve.jsx(bs,{OK_BUTTON:h}),ve.jsx(Np,{hotkey:o,children:h})]})}function Ume({chip:n,active:e,label:t,args:r,context:i}){const[s,o]=[po(r[0],""),r[1]],a=ou(e);Wn(` $purple$16 ${a}${t} +`,i,!0);const c=ke.useContext(xx),l=ke.useCallback(()=>{c.sendmessage(MB(n,s),o),c.sendclose()},[c,n,s,o]);return e&&ve.jsx(bs,{OK_BUTTON:l})}function Fme({chip:n,active:e,label:t,args:r,context:i}){const[s,o,a]=[po(r[0],""),po(r[1],-1),po(r[2],-1)];let c,l;o===-1?(c=0,l=31):a===-1?(c=0,l=o):(c=o,l=a);const u=Rd(n,s),h=Iw(u),d=h==null?void 0:h.value,m=d??0,g=rc(),[v,y]=ke.useState(""),[_,S]=ke.useState(0),[E,T]=ke.useState(!1);let k=`${m}`;const R=t.trim(),M=ou(e);E&&(k=g?wp(v,_,1,"$219+"):v),i.writefullwidth=32,Wn(` # ${M}${R} $green${k}`,i,!1),i.writefullwidth=void 0,Wn(` +`,i,!1);const O=ke.useCallback(U=>{const L=U.alt?10:1;Pl(u,Math.min(l,m+L))},[l,m,u]),C=ke.useCallback(U=>{const L=U.alt?10:1;Pl(u,Math.max(c,m-L))},[c,m,u]),I=ke.useCallback(()=>{T(U=>{const L=!U;if(L){const P=`${d}`;y(P),S(P.length)}else{const P=parseFloat(v),w=isNaN(P)?0:P;Pl(s,Math.min(l,Math.max(c,w)))}return L})},[l,c,v,s,d]);return d!==void 0&&ve.jsxs(ve.Fragment,{children:[e&&ve.jsx(bs,{MOVE_LEFT:C,MOVE_RIGHT:O,OK_BUTTON:I}),E&&ve.jsxs($m,{blockhotkeys:!0,children:[ve.jsx(Np,{hotkey:"ctrl+c",children:()=>{console.info("copy")}}),ve.jsx(Np,{hotkey:"ctrl+v",children:()=>{console.info("paste")}}),ve.jsx(Np,{hotkey:"ctrl+a",children:()=>{console.info("select all")}}),ve.jsx(bs,{MOVE_LEFT:()=>{S(U=>Math.max(0,U-1))},MOVE_RIGHT:()=>{S(U=>Math.min(v.length,U+1))},CANCEL_BUTTON:I,OK_BUTTON:I,keydown:U=>{switch(Kt(U.key)){case"delete":v.length>0&&y(L=>wp(L,_,1));break;case"backspace":_>0&&(y(L=>wp(L,_-1,1)),S(L=>Math.max(0,L-1)));break}U.key.length===1&&v.lengthwp(L,_,0,U.key)),S(L=>L+1))}})]})]})}function Bme({chip:n,active:e,label:t,args:r,context:i}){const[s,o,a]=[po(r[0],""),po(r[1],""),po(r[2],"")];let c,l;o===""?(c="L ",l=" H"):a===""?(c="L ",l=` ${o}`):(c=`${o} `,l=` ${a}`);const u=0,h=8,d=Rd(n,s),m=Iw(d),g=(m==null?void 0:m.value)??0,v=rc(),y=t.trim(),_=ou(e);Wn(` $red $29 ${_}${y} `,i,!1);const E=wp("----:----",g,1,`$green${e?v?"$26":"$27":"$4"}${_}`).replaceAll("-","$7").replaceAll(":","$9");Wn(`${_}${c}${E}${l} $green${g+1} +`,i,!1);const T=ke.useCallback(R=>{const M=R.alt?10:1;Pl(d,Math.min(h,g+M))},[h,g,d]),k=ke.useCallback(R=>{const M=R.alt?10:1;Pl(d,Math.max(u,g-M))},[u,g,d]);return ve.jsx(ve.Fragment,{children:e&&ve.jsx(bs,{MOVE_LEFT:k,MOVE_RIGHT:T})})}function zme({chip:n,active:e,label:t,args:r,context:i}){const[s,...o]=[po(r[0],""),...r.slice(1)],a=0,c=o.length-1,l=Rd(n,s),u=Iw(l),h=(u==null?void 0:u.value)??0,d=rc(),m=`${o[h]}`,g=t.trim(),v=ou(e);Wn(` $dkred ? ${v}${g} `,i,!1);const y=e?d?"$26":"$27":"/";Wn(`${h+1}$green${y}${v}${c+1}`,i,!1),i.writefullwidth=32,Wn(` $green${m}`,i,!1),i.writefullwidth=void 0,Wn(` +`,i,!1);const _=ke.useCallback(E=>{const T=E.alt?10:1;Pl(l,Math.min(c,h+T))},[c,h,l]),S=ke.useCallback(E=>{const T=E.alt?10:1;Pl(l,Math.max(a,h-T))},[a,h,l]);return ve.jsx(ve.Fragment,{children:e&&ve.jsx(bs,{MOVE_LEFT:S,MOVE_RIGHT:_})})}function Vme({chip:n,active:e,label:t,args:r,context:i}){const s=po(r[0],""),o=Rd(n,s),a=xD(o),c=a==null?void 0:a.value,l=(c==null?void 0:c.toJSON())??"",u=rc(),[h,d]=ke.useState(0),[m,g]=ke.useState(!1),[v,y]=ke.useState(void 0),_=`${l} `,S=t.trim(),E=ou(e);Wn(`$green $20 ${E}${S} $green`,i,!1);const T=i.x,R=i.y*i.width;i.writefullwidth=32,Wn(`${_}`,i,!1),i.writefullwidth=void 0,Wn(` +`,i,!1);const M=Z(v),O=i.width-T-2,C=M?Math.min(v,h):h;let I=M?Math.max(v,h):h;M&&(I!==C&&I===h&&--I,yx(T+C+R,T+I+R,15,8,i)),m&&u&&vx(T+h+R,"Û",i);function U(){Z(c)&&(d(C),y(void 0),c.delete(C,I-C+1))}return ve.jsxs(ve.Fragment,{children:[e&&ve.jsx(bs,{OK_BUTTON:()=>{c&&(g(!0),d(c.length),y(void 0))}}),m&&ve.jsx($m,{blockhotkeys:!0,children:ve.jsx(bs,{MOVE_LEFT:L=>{L.shift?Z(v)||y(Nn(h-1,0,l.length)):y(void 0),d(P=>Nn(P-1,0,l.length))},MOVE_RIGHT:L=>{L.shift?Z(v)||y(h):y(void 0),d(P=>Nn(P+1,0,l.length))},CANCEL_BUTTON:()=>{g(!1),d(l.length),y(void 0)},OK_BUTTON:()=>g(!1),keydown:L=>{if(!c)return;const{key:P}=L,w=Kt(P),H={alt:L.altKey,ctrl:fd?L.metaKey:L.ctrlKey,shift:L.shiftKey},V=c.toJSON();switch(w){case"delete":M?U():V.length>0&&c.delete(h,1);break;case"backspace":M?U():h>0&&(c.delete(h-1,1),d(B=>Math.max(0,B-1)));break;default:if(H.ctrl)switch(w){case"a":y(0),d(V.length);break;case"c":Z(navigator.clipboard)&&navigator.clipboard.writeText(c.toJSON()).catch(B=>console.error(B));break;case"v":Z(navigator.clipboard)&&navigator.clipboard.readText().then(B=>{M&&U(),c.insert(h,B),d(h+B.length)}).catch(B=>console.error(B));break;case"x":Z(navigator.clipboard)&&navigator.clipboard.writeText(c.toJSON()).then(()=>U()).catch(B=>console.error(B));break}else H.alt||P.length===1&&V.lengthB+1));break}}})})]})}function Hme({item:n,active:e}){const t=Xi(),r=nc();if(r.iseven=r.y%2===0,typeof n=="string")return ve.jsx(Pme,{player:t,item:n,context:r});if(cn(n)){const[i,s,o,...a]=n;if(typeof i!="string"||typeof s!="string"||typeof o!="string")return null;const c={player:t,chip:i,active:e,label:s,args:a,context:r};switch(Kt(o)){case"hk":case"hotkey":return ve.jsx(Dme,{...c});case"hyperlink":return ve.jsx(Ume,{...c});case"rn":case"range":return ve.jsx(Bme,{...c});case"sl":case"select":return ve.jsx(zme,{...c});case"nm":case"number":return ve.jsx(Fme,{...c});case"tx":case"text":return ve.jsx(Vme,{...c})}_x(r)}return null}function RM({store:n,children:e}){return ve.jsx(MM.Provider,{value:n,children:e})}function kM({width:n,height:e}){const t=ke.useContext(MM),[r,i,s]=$A(t,iu(o=>[o.char,o.color,o.bg,o.render]));return n>0&&e>0&&ve.jsx(q3,{char:r.slice(),color:i.slice(),bg:s.slice(),width:n,height:e})}function CB({margin:n=1,selected:e=-1,width:t,height:r,color:i,bg:s,text:o}){const a=CM(t,r,0,i,s),c=a.getState(),l={...ig(t,r,i,s,0,n,t-n,r),...a.getState(),x:n};return Ome(c,0,i,s),c.changed(),ve.jsxs(RM,{store:a,children:[ve.jsx(Uu.Provider,{value:l,children:o.map((u,h)=>ve.jsx(Hme,{item:u,active:h===e},h))}),ve.jsx(kM,{width:t,height:r})]})}var Gme=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.01,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1/(2*Math.PI);return r/Math.atan(1/t)*Math.atan(Math.sin(2*Math.PI*e*i)/t)},Wme=function(e){return 1/(1+e+.48*e*e+.235*e*e*e)};function jme(n,e,t){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:.25,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:.01,s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1/0,o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Wme,a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:.001,c="velocity_"+e;if(n.__damp===void 0&&(n.__damp={}),n.__damp[c]===void 0&&(n.__damp[c]=0),Math.abs(n[e]-t)<=a)return n[e]=t,!1;r=Math.max(1e-4,r);var l=2/r,u=o(l*i),h=n[e]-t,d=t,m=s*r;h=Math.min(Math.max(h,-m),m),t=n[e]-h;var g=(n.__damp[c]+l*h)*i;n.__damp[c]=(n.__damp[c]-l*g)*u;var v=t+(h+g)*u;return d-n[e]>0==v>d&&(v=d,n.__damp[c]=(v-d)/i),n[e]=v,!0}const $me=2,qme=14,RB=qme*$me;function Xme(n){return Xj(n,RB*.5)}function Kme(n,e,t,r,i=1.235){function s(a){return Gme(a,r)}jme(n.userData,e,t,i,r,RB*12,s),n.position[e]=Xme(n.userData[e]);const o=t-n.position.y;return Math.abs(o)<.1}function aO({x:n,y:e,color:t,on:r=232,off:i=7,alt:s}){const o=rc(),a=Lme(),c=ke.useRef(0),l=Z(s)?c.current%2===0?r:s:r;return Br(a,a.width,a.height,n,e,{char:o?l:i,color:t}),a.changed(),o&&++c.current,null}function Yme({store:n,children:e}){return ve.jsx(wB.Provider,{value:n,children:e})}function Zme({width:n,height:e}){const t=ke.useContext(wB),[r]=$A(t,iu(i=>[i.dither,i.render]));return n>0&&e>0&&ve.jsx(nx,{alphas:r.slice(),width:n,height:e})}function Jme({name:n,width:e,height:t,color:r,bg:i,text:s,shouldclose:o}){const{viewport:a}=Ma(),c=e-3,l=t-3,u=CM(e,t,0,r,i),h=Ime(c,l,0),d=ke.useContext(xx),m=u.getState();for(let w=1;w2&&w{o&&d.didclose()},[o,d]);ke.useEffect(()=>{if(I.current&&!o){const w=a.height;I.current.position.y=w,I.current.userData.y=w,I.current.userData.vy=0}},[o]),ry(ke.useCallback((w,H)=>{if(Z(I.current)){const V=o?t*2*-$i:0;Kme(I.current,"y",V,H)&&U()}},[o,U,t]));const L=ke.useCallback(w=>{const H=w.alt?10:1;E(V=>Math.max(0,V-H))},[E]),P=ke.useCallback(w=>{const H=w.alt?10:1;E(V=>Math.min(s.length,V+H))},[E,s.length]);return ve.jsx(RM,{store:u,children:ve.jsx(Yme,{store:h,children:ve.jsx("group",{ref:I,"position-y":1e6,children:ve.jsxs($m,{children:[ve.jsx(bs,{MOVE_UP:L,MOVE_DOWN:P,CANCEL_BUTTON:d.sendclose}),ve.jsx(kM,{width:e,height:t}),ve.jsxs("group",{position:[2*ps,2*$i,0],children:[ve.jsx(Zme,{width:c,height:l}),ve.jsx(CB,{name:n,width:c,height:l,margin:0,color:r,bg:wn.ONCLEAR,text:k,selected:R}),ve.jsx(aO,{x:1,y:1}),ve.jsx(aO,{x:1,y:2+R,on:26,alt:27,off:45,color:12})]})]})})})})}function cO({rect:n,shouldclose:e=!1}){switch(n.type){case 0:return ve.jsx(CB,{name:n.name,width:n.width,height:n.height,color:14,bg:1,text:n.text});case 1:return ve.jsx(Jme,{name:n.name,width:n.width,height:n.height,color:14,bg:1,text:n.text,shouldclose:e});case 2:return ve.jsx(Aue,{width:n.width,height:n.height})}return null}function Qme(){const n=Ma(g=>g.viewport),{width:e,height:t}=n.getCurrentViewport(),r=Math.floor(e/ps),i=Math.floor(t/$i),s=e-r*ps,o=t-i*$i,[a,c]=ke.useState(),l=kc(yle(g=>g.gadget.panels));if(r<1||i<1)return null;const u={name:"main",type:2,x:0,y:0,width:r,height:i,text:[]},h=[];let d=!0;l.forEach(g=>{let v;switch(g.edge){case Ti.LEFT:v={name:g.name,type:0,x:u.x,y:u.y,width:g.size,height:u.height,text:g.text},u.x+=g.size,u.width-=g.size,h.push(v);break;default:case Ti.RIGHT:v={name:g.name,type:0,x:u.x+u.width-g.size,y:u.y,width:g.size,height:u.height,text:g.text},u.width-=g.size,h.push(v);break;case Ti.TOP:v={name:g.name,type:0,x:u.x,y:u.y,width:u.width,height:g.size,text:g.text},u.y+=g.size,u.height-=g.size,h.push(v);break;case Ti.BOTTOM:v={name:g.name,type:0,x:u.x,y:u.y+u.height-g.size,width:u.width,height:g.size,text:g.text},u.height-=g.size,h.push(v);break;case Ti.SCROLL:v={name:g.name,type:1,x:0,y:0,width:Nn(g.size||50,24,u.width-2),height:Nn(18,8,u.height-8),text:g.text},v.x=u.x+Math.floor((u.width-v.width)*.5),v.y=u.y+Math.floor((u.height-v.height)*.5),d=!1,Yf(a,v)||c(Gi(v))}}),h.unshift(u);const m=Xi();return ve.jsx(xx.Provider,{value:{sendmessage(g,v){Pt.emit(g,"gadget",v,m)},sendclose(){L9("gadget",m)},didclose(){c(void 0)}},children:ve.jsxs("group",{position:[s*.5,o*.5,-512],children:[h.map(g=>ve.jsx("group",{position:[g.x*ps,g.y*$i,0],children:ve.jsx(cO,{rect:g})},g.name)),a&&ve.jsxs(Lo.Fragment,{children:[ve.jsx("group",{position:[0,0,800],children:ve.jsx(Zle,{width:r,height:i,alpha:.14})}),ve.jsx("group",{position:[a.x*ps,a.y*$i,900],children:ve.jsx(cO,{rect:a,shouldclose:d})})]},a.name)]})})}const ege=250,tge=249,om=wn.BLUE,nge=wn.WHITE,Jl=wn.DKBLUE,rge=wn.DKGRAY,kB=wn.BLACK,Wv=1,Y1=ps*Wv,Z1=$i*Wv,NB=ke.createContext({sendmessage(){}});function Gf(n,e,t,r,i){const s=ea(i);i.iseven=i.y%2===0,i.active.bg=e&&!n?kB:Jl,i.active.leftedge=s.left,i.active.rightedge=s.right,i.active.topedge=s.top,i.active.bottomedge=s.bottom,i.x=i.active.leftedge+t,i.y=i.active.topedge+r}function Rf(n,e,t,r,i,s,o,a){const c=ea(i);i.iseven=i.y%2===0,i.active.bg=Jl,i.active.leftedge=c.left+s,i.active.rightedge=c.right-s,i.active.topedge=c.top+o,i.active.bottomedge=c.bottom-a,i.x=i.active.leftedge+t,i.y=i.active.topedge+r}function ige(n){let e=0;return n.split(/\r?\n/).map(r=>{const i=e,s=`${r} +`;return e+=s.length,{start:i,code:s,end:i+r.length}})}function sge(n){return n.reduce((e,t)=>{const r=t.code.length;return r>e?r:e},0)}function oge(n,e){for(let t=0;t{const e="nativeEvent"in n?n.nativeEvent:n;return{deltaX:e.deltaX||0,deltaY:e.deltaY||0,deltaZ:e.deltaZ||0,timeStamp:e.timeStamp}},uge=n=>[n.deltaX,n.deltaY,n.deltaZ],o_=n=>{const e=uge(n).map(Math.abs);return Math.max(...e)};var Cl;(function(n){n.ALL_OTHER_CHECKS_FAILED="ALL_OTHER_CHECKS_FAILED",n.NO_PREVIOUS_EVENT_TO_COMPARE="NO_PREVIOUS_EVENT_TO_COMPARE",n.PAST_TIMESTAMP_EVENT="PAST_TIMESTAMP_EVENT",n.ENOUGH_TIME_PASSED="ENOUGH_TIME_PASSED",n.NON_DECREASING_DELTAS_OF_KNOWN_HUMAN="NON_DECREASING_DELTAS_OF_KNOWN_HUMAN",n.DELTA_MODULE_HAS_BEEN_INCREASING="DELTA_MODULE_HAS_BEEN_INCREASING"})(Cl||(Cl={}));class hge{constructor({sensitivity:e=2,delay:t=100,increasingDeltasThreshold:r=3}={}){yt(this,"sensitivity");yt(this,"delay");yt(this,"increasingDeltasThreshold");yt(this,"previousEvents");this.sensitivity=Math.max(1,e),this.delay=Math.max(1,t),this.increasingDeltasThreshold=Math.max(2,r),this.previousEvents=[]}check(e){var s;if(!(("nativeEvent"in e?e.nativeEvent:e)instanceof Event))throw new Error(`"${e}" is not a valid event`);const r=lge(e);if(o_(r)(((s=this.previousEvents.at(-1))==null?void 0:s.timeStamp)||0)&&this.previousEvents.push(r),i}isHuman(e){const t=this.previousEvents.at(-1);if(!t)return{isHuman:!0,reason:Cl.NO_PREVIOUS_EVENT_TO_COMPARE};if(e.timeStampt.timeStamp+this.delay)return{isHuman:!0,reason:Cl.ENOUGH_TIME_PASSED};const s=o_(e),o=o_(t);if(s>=o){if(this.previousEvents.length===1)return{isHuman:!0,reason:Cl.NON_DECREASING_DELTAS_OF_KNOWN_HUMAN};if(this.increasingDeltasThreshold<=2||this.previousEvents.length>=this.increasingDeltasThreshold&&this.previousEvents.slice(-this.increasingDeltasThreshold).map(o_).every((u,h,d)=>h===0||u>d[h-1]))return{isHuman:!0,reason:Cl.DELTA_MODULE_HAS_BEEN_INCREASING}}return{isHuman:!1,reason:Cl.ALL_OTHER_CHECKS_FAILED}}}function lO(){}const fge=Lo.forwardRef(function({args:e,children:t,...r},i){const s=Lo.useRef(null);return Lo.useImperativeHandle(i,()=>s.current),ve.jsxs("mesh",{ref:s,...r,children:[ve.jsx("planeGeometry",{attach:"geometry",args:e}),t]})}),dge=Lo.forwardRef(function({blocking:e=!1,cursor:t="default",x:r=0,y:i=0,width:s=1,height:o=1,opacity:a=1,visible:c=!0,...l},u){const h=s*.5,d=o*.5,m=[(r+h)*ps,(i+d)*$i,0],g=Qy();return ve.jsx(fge,{ref:u,args:[s*ps,o*$i],userData:{blocking:e,cursor:t,clippingPlanes:g},onClick:e?lO:void 0,onPointerMove:e?lO:void 0,position:m,...l,children:ve.jsx("meshBasicMaterial",{color:"white",opacity:a,visible:c,transparent:a!==1,clippingPlanes:g})})}),pge=new hge({sensitivity:fd?7:2}),uO=4,mge=.75;function gge(n){const e=Nn(n,-uO,uO);return Math.round(e*mge)}function OB({debug:n=!1,disabled:e=!1,blocking:t=!0,cursor:r="pointer",x:i=0,y:s=0,width:o=30,height:a=10,children:c,onScroll:l,...u}){return ve.jsxs("group",{...u,children:[ve.jsx(dge,{blocking:t,cursor:r,visible:n,x:i,y:s,width:o,height:a,onWheel:h=>{e||!pge.check(h)||l==null||l(gge(h.deltaY))}}),c]})}function _ge({tapeycursor:n,logrowtotalheight:e}){const t=rc(),r=nc(),i=Cr(),s=Xi(),o=ea(r),a=i.buffer[i.bufferindex];let c=i.xcursor,l=i.xcursor,u=!1;Z(i.xselect)&&Z(i.yselect)&&(u=!0,c=Math.min(i.xcursor,i.xselect),l=Math.max(i.xcursor,i.xselect),i.xcursor!==i.xselect&&--l);const h=l-c+1,d=i.ycursor===0,m=u?a.substring(c,l+1):a;function g(O,C,I){i.bufferindex>0&&Cr.setState({bufferindex:0}),i.buffer[0]=age(a,O,C,I),Cr.setState({buffer:i.buffer,xselect:void 0,xcursor:O+(I??"").length})}function v(O){const C=i.buffer.length-1,I=Nn(O,0,C);Cr.setState({bufferindex:I,xcursor:i.buffer[I].length,ycursor:0,xselect:void 0,yselect:void 0})}function y(O){O?Z(i.xselect)||Cr.setState({xselect:i.xcursor,yselect:i.ycursor}):Cr.setState({xselect:void 0,yselect:void 0})}function _(){Z(i.xselect)&&(Cr.setState({xcursor:c,xselect:void 0,yselect:void 0}),g(c,h))}function S(){Cr.setState({xcursor:a.length,ycursor:0,xselect:void 0,yselect:void 0})}Gf(!1,!1,0,0,r);const E="main:0.20.45 - if lost try #help";r.x=o.right-E.length,Wn(`$dkcyan${E}`,r,!0);const T="$196",R="$205".repeat(o.width-6);Gf(!1,!1,0,o.height-2,r),Wn(` ${T}${R}${T} `,r,!0);const M=a.padEnd(o.width," ");if(Gf(!1,!1,0,o.height-1,r),EB(M,r,!0),Z(i.xselect)&&Z(i.yselect)&&i.xcursor!==i.xselect){const O=Math.min(i.xcursor,i.xselect),C=Math.min(i.ycursor,i.yselect),I=Math.max(i.xcursor,i.xselect)-1,U=Math.max(i.ycursor,i.yselect);for(let L=C;L<=U;++L){const P=O+(o.bottom-L)*o.width,w=I+(o.bottom-L)*o.width;yx(P,w,15,8,r)}}if(t){const O=o.left+i.xcursor,C=o.top+n;vx(O+C*r.width,"Ý",r)}return ke.useEffect(()=>{let O=i.scroll;n<4&&O++,n>o.bottom-4&&O--,Cr.setState({scroll:Math.round(Nn(O,0,e))})},[i.scroll,n,e,o.bottom]),r.changed(),ve.jsxs(ve.Fragment,{children:[ve.jsx(OB,{blocking:!0,x:o.left,y:o.top,width:o.width,height:o.height,onScroll:O=>{y(!1),Cr.setState({ycursor:Nn(Math.round(i.ycursor-O),0,e)})}}),ve.jsx(bs,{keydown:O=>{const{key:C}=O,I=Kt(C),U=ix(O);switch(I){case"arrowleft":y(U.shift),U.ctrl?Cr.setState({xcursor:0}):Cr.setState({xcursor:Nn(i.xcursor-(U.alt?10:1),0,o.right)});break;case"arrowright":y(U.shift),U.ctrl?Cr.setState({xcursor:d?a.length:o.right}):Cr.setState({xcursor:Nn(i.xcursor+(U.alt?10:1),0,o.right)});break;case"arrowup":U.ctrl?v(i.bufferindex+1):(y(U.shift),Cr.setState({ycursor:Nn(Math.round(i.ycursor+(U.alt?10:1)),0,e)}));break;case"arrowdown":U.ctrl?v(i.bufferindex-1):(y(U.shift),Cr.setState({ycursor:Nn(Math.round(i.ycursor-(U.alt?10:1)),0,e)}));break;case"enter":{const L=u?m:a;L.length&&(d?(Cr.setState({xcursor:0,bufferindex:0,xselect:void 0,yselect:void 0,buffer:["",L,...i.buffer.slice(1).filter(P=>P!==L)]}),sy("tape",L,s)):S());break}case"esc":case"escape":iw("tape",s);break;case"tab":XL("tape",!U.shift,s);break;case"delete":d?u?_():a.length>0&&g(i.xcursor,1):S();break;case"backspace":d?u?_():i.xcursor>0&&g(i.xcursor-1,1):S();break;default:if(U.ctrl)switch(I){case"a":Cr.setState({xselect:0,yselect:0,xcursor:a.length,ycursor:0});break;case"c":d&&Z(navigator.clipboard)?navigator.clipboard.writeText(m).catch(L=>console.error(L)):S();break;case"v":d&&Z(navigator.clipboard)?navigator.clipboard.readText().then(L=>{const P=L.replaceAll("\r","");u?g(c,h,P):g(i.xcursor,0,P)}).catch(L=>console.error(L)):S();break;case"x":d&&Z(navigator.clipboard)?navigator.clipboard.writeText(m).then(()=>_()).catch(L=>console.error(L)):S();break}else U.alt||C.length===1&&(d&&i.xcursor<=a.length?u?(g(c,h,C),Cr.setState({xselect:void 0})):g(i.xcursor,0,C):S());break}}})]})}function vge({blink:n,active:e,prefix:t,label:r,words:i,y:s}){const o=nc(),a=ke.useCallback(()=>{if(Z(navigator.clipboard)){const[,...l]=i,u=l.join(" ");navigator.clipboard.writeText(u).then(()=>vn("copyit","copied!")).catch(h=>console.error(h))}},[i]),c=ou(!!e);return Gf(!!n,!!e,0,s,o),Wn(`${t} $purple$16 $yellowCOPYIT ${c}${r}`,o,!0),o.changed(),e&&ve.jsx(bs,{OK_BUTTON:a})}function yge({blink:n,active:e,prefix:t,label:r,words:i,y:s}){const o=nc(),a=ke.useContext(NB),c=ke.useCallback(()=>{const[u,h]=i;a.sendmessage(u,h)},[i,a]),l=ou(!!e);return Gf(!!n,!!e,0,s,o),Wn(`${t} $purple$16 ${l}${r}`,o,!0),o.changed(),e&&ve.jsx(bs,{OK_BUTTON:c})}function LB({blink:n,active:e,text:t,y:r}){const i=nc(),s=ea(i),o=t.startsWith("!");if(Gf(!!n,!!e,0,r,i),i.active.bottomedge=s.bottom,Wn(o?"":t,i,!0),o){const[a,...c]=t.slice(1).split("!"),l=`${c.join("!")}`;let u="PRESS ME";const h=[];gx(l,!0).tokens.forEach(y=>{switch(y.tokenType){case TM:u=y.image.slice(1);break;default:h.push(y.image);break}});const[m,...g]=h,v={blink:n,active:e,prefix:a,label:u,words:g,y:r};switch(Kt(m)){case"hk":case"hotkey":return null;case"rn":case"range":return null;case"sl":case"select":return null;case"nm":case"number":return null;case"tx":case"text":return null;case"copyit":return ve.jsx(vge,{...v,words:h});default:case"hyperlink":return ve.jsx(yge,{...v,words:h})}}return null}function xge(n){const e=rc();return ve.jsx(LB,{active:!0,blink:e,...n})}function J1(){const n=Xi(),[e,t]=cs(iu(d=>[d.terminal.logs,d.editor.open])),r=nc(),i=Cr(),s=ea(r),o=e.map(d=>{const[,m,g,...v]=d;let y="$white";switch(m){case"debug":y="$yellow";break;case"error":y="$red";break}const _=v.map(T=>`${T}`).join(" "),S=_.startsWith("!"),E=`$blue[${y}${g}$blue]`;return`${S?"!":""}${E} ${_}`}),a=o.map(d=>{if(d.startsWith("!"))return 1;const m=AM(d,s.width,s.height);return(m==null?void 0:m.y)??1});let c=0,l=s.bottom-1;const u=a.map(d=>(l-=d,c+=d,l));++c;const h=s.bottom-i.ycursor+i.scroll;return ve.jsxs(ve.Fragment,{children:[ve.jsx(NM,{context:r}),ve.jsxs(NB.Provider,{value:{sendmessage(d,m){const[g,v]=cge(d);if(g==="self"){const y=`#${v} ${m??""}`;sy("tape",y,n)}else Pt.emit(`${g}:${v}`,"gadget",m,n)}},children:[o.map((d,m)=>{const g=u[m]+i.scroll,v=a[m],y=g+v;return y<0||g>s.bottom-1?null:!t&&h>=g&&h[m.editor.type,m.editor.title])),o=rc(),a="$205".repeat(e.width-4);Rf(!1,!1,0,1,n,0,0,0),Wn(`$179$${o?"7":"232"}$200${a}$181`,n,!0);const l=` ${`[${i}] `}${s} `,u=AM(l,e.width,e.height),h=(u==null?void 0:u.measuredwidth)??1,d=Math.round(e.width*.5)-Math.round(h*.5);return Rf(!1,!1,d,0,n,0,0,0),Wn(l,n,!0),n.changed(),null}function Ege({xcursor:n,ycursor:e,xoffset:t,yoffset:r,rows:i,codepage:s}){var P,w;const o=rc(),a=nc(),c=ke.useRef(),l=mr(),u=ea(a),h=cs(H=>H.editor.player),d=IB(s),m=Z(d)?d.toJSON():"",g=i.length-1,v=n+1-t,y=e+2-r;if(Z(s)){const H=((P=c.current)==null?void 0:P.x)!==v||((w=c.current)==null?void 0:w.y)!==y;if(o||H){const V=u.left+v,B=u.top+y;B>u.top+1&&Bu.left&&V0&&(d==null||d.delete(H,V)),Z(B)&&(d==null||d.insert(H,B)),mr.setState({cursor:H+(B??"").length,select:void 0})}function I(){Z(l.select)&&(mr.setState({cursor:E}),C(E,R))}function U(){mr.setState({cursor:_,select:void 0})}const L=ke.useCallback(function(V){const B=Math.round(e+V);if(B<0)mr.setState({cursor:0});else if(B>g)mr.setState({cursor:_});else{const z=i[B];mr.setState({cursor:z.start+Math.min(n,z.code.length-1)})}},[_,i,g,n,e]);return a.changed(),ve.jsxs(ve.Fragment,{children:[ve.jsx(OB,{blocking:!0,x:u.left,y:u.top,width:u.width,height:u.height,onScroll:H=>L(H*.75)}),ve.jsx(bs,{keydown:H=>{if(!Z(d))return;const{key:V}=H,B=Kt(V),z=ix(H);switch(B){case"arrowleft":if(O(z.shift),z.ctrl)mr.setState({cursor:S.start});else{const W=l.cursor-(z.alt?10:1);mr.setState({cursor:Nn(W,0,_)})}break;case"arrowright":if(O(z.shift),z.ctrl)mr.setState({cursor:S.end});else{const W=l.cursor+(z.alt?10:1);mr.setState({cursor:Nn(W,0,_)})}break;case"arrowup":O(z.shift),z.ctrl?mr.setState({cursor:0}):L(z.alt?-10:-1);break;case"arrowdown":O(z.shift),z.ctrl?mr.setState({cursor:_}):L(z.alt?10:1);break;case"enter":Z(d)&&(d.insert(l.cursor,` +`),mr.setState({cursor:l.cursor+1}));break;case"esc":case"escape":z.shift||z.alt||z.ctrl?iw("tape",h):q9("editor",h);break;case"tab":XL("editor",!z.shift,h);break;case"delete":k?I():C(l.cursor,1);break;case"backspace":k?I():m.length>0&&C(Math.max(l.cursor-1,0),1);break;default:if(z.ctrl)switch(B){case"a":mr.setState({cursor:_,select:0});break;case"c":Z(navigator.clipboard)?navigator.clipboard.writeText(M).catch(W=>An("tape","clipboard",W)):U();break;case"v":Z(navigator.clipboard)?navigator.clipboard.readText().then(W=>{const K=W.replaceAll("\r","");k?C(E,R,K):C(l.cursor,0,K)}).catch(W=>An("tape","clipboard",W)):U();break;case"x":Z(navigator.clipboard)?navigator.clipboard.writeText(M).then(()=>I()).catch(W=>An("tape","clipboard",W)):U();break;case"p":sy("editor",M,h),vn("editor",`running: ${M}`);break}else if(!z.alt){if(V.length===1)if(k)C(E,R,V);else{const W=l.cursor+V.length;d.insert(l.cursor,V),mr.setState({cursor:W})}}break}}})]})}function bge({ycursor:n,xoffset:e,yoffset:t,rows:r,codepage:i}){const s=rc(),o=nc(),a=mr(),c=ea(o);if(!Z(i)){const m=(s?"|":"-").repeat(3);return Rf(!1,!1,0,0,o,1,2,1),Wn(` ${m} LOADING ${m}`,o,!0),null}let l=a.cursor,u=a.cursor,h=!1;Z(a.select)&&(h=!0,l=Math.min(a.cursor,a.select),u=Math.max(a.cursor,a.select),a.cursor!==a.select&&--u);const d=c.left+1;Rf(!1,!1,-e,-t,o,1,2,1);for(let m=0;m=l){const _=Math.max(g.start,l)-g.start-e,S=Math.min(g.end,u)-g.start-e,E=c.width-3,T=1+o.y*o.width,k=Math.max(0,_),R=Math.min(E,S);k<=E&&R>=d&&yx(T+k,T+R,nge,rge,o)}if(++o.y,o.y>=c.bottom)break}return o.disablewrap=!1,null}function Q1(){const[n]=cs(iu(v=>[v.editor])),e=nc(),t=mr(),r=xD(KL(n.book,n.page)),i=ea(e);ke.useEffect(()=>(Q9("editor",n.book,n.page,n.player),()=>{e$("editor",n.book,n.page,n.player)}),[n.book,n.page,n.player]);const s=IB(r),o=Z(s)?s.toJSON():"",a=ige(o),c=oge(t.cursor,a),l=t.cursor-a[c].start,u=sge(a),h={rows:a,xcursor:l,ycursor:c,codepage:r,xoffset:t.xscroll,yoffset:t.yscroll},d=32,m=(Math.round(u/d)+1)*d,g=a.length;return ke.useEffect(()=>{let v=t.xscroll;const y=l-v,_=i.width-3;let S=Math.round(Nn(Math.abs(y)*.5,1,d));S<8&&(S=1),y>_-8&&(v+=S),y<8&&(v-=S);let E=t.yscroll;const T=c-E,k=i.height-4,R=Math.round(k*.5);let M=Math.round(Nn(Math.abs(T)*.25,1,R));M<8&&(M=1),T>k-4&&(E+=M),T<4&&(E-=M),setTimeout(()=>mr.setState({xscroll:Math.round(Nn(v,0,m)),yscroll:Math.round(Nn(E,0,g))}),16)},[l,m,t.xscroll,c,g,t.yscroll,i.width,i.height]),ve.jsxs(ve.Fragment,{children:[ve.jsx(NM,{context:e}),ve.jsx(Sge,{}),ve.jsx(bge,{...h}),ve.jsx(Ege,{...h})]})}function hO(n,e,t,r,i){return{...i,x:n,y:e,reset:{...i.reset,topedge:e,leftedge:n,rightedge:t,bottomedge:r},active:{...i.reset,topedge:e,leftedge:n,rightedge:t,bottomedge:r}}}function Tge({context:n}){const[e,t]=cs(iu(l=>[l.layout,l.editor.open])),r=n.width-1,i=n.height-1,s=ea(n),o=Math.floor(s.height*.5),a=ke.useMemo(()=>hO(0,0,r,o-1,n),[o,r,n]),c=ke.useMemo(()=>hO(0,o,r,i,n),[o,r,i,n]);if(t){let l,u;switch(e){case Bi.SPLIT_Y:case Bi.SPLIT_Y_ALT:l=a,u=c;break}if(Z(l)&&Z(u))switch(e){case Bi.SPLIT_Y:return ve.jsxs(ve.Fragment,{children:[ve.jsx(Uu.Provider,{value:l,children:ve.jsx(J1,{})}),ve.jsx(Uu.Provider,{value:u,children:ve.jsx(Q1,{})})]});case Bi.SPLIT_Y_ALT:return ve.jsxs(ve.Fragment,{children:[ve.jsx(Uu.Provider,{value:l,children:ve.jsx(Q1,{})}),ve.jsx(Uu.Provider,{value:u,children:ve.jsx(J1,{})})]})}}return ve.jsx(ve.Fragment,{children:ve.jsx(Uu.Provider,{value:n,children:t?ve.jsx(Q1,{}):ve.jsx(J1,{})})})}function wge(){const n=Ma(S=>S.viewport),{width:e,height:t}=n.getCurrentViewport(),r=Math.floor(e/ps),i=Math.floor(t/$i),s=Math.floor(e/Y1),o=Math.floor(t/Z1),a=e-s*Y1,c=t-o*Z1;let l=0;const u=0,h=s;let d=o;const[m,g]=cs(iu(S=>[S.layout,S.terminal.open]));switch(m){case Bi.TOP:d=Math.round(o*.5);break;case Bi.BOTTOM:d=Math.round(o*.5),l=o-d;break;default:case Bi.FULL:break}const v=CM(h,d,0,om,Jl),y={...ig(h,d,om,Jl),...v.getState()};if(h<1||d<1)return null;const _=Xi();return ve.jsx(RM,{store:v,children:ve.jsxs("group",{position:[0,0,900],children:[g&&ve.jsx(Jle,{width:r,height:i,top:l,left:u,right:u+h-1,bottom:l+d-1}),ve.jsx("group",{position:[a*.5+u*Y1,c+l*Z1,1],scale:[Wv,Wv,1],children:g?ve.jsxs($m,{blockhotkeys:!0,children:[ve.jsx(NM,{context:y}),ve.jsx(Tge,{context:y}),ve.jsx(kM,{width:h,height:d})]}):ve.jsx(Np,{hotkey:"Shift+?",children:()=>qL("tape",_)})})]})})}class Age{constructor(){this.encoder=new TextEncoder,this._pieces=[],this._parts=[]}append_buffer(e){this.flush(),this._parts.push(e)}append(e){this._pieces.push(e)}flush(){if(this._pieces.length>0){const e=new Uint8Array(this._pieces);this._parts.push(e),this._pieces=[]}}toArrayBuffer(){const e=[];for(const t of this._parts)e.push(t);return Mge(e).buffer}}function Mge(n){let e=0;for(const i of n)e+=i.byteLength;const t=new Uint8Array(e);let r=0;for(const i of n){const s=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);t.set(s,r),r+=i.byteLength}return t}function PB(n){return new Cge(n).unpack()}function DB(n){const e=new Rge,t=e.pack(n);return t instanceof Promise?t.then(()=>e.getBuffer()):e.getBuffer()}class Cge{constructor(e){this.index=0,this.dataBuffer=e,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}unpack(){const e=this.unpack_uint8();if(e<128)return e;if((e^224)<32)return(e^224)-32;let t;if((t=e^160)<=15)return this.unpack_raw(t);if((t=e^176)<=15)return this.unpack_string(t);if((t=e^144)<=15)return this.unpack_array(t);if((t=e^128)<=15)return this.unpack_map(t);switch(e){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:return;case 213:return;case 214:return;case 215:return;case 216:return t=this.unpack_uint16(),this.unpack_string(t);case 217:return t=this.unpack_uint32(),this.unpack_string(t);case 218:return t=this.unpack_uint16(),this.unpack_raw(t);case 219:return t=this.unpack_uint32(),this.unpack_raw(t);case 220:return t=this.unpack_uint16(),this.unpack_array(t);case 221:return t=this.unpack_uint32(),this.unpack_array(t);case 222:return t=this.unpack_uint16(),this.unpack_map(t);case 223:return t=this.unpack_uint32(),this.unpack_map(t)}}unpack_uint8(){const e=this.dataView[this.index]&255;return this.index++,e}unpack_uint16(){const e=this.read(2),t=(e[0]&255)*256+(e[1]&255);return this.index+=2,t}unpack_uint32(){const e=this.read(4),t=((e[0]*256+e[1])*256+e[2])*256+e[3];return this.index+=4,t}unpack_uint64(){const e=this.read(8),t=((((((e[0]*256+e[1])*256+e[2])*256+e[3])*256+e[4])*256+e[5])*256+e[6])*256+e[7];return this.index+=8,t}unpack_int8(){const e=this.unpack_uint8();return e<128?e:e-256}unpack_int16(){const e=this.unpack_uint16();return e<32768?e:e-65536}unpack_int32(){const e=this.unpack_uint32();return e<2**31?e:e-2**32}unpack_int64(){const e=this.unpack_uint64();return e<2**63?e:e-2**64}unpack_raw(e){if(this.length>31,r=(e>>23&255)-127,i=e&8388607|8388608;return(t===0?1:-1)*i*2**(r-23)}unpack_double(){const e=this.unpack_uint32(),t=this.unpack_uint32(),r=e>>31,i=(e>>20&2047)-1023,o=(e&1048575|1048576)*2**(i-20)+t*2**(i-52);return(r===0?1:-1)*o}read(e){const t=this.index;if(t+e<=this.length)return this.dataView.subarray(t,t+e);throw new Error("BinaryPackFailure: read index out of range")}}class Rge{getBuffer(){return this._bufferBuilder.toArrayBuffer()}pack(e){if(typeof e=="string")this.pack_string(e);else if(typeof e=="number")Math.floor(e)===e?this.pack_integer(e):this.pack_double(e);else if(typeof e=="boolean")e===!0?this._bufferBuilder.append(195):e===!1&&this._bufferBuilder.append(194);else if(e===void 0)this._bufferBuilder.append(192);else if(typeof e=="object")if(e===null)this._bufferBuilder.append(192);else{const t=e.constructor;if(e instanceof Array){const r=this.pack_array(e);if(r instanceof Promise)return r.then(()=>this._bufferBuilder.flush())}else if(e instanceof ArrayBuffer)this.pack_bin(new Uint8Array(e));else if("BYTES_PER_ELEMENT"in e){const r=e;this.pack_bin(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}else if(e instanceof Date)this.pack_string(e.toString());else{if(e instanceof Blob)return e.arrayBuffer().then(r=>{this.pack_bin(new Uint8Array(r)),this._bufferBuilder.flush()});if(t==Object||t.toString().startsWith("class")){const r=this.pack_object(e);if(r instanceof Promise)return r.then(()=>this._bufferBuilder.flush())}else throw new Error(`Type "${t.toString()}" not yet supported`)}}else throw new Error(`Type "${typeof e}" not yet supported`);this._bufferBuilder.flush()}pack_bin(e){const t=e.length;if(t<=15)this.pack_uint8(160+t);else if(t<=65535)this._bufferBuilder.append(218),this.pack_uint16(t);else if(t<=4294967295)this._bufferBuilder.append(219),this.pack_uint32(t);else throw new Error("Invalid length");this._bufferBuilder.append_buffer(e)}pack_string(e){const t=this._textEncoder.encode(e),r=t.length;if(r<=15)this.pack_uint8(176+r);else if(r<=65535)this._bufferBuilder.append(216),this.pack_uint16(r);else if(r<=4294967295)this._bufferBuilder.append(217),this.pack_uint32(r);else throw new Error("Invalid length");this._bufferBuilder.append_buffer(t)}pack_array(e){const t=e.length;if(t<=15)this.pack_uint8(144+t);else if(t<=65535)this._bufferBuilder.append(220),this.pack_uint16(t);else if(t<=4294967295)this._bufferBuilder.append(221),this.pack_uint32(t);else throw new Error("Invalid length");const r=i=>{if(ir(i+1)):r(i+1)}};return r(0)}pack_integer(e){if(e>=-32&&e<=127)this._bufferBuilder.append(e&255);else if(e>=0&&e<=255)this._bufferBuilder.append(204),this.pack_uint8(e);else if(e>=-128&&e<=127)this._bufferBuilder.append(208),this.pack_int8(e);else if(e>=0&&e<=65535)this._bufferBuilder.append(205),this.pack_uint16(e);else if(e>=-32768&&e<=32767)this._bufferBuilder.append(209),this.pack_int16(e);else if(e>=0&&e<=4294967295)this._bufferBuilder.append(206),this.pack_uint32(e);else if(e>=-2147483648&&e<=2147483647)this._bufferBuilder.append(210),this.pack_int32(e);else if(e>=-9223372036854776e3&&e<=9223372036854776e3)this._bufferBuilder.append(211),this.pack_int64(e);else if(e>=0&&e<=18446744073709552e3)this._bufferBuilder.append(207),this.pack_uint64(e);else throw new Error("Invalid integer")}pack_double(e){let t=0;e<0&&(t=1,e=-e);const r=Math.floor(Math.log(e)/Math.LN2),i=e/2**r-1,s=Math.floor(i*2**52),o=2**32,a=t<<31|r+1023<<20|s/o&1048575,c=s%o;this._bufferBuilder.append(203),this.pack_int32(a),this.pack_int32(c)}pack_object(e){const t=Object.keys(e),r=t.length;if(r<=15)this.pack_uint8(128+r);else if(r<=65535)this._bufferBuilder.append(222),this.pack_uint16(r);else if(r<=4294967295)this._bufferBuilder.append(223),this.pack_uint32(r);else throw new Error("Invalid length");const i=s=>{if(si(s+1))}return i(s+1)}};return i(0)}pack_uint8(e){this._bufferBuilder.append(e)}pack_uint16(e){this._bufferBuilder.append(e>>8),this._bufferBuilder.append(e&255)}pack_uint32(e){const t=e&4294967295;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255)}pack_uint64(e){const t=e/4294967296,r=e%2**32;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255),this._bufferBuilder.append((r&4278190080)>>>24),this._bufferBuilder.append((r&16711680)>>>16),this._bufferBuilder.append((r&65280)>>>8),this._bufferBuilder.append(r&255)}pack_int8(e){this._bufferBuilder.append(e&255)}pack_int16(e){this._bufferBuilder.append((e&65280)>>8),this._bufferBuilder.append(e&255)}pack_int32(e){this._bufferBuilder.append(e>>>24&255),this._bufferBuilder.append((e&16711680)>>>16),this._bufferBuilder.append((e&65280)>>>8),this._bufferBuilder.append(e&255)}pack_int64(e){const t=Math.floor(e/4294967296),r=e%2**32;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255),this._bufferBuilder.append((r&4278190080)>>>24),this._bufferBuilder.append((r&16711680)>>>16),this._bufferBuilder.append((r&65280)>>>8),this._bufferBuilder.append(r&255)}constructor(){this._bufferBuilder=new Age,this._textEncoder=new TextEncoder}}let UB=!0,FB=!0;function G_(n,e,t){const r=n.match(e);return r&&r.length>=t&&parseInt(r[t],10)}function Ch(n,e,t){if(!n.RTCPeerConnection)return;const r=n.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(o,a){if(o!==e)return i.apply(this,arguments);const c=l=>{const u=t(l);u&&(a.handleEvent?a.handleEvent(u):a(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),i.apply(this,[o,c])};const s=r.removeEventListener;r.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(a))return s.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(r,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function kge(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(UB=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function Nge(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(FB=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function BB(){if(typeof window=="object"){if(UB)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function IM(n,e){FB&&console.warn(n+" is deprecated, please use "+e+" instead.")}function Ige(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.userAgentData&&t.userAgentData.brands){const r=t.userAgentData.brands.find(i=>i.brand==="Chromium");if(r)return{browser:"chrome",version:parseInt(r.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=G_(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=G_(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=G_(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function fO(n){return Object.prototype.toString.call(n)==="[object Object]"}function zB(n){return fO(n)?Object.keys(n).reduce(function(e,t){const r=fO(n[t]),i=r?zB(n[t]):n[t],s=r&&!Object.keys(i).length;return i===void 0||s?e:Object.assign(e,{[t]:i})},{}):n}function bT(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(r=>{r.endsWith("Id")?bT(n,n.get(e[r]),t):r.endsWith("Ids")&&e[r].forEach(i=>{bT(n,n.get(i),t)})}))}function dO(n,e,t){const r=t?"outbound-rtp":"inbound-rtp",i=new Map;if(e===null)return i;const s=[];return n.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&s.push(o)}),s.forEach(o=>{n.forEach(a=>{a.type===r&&a.trackId===o.id&&bT(n,a,i)})}),i}const pO=BB;function VB(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const r=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const u=typeof a[l]=="object"?a[l]:{ideal:a[l]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const h=function(d,m){return d?d+m.charAt(0).toUpperCase()+m.slice(1):m==="deviceId"?"sourceId":m};if(u.ideal!==void 0){c.optional=c.optional||[];let d={};typeof u.ideal=="number"?(d[h("min",l)]=u.ideal,c.optional.push(d),d={},d[h("max",l)]=u.ideal,c.optional.push(d)):(d[h("",l)]=u.ideal,c.optional.push(d))}u.exact!==void 0&&typeof u.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[h("",l)]=u.exact):["min","max"].forEach(d=>{u[d]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[h(d,l)]=u[d])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},i=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(u,h,d){h in u&&!(d in u)&&(u[d]=u[h],delete u[h])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=r(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const u=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete a.video.facingMode;let h;if(l.exact==="environment"||l.ideal==="environment"?h=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(d=>{d=d.filter(g=>g.kind==="videoinput");let m=d.find(g=>h.some(v=>g.label.toLowerCase().includes(v)));return!m&&d.length&&h.includes("back")&&(m=d[d.length-1]),m&&(a.video.deviceId=l.exact?{exact:m.deviceId}:{ideal:m.deviceId}),a.video=r(a.video),pO("chrome: "+JSON.stringify(a)),c(a)})}a.video=r(a.video)}return pO("chrome: "+JSON.stringify(a)),c(a)},s=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){i(a,u=>{t.webkitGetUserMedia(u,c,h=>{l&&l(s(h))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return i(c,l=>a(l).then(u=>{if(l.audio&&!u.getAudioTracks().length||l.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function HB(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function GB(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=r=>{r.stream.addEventListener("addtrack",i=>{let s;n.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===i.track.id):s={track:i.track};const o=new Event("track");o.track=i.track,o.receiver=s,o.transceiver={receiver:s},o.streams=[r.stream],this.dispatchEvent(o)}),r.stream.getTracks().forEach(i=>{let s;n.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===i.id):s={track:i};const o=new Event("track");o.track=i,o.receiver=s,o.transceiver={receiver:s},o.streams=[r.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Ch(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function WB(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(i,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=i.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:i}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,c){let l=i.apply(this,arguments);return l||(l=e(this,a),this._senders.push(l)),l};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const r=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],r.apply(this,[s]),s.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(i=>i._pc=this),r},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function jB(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=t.apply(this,[]);return s.forEach(o=>o._pc=this),s});const r=n.RTCPeerConnection.prototype.addTrack;r&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=r.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(o=>dO(o,s.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=t.apply(this,[]);return i.forEach(s=>s._pc=this),i}),Ch(n,"track",r=>(r.receiver._pc=r.srcElement,r)),n.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(s=>dO(s,i.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const r=arguments[0];let i,s,o;return this.getSenders().forEach(a=>{a.track===r&&(i?o=!0:i=a)}),this.getReceivers().forEach(a=>(a.track===r&&(s?o=!0:s=a),a.track===r)),o||i&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function $B(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(h=>h.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const r=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],r.apply(this,arguments)};const i=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),i.apply(this,arguments)}}function qB(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return $B(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(h=>this._reverseStreams[h.id])};const r=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(h=>{if(this.getSenders().find(m=>m.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const h=new n.MediaStream(u.getTracks());this._streams[u.id]=h,this._reverseStreams[h.id]=u,u=h}r.apply(this,[u])};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},n.RTCPeerConnection.prototype.addTrack=function(u,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const d=[].slice.call(arguments,1);if(d.length!==1||!d[0].getTracks().find(v=>v===u))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(v=>v.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const g=this._streams[h.id];if(g)g.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new n.MediaStream([u]);this._streams[h.id]=v,this._reverseStreams[v.id]=h,this.addStream(v)}return this.getSenders().find(v=>v.track===u)};function s(l,u){let h=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(d=>{const m=l._reverseStreams[d],g=l._streams[m.id];h=h.replace(new RegExp(g.id,"g"),m.id)}),new RTCSessionDescription({type:u.type,sdp:h})}function o(l,u){let h=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(d=>{const m=l._reverseStreams[d],g=l._streams[m.id];h=h.replace(new RegExp(m.id,"g"),g.id)}),new RTCSessionDescription({type:u.type,sdp:h})}["createOffer","createAnswer"].forEach(function(l){const u=n.RTCPeerConnection.prototype[l],h={[l](){const d=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[g=>{const v=s(this,g);d[0].apply(null,[v])},g=>{d[1]&&d[1].apply(null,g)},arguments[2]]):u.apply(this,arguments).then(g=>s(this,g))}};n.RTCPeerConnection.prototype[l]=h[l]});const a=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:s(this,l)}}),n.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let d;Object.keys(this._streams).forEach(m=>{this._streams[m].getTracks().find(v=>u.track===v)&&(d=this._streams[m])}),d&&(d.getTracks().length===1?this.removeStream(this._reverseStreams[d.id]):d.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function TT(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const r=n.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=i[t]})}function XB(n,e){Ch(n,"negotiationneeded",t=>{const r=t.target;if(!((e.version<72||r.getConfiguration&&r.getConfiguration().sdpSemantics==="plan-b")&&r.signalingState!=="stable"))return t})}const mO=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:XB,shimAddTrackRemoveTrack:qB,shimAddTrackRemoveTrackWithNative:$B,shimGetSendersWithDtmf:WB,shimGetUserMedia:VB,shimMediaStream:HB,shimOnTrack:GB,shimPeerConnection:TT,shimSenderReceiverGetStats:jB},Symbol.toStringTag,{value:"Module"}));function KB(n,e){const t=n&&n.navigator,r=n&&n.MediaStreamTrack;if(t.getUserMedia=function(i,s,o){IM("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(i).then(s,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const i=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),i(o.audio,"autoGainControl","mozAutoGainControl"),i(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},r&&r.prototype.getSettings){const o=r.prototype.getSettings;r.prototype.getSettings=function(){const a=o.apply(this,arguments);return i(a,"mozAutoGainControl","autoGainControl"),i(a,"mozNoiseSuppression","noiseSuppression"),a}}if(r&&r.prototype.applyConstraints){const o=r.prototype.applyConstraints;r.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),i(a,"autoGainControl","mozAutoGainControl"),i(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function Oge(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(r){if(!(r&&r.video)){const i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return r.video===!0?r.video={mediaSource:e}:r.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(r)})}function YB(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function wT(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){const s=n.RTCPeerConnection.prototype[i],o={[i](){return arguments[0]=new(i==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};n.RTCPeerConnection.prototype[i]=o[i]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[s,o,a]=arguments;return r.apply(this,[s||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((u,h)=>{c.set(h,Object.assign({},u,{type:t[u.type]||u.type}))})}return c}).then(o,a)}}function ZB(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const i=t.apply(this,arguments);return i._pc=this,i}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function JB(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const r=e.apply(this,[]);return r.forEach(i=>i._pc=this),r}),Ch(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function QB(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){IM("removeStream","removeTrack"),this.getSenders().forEach(r=>{r.track&&t.getTracks().includes(r.track)&&this.removeTrack(r)})})}function e5(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function t5(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let r=arguments[1]&&arguments[1].sendEncodings;r===void 0&&(r=[]),r=[...r];const i=r.length>0;i&&r.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(i){const{sender:o}=s,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=r,o.sendEncodings=r,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return s})}function n5(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const r=e.apply(this,arguments);return"encodings"in r||(r.encodings=[].concat(this.sendEncodings||[{}])),r})}function r5(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function i5(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}const gO=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:t5,shimCreateAnswer:i5,shimCreateOffer:r5,shimGetDisplayMedia:Oge,shimGetParameters:n5,shimGetUserMedia:KB,shimOnTrack:YB,shimPeerConnection:wT,shimRTCDataChannel:e5,shimReceiverGetStats:JB,shimRemoveStream:QB,shimSenderGetStats:ZB},Symbol.toStringTag,{value:"Module"}));function s5(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(r){this._localStreams||(this._localStreams=[]),this._localStreams.includes(r)||this._localStreams.push(r),r.getAudioTracks().forEach(i=>e.call(this,i,r)),r.getVideoTracks().forEach(i=>e.call(this,i,r))},n.RTCPeerConnection.prototype.addTrack=function(r,...i){return i&&i.forEach(s=>{this._localStreams?this._localStreams.includes(s)||this._localStreams.push(s):this._localStreams=[s]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const r=this._localStreams.indexOf(t);if(r===-1)return;this._localStreams.splice(r,1);const i=t.getTracks();this.getSenders().forEach(s=>{i.includes(s.track)&&this.removeTrack(s)})})}}function o5(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=r=>{r.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);const s=new Event("addstream");s.stream=i,this.dispatchEvent(s)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const r=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(s=>{if(r._remoteStreams||(r._remoteStreams=[]),r._remoteStreams.indexOf(s)>=0)return;r._remoteStreams.push(s);const o=new Event("addstream");o.stream=s,r.dispatchEvent(o)})}),e.apply(r,arguments)}}}function a5(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,r=e.createAnswer,i=e.setLocalDescription,s=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(l,u){const h=arguments.length>=2?arguments[2]:arguments[0],d=t.apply(this,[h]);return u?(d.then(l,u),Promise.resolve()):d},e.createAnswer=function(l,u){const h=arguments.length>=2?arguments[2]:arguments[0],d=r.apply(this,[h]);return u?(d.then(l,u),Promise.resolve()):d};let a=function(c,l,u){const h=i.apply(this,[c]);return u?(h.then(l,u),Promise.resolve()):h};e.setLocalDescription=a,a=function(c,l,u){const h=s.apply(this,[c]);return u?(h.then(l,u),Promise.resolve()):h},e.setRemoteDescription=a,a=function(c,l,u){const h=o.apply(this,[c]);return u?(h.then(l,u),Promise.resolve()):h},e.addIceCandidate=a}function c5(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,r=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=i=>r(l5(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(r,i,s){e.mediaDevices.getUserMedia(r).then(i,s)}).bind(e))}function l5(n){return n&&n.video!==void 0?Object.assign({},n,{video:zB(n.video)}):n}function u5(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(r,i){if(r&&r.iceServers){const s=[];for(let o=0;oo.receiver.track.kind==="audio");r.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):r.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof r.offerToReceiveVideo<"u"&&(r.offerToReceiveVideo=!!r.offerToReceiveVideo);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="video");r.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):r.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function d5(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}const _O=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:d5,shimCallbacksAPI:a5,shimConstraints:l5,shimCreateOfferLegacy:f5,shimGetUserMedia:c5,shimLocalStreamsAPI:s5,shimRTCIceServerUrls:u5,shimRemoteStreamsAPI:o5,shimTrackEventTransceiver:h5},Symbol.toStringTag,{value:"Module"}));var p5={exports:{}};(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(` +`).map(r=>r.trim())},e.splitSections=function(t){return t.split(` +m=`).map((i,s)=>(s>0?"m="+i:i).trim()+`\r +`)},e.getDescription=function(t){const r=e.splitSections(t);return r&&r[0]},e.getMediaSections=function(t){const r=e.splitSections(t);return r.shift(),r},e.matchPrefix=function(t,r){return e.splitLines(t).filter(i=>i.indexOf(r)===0)},e.parseCandidate=function(t){let r;t.indexOf("a=candidate:")===0?r=t.substring(12).split(" "):r=t.substring(10).split(" ");const i={foundation:r[0],component:{1:"rtp",2:"rtcp"}[r[1]]||r[1],protocol:r[2].toLowerCase(),priority:parseInt(r[3],10),ip:r[4],address:r[4],port:parseInt(r[5],10),type:r[7]};for(let s=8;s0?r[0].split("/")[1]:"sendrecv",uri:r[1],attributes:r.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r +`},e.parseFmtp=function(t){const r={};let i;const s=t.substring(t.indexOf(" ")+1).split(";");for(let o=0;o{t.parameters[o]!==void 0?s.push(o+"="+t.parameters[o]):s.push(o)}),r+="a=fmtp:"+i+" "+s.join(";")+`\r +`}return r},e.parseRtcpFb=function(t){const r=t.substring(t.indexOf(" ")+1).split(" ");return{type:r.shift(),parameter:r.join(" ")}},e.writeRtcpFb=function(t){let r="",i=t.payloadType;return t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(s=>{r+="a=rtcp-fb:"+i+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r +`}),r},e.parseSsrcMedia=function(t){const r=t.indexOf(" "),i={ssrc:parseInt(t.substring(7,r),10)},s=t.indexOf(":",r);return s>-1?(i.attribute=t.substring(r+1,s),i.value=t.substring(s+1)):i.attribute=t.substring(r+1),i},e.parseSsrcGroup=function(t){const r=t.substring(13).split(" ");return{semantics:r.shift(),ssrcs:r.map(i=>parseInt(i,10))}},e.getMid=function(t){const r=e.matchPrefix(t,"a=mid:")[0];if(r)return r.substring(6)},e.parseFingerprint=function(t){const r=t.substring(14).split(" ");return{algorithm:r[0].toLowerCase(),value:r[1].toUpperCase()}},e.getDtlsParameters=function(t,r){return{role:"auto",fingerprints:e.matchPrefix(t+r,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,r){let i="a=setup:"+r+`\r +`;return t.fingerprints.forEach(s=>{i+="a=fingerprint:"+s.algorithm+" "+s.value+`\r +`}),i},e.parseCryptoLine=function(t){const r=t.substring(9).split(" ");return{tag:parseInt(r[0],10),cryptoSuite:r[1],keyParams:r[2],sessionParams:r.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r +`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const r=t.substring(7).split("|");return{keyMethod:"inline",keySalt:r[0],lifeTime:r[1],mkiValue:r[2]?r[2].split(":")[0]:void 0,mkiLength:r[2]?r[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,r){return e.matchPrefix(t+r,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,r){const i=e.matchPrefix(t+r,"a=ice-ufrag:")[0],s=e.matchPrefix(t+r,"a=ice-pwd:")[0];return i&&s?{usernameFragment:i.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let r="a=ice-ufrag:"+t.usernameFragment+`\r +a=ice-pwd:`+t.password+`\r +`;return t.iceLite&&(r+=`a=ice-lite\r +`),r},e.parseRtpParameters=function(t){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");r.profile=s[2];for(let a=3;a{r.headerExtensions.push(e.parseExtmap(a))});const o=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return r.codecs.forEach(a=>{o.forEach(c=>{a.rtcpFeedback.find(u=>u.type===c.type&&u.parameter===c.parameter)||a.rtcpFeedback.push(c)})}),r},e.writeRtpDescription=function(t,r){let i="";i+="m="+t+" ",i+=r.codecs.length>0?"9":"0",i+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=r.codecs.map(o=>o.preferredPayloadType!==void 0?o.preferredPayloadType:o.payloadType).join(" ")+`\r +`,i+=`c=IN IP4 0.0.0.0\r +`,i+=`a=rtcp:9 IN IP4 0.0.0.0\r +`,r.codecs.forEach(o=>{i+=e.writeRtpMap(o),i+=e.writeFmtp(o),i+=e.writeRtcpFb(o)});let s=0;return r.codecs.forEach(o=>{o.maxptime>s&&(s=o.maxptime)}),s>0&&(i+="a=maxptime:"+s+`\r +`),r.headerExtensions&&r.headerExtensions.forEach(o=>{i+=e.writeExtmap(o)}),i},e.parseRtpEncodingParameters=function(t){const r=[],i=e.parseRtpParameters(t),s=i.fecMechanisms.indexOf("RED")!==-1,o=i.fecMechanisms.indexOf("ULPFEC")!==-1,a=e.matchPrefix(t,"a=ssrc:").map(d=>e.parseSsrcMedia(d)).filter(d=>d.attribute==="cname"),c=a.length>0&&a[0].ssrc;let l;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(d=>d.substring(17).split(" ").map(g=>parseInt(g,10)));u.length>0&&u[0].length>1&&u[0][0]===c&&(l=u[0][1]),i.codecs.forEach(d=>{if(d.name.toUpperCase()==="RTX"&&d.parameters.apt){let m={ssrc:c,codecPayloadType:parseInt(d.parameters.apt,10)};c&&l&&(m.rtx={ssrc:l}),r.push(m),s&&(m=JSON.parse(JSON.stringify(m)),m.fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},r.push(m))}}),r.length===0&&c&&r.push({ssrc:c});let h=e.matchPrefix(t,"b=");return h.length&&(h[0].indexOf("b=TIAS:")===0?h=parseInt(h[0].substring(7),10):h[0].indexOf("b=AS:")===0?h=parseInt(h[0].substring(5),10)*1e3*.95-50*40*8:h=void 0,r.forEach(d=>{d.maxBitrate=h})),r},e.parseRtcpParameters=function(t){const r={},i=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="cname")[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");r.reducedSize=s.length>0,r.compound=s.length===0;const o=e.matchPrefix(t,"a=rtcp-mux");return r.mux=o.length>0,r},e.writeRtcpParameters=function(t){let r="";return t.reducedSize&&(r+=`a=rtcp-rsize\r +`),t.mux&&(r+=`a=rtcp-mux\r +`),t.ssrc!==void 0&&t.cname&&(r+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r +`),r},e.parseMsid=function(t){let r;const i=e.matchPrefix(t,"a=msid:");if(i.length===1)return r=i[0].substring(7).split(" "),{stream:r[0],track:r[1]};const s=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="msid");if(s.length>0)return r=s[0].value.split(" "),{stream:r[0],track:r[1]}},e.parseSctpDescription=function(t){const r=e.parseMLine(t),i=e.matchPrefix(t,"a=max-message-size:");let s;i.length>0&&(s=parseInt(i[0].substring(19),10)),isNaN(s)&&(s=65536);const o=e.matchPrefix(t,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:r.fmt,maxMessageSize:s};const a=e.matchPrefix(t,"a=sctpmap:");if(a.length>0){const c=a[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,r){let i=[];return t.protocol!=="DTLS/SCTP"?i=["m="+t.kind+" 9 "+t.protocol+" "+r.protocol+`\r +`,`c=IN IP4 0.0.0.0\r +`,"a=sctp-port:"+r.port+`\r +`]:i=["m="+t.kind+" 9 "+t.protocol+" "+r.port+`\r +`,`c=IN IP4 0.0.0.0\r +`,"a=sctpmap:"+r.port+" "+r.protocol+` 65535\r +`],r.maxMessageSize!==void 0&&i.push("a=max-message-size:"+r.maxMessageSize+`\r +`),i.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,r,i){let s;const o=r!==void 0?r:2;return t?s=t:s=e.generateSessionId(),`v=0\r +o=`+(i||"thisisadapterortc")+" "+s+" "+o+` IN IP4 127.0.0.1\r +s=-\r +t=0 0\r +`},e.getDirection=function(t,r){const i=e.splitLines(t);for(let s=0;s(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function AT(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||Ch(n,"icecandidate",e=>{if(e.candidate){const t=Wf.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function j_(n,e){if(!n.RTCPeerConnection)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const c=Wf.splitSections(a.sdp);return c.shift(),c.some(l=>{const u=Wf.parseMLine(l);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},r=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},i=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},s=function(a,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const u=Wf.matchPrefix(a.sdp,"a=max-message-size:");return u.length>0?l=parseInt(u[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},o=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=r(arguments[0]),l=i(c),u=s(arguments[0],c);let h;l===0&&u===0?h=Number.POSITIVE_INFINITY:l===0||u===0?h=Math.max(l,u):h=Math.min(l,u);const d={};Object.defineProperty(d,"maxMessageSize",{get(){return h}}),this._sctp=d}return o.apply(this,arguments)}}function $_(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(r,i){const s=r.send;r.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(r.readyState==="open"&&i.sctp&&c>i.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+i.sctp.maxMessageSize+" bytes)");return s.apply(r,arguments)}}const t=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const i=t.apply(this,arguments);return e(i,this),i},Ch(n,"datachannel",r=>(e(r.channel,r.target),r))}function MT(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const r=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{const s=i.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const o=new Event("connectionstatechange",i);s.dispatchEvent(o)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function CT(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(i){if(i&&i.sdp&&i.sdp.indexOf(` +a=extmap-allow-mixed`)!==-1){const s=i.sdp.split(` +`).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(` +`);n.RTCSessionDescription&&i instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:i.type,sdp:s}):i.sdp=s}return t.apply(this,arguments)}}function q_(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function X_(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}const Pge=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:CT,shimAddIceCandidateNullOrEmpty:q_,shimConnectionState:MT,shimMaxMessageSize:j_,shimParameterlessSetLocalDescription:X_,shimRTCIceCandidate:W_,shimRTCIceCandidateRelayProtocol:AT,shimSendThrowTypeError:$_},Symbol.toStringTag,{value:"Module"}));function Dge({window:n}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=BB,r=Ige(n),i={browserDetails:r,commonShim:Pge,extractVersion:G_,disableLog:kge,disableWarnings:Nge,sdp:Lge};switch(r.browser){case"chrome":if(!mO||!TT||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(r.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=mO,q_(n,r),X_(n),VB(n,r),HB(n),TT(n,r),GB(n),qB(n,r),WB(n),jB(n),XB(n,r),W_(n),AT(n),MT(n),j_(n,r),$_(n),CT(n,r);break;case"firefox":if(!gO||!wT||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=gO,q_(n,r),X_(n),KB(n,r),wT(n,r),YB(n),QB(n),ZB(n),JB(n),e5(n),t5(n),n5(n),r5(n),i5(n),W_(n),MT(n),j_(n,r),$_(n);break;case"safari":if(!_O||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=_O,q_(n,r),X_(n),u5(n),f5(n),a5(n),s5(n),o5(n),h5(n),c5(n),d5(n),W_(n),AT(n),j_(n,r),$_(n),CT(n,r);break;default:t("Unsupported browser!");break}return i}const vO=Dge({window:typeof window>"u"?void 0:window});function Rh(n,e,t,r){Object.defineProperty(n,e,{get:t,set:r,enumerable:!0,configurable:!0})}class g5{constructor(){this.chunkedMTU=16300,this._dataCount=1,this.chunk=e=>{const t=[],r=e.byteLength,i=Math.ceil(r/this.chunkedMTU);let s=0,o=0;for(;o=this.minChromeVersion:n==="firefox"?e>=this.minFirefoxVersion:n==="safari"?!this.isIOS&&e>=this.minSafariVersion:!1:!1}getBrowser(){return eE.browserDetails.browser}getVersion(){return eE.browserDetails.version||0}isUnifiedPlanSupported(){const n=this.getBrowser(),e=eE.browserDetails.version||0;if(n==="chrome"&&e=this.minFirefoxVersion)return!0;if(!window.RTCRtpTransceiver||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let t,r=!1;try{t=new RTCPeerConnection,t.addTransceiver("audio"),r=!0}catch{}finally{t&&t.close()}return r}toString(){return`Supports: + browser:${this.getBrowser()} + version:${this.getVersion()} + isIOS:${this.isIOS} + isWebRTCSupported:${this.isWebRTCSupported()} + isBrowserSupported:${this.isBrowserSupported()} + isUnifiedPlanSupported:${this.isUnifiedPlanSupported()}`}constructor(){this.isIOS=typeof navigator<"u"?["iPad","iPhone","iPod"].includes(navigator.platform):!1,this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}},Fge=n=>!n||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(n),_5=()=>Math.random().toString(36).slice(2),yO={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"};class Bge extends g5{noop(){}blobToArrayBuffer(e,t){const r=new FileReader;return r.onload=function(i){i.target&&t(i.target.result)},r.readAsArrayBuffer(e),r}binaryStringToArrayBuffer(e){const t=new Uint8Array(e.length);for(let r=0;r=3&&this._print(3,...e)}warn(...e){this._logLevel>=2&&this._print(2,...e)}error(...e){this._logLevel>=1&&this._print(1,...e)}setLogFunction(e){this._print=e}_print(e,...t){const r=[zge,...t];for(const i in r)r[i]instanceof Error&&(r[i]="("+r[i].name+") "+r[i].message);e>=3?console.log(...r):e>=2?console.warn("WARNING",...r):e>=1&&console.error("ERROR",...r)}constructor(){this._logLevel=0}}var ut=new Vge,OM={},Hge=Object.prototype.hasOwnProperty,Zi="~";function am(){}Object.create&&(am.prototype=Object.create(null),new am().__proto__||(Zi=!1));function Gge(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function v5(n,e,t,r,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Gge(t,r||n,i),o=Zi?Zi+e:e;return n._events[o]?n._events[o].fn?n._events[o]=[n._events[o],s]:n._events[o].push(s):(n._events[o]=s,n._eventsCount++),n}function K_(n,e){--n._eventsCount===0?n._events=new am:delete n._events[e]}function Ri(){this._events=new am,this._eventsCount=0}Ri.prototype.eventNames=function(){var e=[],t,r;if(this._eventsCount===0)return e;for(r in t=this._events)Hge.call(t,r)&&e.push(Zi?r.slice(1):r);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ri.prototype.listeners=function(e){var t=Zi?Zi+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,s=r.length,o=new Array(s);iPa);Rh(kh,"PeerErrorType",()=>ir);Rh(kh,"BaseConnectionErrorType",()=>cm);Rh(kh,"DataConnectionErrorType",()=>lm);Rh(kh,"SerializationType",()=>gd);Rh(kh,"SocketEventType",()=>Ca);Rh(kh,"ServerMessageType",()=>oi);var Pa;(function(n){n.Data="data",n.Media="media"})(Pa||(Pa={}));var ir;(function(n){n.BrowserIncompatible="browser-incompatible",n.Disconnected="disconnected",n.InvalidID="invalid-id",n.InvalidKey="invalid-key",n.Network="network",n.PeerUnavailable="peer-unavailable",n.SslUnavailable="ssl-unavailable",n.ServerError="server-error",n.SocketError="socket-error",n.SocketClosed="socket-closed",n.UnavailableID="unavailable-id",n.WebRTC="webrtc"})(ir||(ir={}));var cm;(function(n){n.NegotiationFailed="negotiation-failed",n.ConnectionClosed="connection-closed"})(cm||(cm={}));var lm;(function(n){n.NotOpenYet="not-open-yet",n.MessageToBig="message-too-big"})(lm||(lm={}));var gd;(function(n){n.Binary="binary",n.BinaryUTF8="binary-utf8",n.JSON="json",n.None="raw"})(gd||(gd={}));var Ca;(function(n){n.Message="message",n.Disconnected="disconnected",n.Error="error",n.Close="close"})(Ca||(Ca={}));var oi;(function(n){n.Heartbeat="HEARTBEAT",n.Candidate="CANDIDATE",n.Offer="OFFER",n.Answer="ANSWER",n.Open="OPEN",n.Error="ERROR",n.IdTaken="ID-TAKEN",n.InvalidKey="INVALID-KEY",n.Leave="LEAVE",n.Expire="EXPIRE"})(oi||(oi={}));var LM={};LM=JSON.parse('{"name":"peerjs","version":"1.5.4","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu ","afrokick ","ericz ","Jairo ","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana ","Carlos Caballero ","hc ","Muhammad Asif ","PrashoonB ","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski ","lmb ","Jairooo ","Moritz Stückler ","Simon ","Denis Lukov ","Philipp Hancke ","Hans Oksendahl ","Jess ","khankuan ","DUODVK ","XiZhao ","Matthias Lohr ","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt ","Chris Cowan ","Alex Chuev ","alxnull ","Yemel Jardi ","Ben Parnell ","Benny Lichtner ","fresheneesz ","bob.barstead@exaptive.com ","chandika ","emersion ","Christopher Van ","eddieherm ","Eduardo Pinho ","Evandro Zanatta ","Gardner Bickford ","Gian Luca ","PatrickJS ","jonnyf ","Hizkia Felix ","Hristo Oskov ","Isaac Madwed ","Ilya Konanykhin ","jasonbarry ","Jonathan Burke ","Josh Hamit ","Jordan Austin ","Joel Wetzell ","xizhao ","Alberto Torres ","Jonathan Mayol ","Jefferson Felix ","Rolf Erik Lekang ","Kevin Mai-Husan Chia ","Pepijn de Vos ","JooYoung ","Tobias Speicher ","Steve Blaurock ","Kyrylo Shegeda ","Diwank Singh Tomer ","Sören Balko ","Arpit Solanki ","Yuki Ito ","Artur Zayats "],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","browser-minified-msgpack":"dist/serializer.msgpack.mjs","types":"dist/types.d.ts","engines":{"node":">= 14"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"chrome >= 83, edge >= 83, firefox >= 80, safari >= 15"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"chrome >= 83, edge >= 83, firefox >= 80, safari >= 15"},"source":"lib/global.ts"},"browser-minified-msgpack":{"context":"browser","outputFormat":"esmodule","isLibrary":true,"optimize":true,"engines":{"browsers":"chrome >= 83, edge >= 83, firefox >= 102, safari >= 15"},"source":"lib/dataconnection/StreamConnection/MsgPack.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit && tsc -p e2e/tsconfig.json --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"jest","test:watch":"jest --watch","coverage":"jest --coverage --collectCoverageFrom=\\"./lib/**\\"","format":"prettier --write .","format:check":"prettier --check .","semantic-release":"semantic-release","e2e":"wdio run e2e/wdio.local.conf.ts","e2e:bstack":"wdio run e2e/wdio.bstack.conf.ts"},"devDependencies":{"@parcel/config-default":"^2.9.3","@parcel/packager-ts":"^2.9.3","@parcel/transformer-typescript-tsc":"^2.9.3","@parcel/transformer-typescript-types":"^2.9.3","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@swc/core":"^1.3.27","@swc/jest":"^0.2.24","@types/jasmine":"^4.3.4","@wdio/browserstack-service":"^8.11.2","@wdio/cli":"^8.11.2","@wdio/globals":"^8.11.2","@wdio/jasmine-framework":"^8.11.2","@wdio/local-runner":"^8.11.2","@wdio/spec-reporter":"^8.11.2","@wdio/types":"^8.10.4","http-server":"^14.1.1","jest":"^29.3.1","jest-environment-jsdom":"^29.3.1","mock-socket":"^9.0.0","parcel":"^2.9.3","prettier":"^3.0.0","semantic-release":"^21.0.0","ts-node":"^10.9.1","typescript":"^5.0.0","wdio-geckodriver-service":"^5.0.1"},"dependencies":{"@msgpack/msgpack":"^2.8.0","eventemitter3":"^4.0.7","peerjs-js-binarypack":"^2.1.0","webrtc-adapter":"^9.0.0"},"alias":{"process":false,"buffer":false}}');class Wge extends OM.EventEmitter{constructor(e,t,r,i,s,o=5e3){super(),this.pingInterval=o,this._disconnected=!0,this._messagesQueue=[];const a=e?"wss://":"ws://";this._baseUrl=a+t+":"+r+i+"peerjs?key="+s}start(e,t){this._id=e;const r=`${this._baseUrl}&id=${e}&token=${t}`;this._socket||!this._disconnected||(this._socket=new WebSocket(r+"&version="+LM.version),this._disconnected=!1,this._socket.onmessage=i=>{let s;try{s=JSON.parse(i.data),ut.log("Server message received:",s)}catch{ut.log("Invalid server message",i.data);return}this.emit(Ca.Message,s)},this._socket.onclose=i=>{this._disconnected||(ut.log("Socket closed.",i),this._cleanup(),this._disconnected=!0,this.emit(Ca.Disconnected))},this._socket.onopen=()=>{this._disconnected||(this._sendQueuedMessages(),ut.log("Socket open"),this._scheduleHeartbeat())})}_scheduleHeartbeat(){this._wsPingTimer=setTimeout(()=>{this._sendHeartbeat()},this.pingInterval)}_sendHeartbeat(){if(!this._wsOpen()){ut.log("Cannot send heartbeat, because socket closed");return}const e=JSON.stringify({type:oi.Heartbeat});this._socket.send(e),this._scheduleHeartbeat()}_wsOpen(){return!!this._socket&&this._socket.readyState===1}_sendQueuedMessages(){const e=[...this._messagesQueue];this._messagesQueue=[];for(const t of e)this.send(t)}send(e){if(this._disconnected)return;if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit(Ca.Error,"Invalid message");return}if(!this._wsOpen())return;const t=JSON.stringify(e);this._socket.send(t)}close(){this._disconnected||(this._cleanup(),this._disconnected=!0)}_cleanup(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)}}class y5{constructor(e){this.connection=e}startConnection(e){const t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===Pa.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){const r=this.connection,i={ordered:!!e.reliable},s=t.createDataChannel(r.label,i);r._initializeDataChannel(s),this._makeOffer()}else this.handleSDP("OFFER",e.sdp)}_startPeerConnection(){ut.log("Creating RTCPeerConnection.");const e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e}_setupListeners(e){const t=this.connection.peer,r=this.connection.connectionId,i=this.connection.type,s=this.connection.provider;ut.log("Listening for ICE candidates."),e.onicecandidate=o=>{!o.candidate||!o.candidate.candidate||(ut.log(`Received ICE candidates for ${t}:`,o.candidate),s.socket.send({type:oi.Candidate,payload:{candidate:o.candidate,type:i,connectionId:r},dst:t}))},e.oniceconnectionstatechange=()=>{switch(e.iceConnectionState){case"failed":ut.log("iceConnectionState is failed, closing connections to "+t),this.connection.emitError(cm.NegotiationFailed,"Negotiation of connection to "+t+" failed."),this.connection.close();break;case"closed":ut.log("iceConnectionState is closed, closing connections to "+t),this.connection.emitError(cm.ConnectionClosed,"Connection to "+t+" closed."),this.connection.close();break;case"disconnected":ut.log("iceConnectionState changed to disconnected on the connection with "+t);break;case"completed":e.onicecandidate=()=>{};break}this.connection.emit("iceStateChanged",e.iceConnectionState)},ut.log("Listening for data channel"),e.ondatachannel=o=>{ut.log("Received data channel");const a=o.channel;s.getConnection(t,r)._initializeDataChannel(a)},ut.log("Listening for remote stream"),e.ontrack=o=>{ut.log("Received remote stream");const a=o.streams[0],c=s.getConnection(t,r);if(c.type===Pa.Media){const l=c;this._addStreamToMediaConnection(a,l)}}}cleanup(){ut.log("Cleaning up PeerConnection to "+this.connection.peer);const e=this.connection.peerConnection;if(!e)return;this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=()=>{};const t=e.signalingState!=="closed";let r=!1;const i=this.connection.dataChannel;i&&(r=!!i.readyState&&i.readyState!=="closed"),(t||r)&&e.close()}async _makeOffer(){const e=this.connection.peerConnection,t=this.connection.provider;try{const r=await e.createOffer(this.connection.options.constraints);ut.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(r.sdp=this.connection.options.sdpTransform(r.sdp)||r.sdp);try{await e.setLocalDescription(r),ut.log("Set localDescription:",r,`for:${this.connection.peer}`);let i={sdp:r,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata};if(this.connection.type===Pa.Data){const s=this.connection;i={...i,label:s.label,reliable:s.reliable,serialization:s.serialization}}t.socket.send({type:oi.Offer,payload:i,dst:this.connection.peer})}catch(i){i!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(ir.WebRTC,i),ut.log("Failed to setLocalDescription, ",i))}}catch(r){t.emitError(ir.WebRTC,r),ut.log("Failed to createOffer, ",r)}}async _makeAnswer(){const e=this.connection.peerConnection,t=this.connection.provider;try{const r=await e.createAnswer();ut.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(r.sdp=this.connection.options.sdpTransform(r.sdp)||r.sdp);try{await e.setLocalDescription(r),ut.log("Set localDescription:",r,`for:${this.connection.peer}`),t.socket.send({type:oi.Answer,payload:{sdp:r,type:this.connection.type,connectionId:this.connection.connectionId},dst:this.connection.peer})}catch(i){t.emitError(ir.WebRTC,i),ut.log("Failed to setLocalDescription, ",i)}}catch(r){t.emitError(ir.WebRTC,r),ut.log("Failed to create answer, ",r)}}async handleSDP(e,t){t=new RTCSessionDescription(t);const r=this.connection.peerConnection,i=this.connection.provider;ut.log("Setting remote description",t);const s=this;try{await r.setRemoteDescription(t),ut.log(`Set remoteDescription:${e} for:${this.connection.peer}`),e==="OFFER"&&await s._makeAnswer()}catch(o){i.emitError(ir.WebRTC,o),ut.log("Failed to setRemoteDescription, ",o)}}async handleCandidate(e){ut.log("handleCandidate:",e);try{await this.connection.peerConnection.addIceCandidate(e),ut.log(`Added ICE candidate for:${this.connection.peer}`)}catch(t){this.connection.provider.emitError(ir.WebRTC,t),ut.log("Failed to handleCandidate, ",t)}}_addTracksToConnection(e,t){if(ut.log(`add tracks from stream ${e.id} to peer connection`),!t.addTrack)return ut.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(r=>{t.addTrack(r,e)})}_addStreamToMediaConnection(e,t){ut.log(`add stream ${e.id} to media connection ${t.connectionId}`),t.addStream(e)}}class x5 extends OM.EventEmitter{emitError(e,t){ut.error("Error:",t),this.emit("error",new jge(`${e}`,t))}}class jge extends Error{constructor(e,t){typeof t=="string"?super(t):(super(),Object.assign(this,t)),this.type=e}}class S5 extends x5{get open(){return this._open}constructor(e,t,r){super(),this.peer=e,this.provider=t,this.options=r,this._open=!1,this.metadata=r.metadata}}var kT;const Op=class Op extends S5{get type(){return Pa.Media}get localStream(){return this._localStream}get remoteStream(){return this._remoteStream}constructor(e,t,r){super(e,t,r),this._localStream=this.options._stream,this.connectionId=this.options.connectionId||Op.ID_PREFIX+as.randomToken(),this._negotiator=new y5(this),this._localStream&&this._negotiator.startConnection({_stream:this._localStream,originator:!0})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{ut.log(`DC#${this.connectionId} dc connection success`),this.emit("willCloseOnRemote")},this.dataChannel.onclose=()=>{ut.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}addStream(e){ut.log("Receiving stream",e),this._remoteStream=e,super.emit("stream",e)}handleMessage(e){const t=e.type,r=e.payload;switch(e.type){case oi.Answer:this._negotiator.handleSDP(t,r.sdp),this._open=!0;break;case oi.Candidate:this._negotiator.handleCandidate(r.candidate);break;default:ut.warn(`Unrecognized message type:${t} from peer:${this.peer}`);break}}answer(e,t={}){if(this._localStream){ut.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,t&&t.sdpTransform&&(this.options.sdpTransform=t.sdpTransform),this._negotiator.startConnection({...this.options._payload,_stream:e});const r=this.provider._getMessages(this.connectionId);for(const i of r)this.handleMessage(i);this._open=!0}close(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,super.emit("close"))}};kT=new WeakMap,Yd(Op,kT,Op.ID_PREFIX="mc_");let jv=Op;class $ge{constructor(e){this._options=e}_buildRequest(e){const t=this._options.secure?"https":"http",{host:r,port:i,path:s,key:o}=this._options,a=new URL(`${t}://${r}:${i}${s}${o}/${e}`);return a.searchParams.set("ts",`${Date.now()}${Math.random()}`),a.searchParams.set("version",LM.version),fetch(a.href,{referrerPolicy:this._options.referrerPolicy})}async retrieveId(){try{const e=await this._buildRequest("id");if(e.status!==200)throw new Error(`Error. Status:${e.status}`);return e.text()}catch(e){ut.error("Error retrieving ID",e);let t="";throw this._options.path==="/"&&this._options.host!==as.CLOUD_HOST&&(t=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+t)}}async listAllPeers(){try{const e=await this._buildRequest("peers");if(e.status!==200){if(e.status===401){let t="";throw this._options.host===as.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+t)}throw new Error(`Error. Status:${e.status}`)}return e.json()}catch(e){throw ut.error("Error retrieving list peers",e),new Error("Could not get list peers from the server."+e)}}}var NT,IT;const Fu=class Fu extends S5{get type(){return Pa.Data}constructor(e,t,r){super(e,t,r),this.connectionId=this.options.connectionId||Fu.ID_PREFIX+_5(),this.label=this.options.label||this.connectionId,this.reliable=!!this.options.reliable,this._negotiator=new y5(this),this._negotiator.startConnection(this.options._payload||{originator:!0,reliable:this.reliable})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{ut.log(`DC#${this.connectionId} dc connection success`),this._open=!0,this.emit("open")},this.dataChannel.onmessage=t=>{ut.log(`DC#${this.connectionId} dc onmessage:`,t.data)},this.dataChannel.onclose=()=>{ut.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}close(e){if(e!=null&&e.flush){this.send({__peerData:{type:"close"}});return}this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this.dataChannel=null),this.open&&(this._open=!1,super.emit("close"))}send(e,t=!1){if(!this.open){this.emitError(lm.NotOpenYet,"Connection is not open. You should listen for the `open` event before sending messages.");return}return this._send(e,t)}async handleMessage(e){const t=e.payload;switch(e.type){case oi.Answer:await this._negotiator.handleSDP(e.type,t.sdp);break;case oi.Candidate:await this._negotiator.handleCandidate(t.candidate);break;default:ut.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}}};NT=new WeakMap,IT=new WeakMap,Yd(Fu,NT,Fu.ID_PREFIX="dc_"),Yd(Fu,IT,Fu.MAX_BUFFERED_AMOUNT=8388608);let $v=Fu;class PM extends $v{get bufferSize(){return this._bufferSize}_initializeDataChannel(e){super._initializeDataChannel(e),this.dataChannel.binaryType="arraybuffer",this.dataChannel.addEventListener("message",t=>this._handleDataMessage(t))}_bufferedSend(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)}_trySend(e){if(!this.open)return!1;if(this.dataChannel.bufferedAmount>$v.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(()=>{this._buffering=!1,this._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(t){return ut.error(`DC#:${this.connectionId} Error when sending:`,t),this._buffering=!0,this.close(),!1}return!0}_tryBuffer(){if(!this.open||this._buffer.length===0)return;const e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}close(e){if(e!=null&&e.flush){this.send({__peerData:{type:"close"}});return}this._buffer=[],this._bufferSize=0,super.close()}constructor(...e){super(...e),this._buffer=[],this._bufferSize=0,this._buffering=!1}}class tE extends PM{close(e){super.close(e),this._chunkedData={}}constructor(e,t,r){super(e,t,r),this.chunker=new g5,this.serialization=gd.Binary,this._chunkedData={}}_handleDataMessage({data:e}){const t=PB(e),r=t.__peerData;if(r){if(r.type==="close"){this.close();return}this._handleChunk(t);return}this.emit("data",t)}_handleChunk(e){const t=e.__peerData,r=this._chunkedData[t]||{data:[],count:0,total:e.total};if(r.data[e.n]=new Uint8Array(e.data),r.count++,this._chunkedData[t]=r,r.total===r.count){delete this._chunkedData[t];const i=Uge(r.data);this._handleDataMessage({data:i})}}_send(e,t){const r=DB(e);if(r instanceof Promise)return this._send_blob(r);if(!t&&r.byteLength>this.chunker.chunkedMTU){this._sendChunks(r);return}this._bufferedSend(r)}async _send_blob(e){const t=await e;if(t.byteLength>this.chunker.chunkedMTU){this._sendChunks(t);return}this._bufferedSend(t)}_sendChunks(e){const t=this.chunker.chunk(e);ut.log(`DC#${this.connectionId} Try to send ${t.length} chunks...`);for(const r of t)this.send(r,!0)}}class qge extends PM{_handleDataMessage({data:e}){super.emit("data",e)}_send(e,t){this._bufferedSend(e)}constructor(...e){super(...e),this.serialization=gd.None}}class Xge extends PM{_handleDataMessage({data:e}){const t=this.parse(this.decoder.decode(e)),r=t.__peerData;if(r&&r.type==="close"){this.close();return}this.emit("data",t)}_send(e,t){const r=this.encoder.encode(this.stringify(e));if(r.byteLength>=as.chunkedMTU){this.emitError(lm.MessageToBig,"Message too big for JSON channel");return}this._bufferedSend(r)}constructor(...e){super(...e),this.serialization=gd.JSON,this.encoder=new TextEncoder,this.decoder=new TextDecoder,this.stringify=JSON.stringify,this.parse=JSON.parse}}var OT;const Lp=class Lp extends x5{get id(){return this._id}get options(){return this._options}get open(){return this._open}get socket(){return this._socket}get connections(){const e=Object.create(null);for(const[t,r]of this._connections)e[t]=r;return e}get destroyed(){return this._destroyed}get disconnected(){return this._disconnected}constructor(e,t){super(),this._serializers={raw:qge,json:Xge,binary:tE,"binary-utf8":tE,default:tE},this._id=null,this._lastServerId=null,this._destroyed=!1,this._disconnected=!1,this._open=!1,this._connections=new Map,this._lostMessages=new Map;let r;if(e&&e.constructor==Object?t=e:e&&(r=e.toString()),t={debug:0,host:as.CLOUD_HOST,port:as.CLOUD_PORT,path:"/",key:Lp.DEFAULT_KEY,token:as.randomToken(),config:as.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin",serializers:{},...t},this._options=t,this._serializers={...this._serializers,...this.options.serializers},this._options.host==="/"&&(this._options.host=window.location.hostname),this._options.path&&(this._options.path[0]!=="/"&&(this._options.path="/"+this._options.path),this._options.path[this._options.path.length-1]!=="/"&&(this._options.path+="/")),this._options.secure===void 0&&this._options.host!==as.CLOUD_HOST?this._options.secure=as.isSecure():this._options.host==as.CLOUD_HOST&&(this._options.secure=!0),this._options.logFunction&&ut.setLogFunction(this._options.logFunction),ut.logLevel=this._options.debug||0,this._api=new $ge(t),this._socket=this._createServerConnection(),!as.supports.audioVideo&&!as.supports.data){this._delayedAbort(ir.BrowserIncompatible,"The current browser does not support WebRTC");return}if(r&&!as.validateId(r)){this._delayedAbort(ir.InvalidID,`ID "${r}" is invalid`);return}r?this._initialize(r):this._api.retrieveId().then(i=>this._initialize(i)).catch(i=>this._abort(ir.ServerError,i))}_createServerConnection(){const e=new Wge(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return e.on(Ca.Message,t=>{this._handleMessage(t)}),e.on(Ca.Error,t=>{this._abort(ir.SocketError,t)}),e.on(Ca.Disconnected,()=>{this.disconnected||(this.emitError(ir.Network,"Lost connection to server."),this.disconnect())}),e.on(Ca.Close,()=>{this.disconnected||this._abort(ir.SocketClosed,"Underlying socket is already closed.")}),e}_initialize(e){this._id=e,this.socket.start(e,this._options.token)}_handleMessage(e){const t=e.type,r=e.payload,i=e.src;switch(t){case oi.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case oi.Error:this._abort(ir.ServerError,r.msg);break;case oi.IdTaken:this._abort(ir.UnavailableID,`ID "${this.id}" is taken`);break;case oi.InvalidKey:this._abort(ir.InvalidKey,`API KEY "${this._options.key}" is invalid`);break;case oi.Leave:ut.log(`Received leave message from ${i}`),this._cleanupPeer(i),this._connections.delete(i);break;case oi.Expire:this.emitError(ir.PeerUnavailable,`Could not connect to peer ${i}`);break;case oi.Offer:{const s=r.connectionId;let o=this.getConnection(i,s);if(o&&(o.close(),ut.warn(`Offer received for existing Connection ID:${s}`)),r.type===Pa.Media){const c=new jv(i,this,{connectionId:s,_payload:r,metadata:r.metadata});o=c,this._addConnection(i,o),this.emit("call",c)}else if(r.type===Pa.Data){const c=new this._serializers[r.serialization](i,this,{connectionId:s,_payload:r,metadata:r.metadata,label:r.label,serialization:r.serialization,reliable:r.reliable});o=c,this._addConnection(i,o),this.emit("connection",c)}else{ut.warn(`Received malformed connection type:${r.type}`);return}const a=this._getMessages(s);for(const c of a)o.handleMessage(c);break}default:{if(!r){ut.warn(`You received a malformed message from ${i} of type ${t}`);return}const s=r.connectionId,o=this.getConnection(i,s);o&&o.peerConnection?o.handleMessage(e):s?this._storeMessage(s,e):ut.warn("You received an unrecognized message:",e);break}}}_storeMessage(e,t){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(t)}_getMessages(e){const t=this._lostMessages.get(e);return t?(this._lostMessages.delete(e),t):[]}connect(e,t={}){if(t={serialization:"default",...t},this.disconnected){ut.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(ir.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}const r=new this._serializers[t.serialization](e,this,t);return this._addConnection(e,r),r}call(e,t,r={}){if(this.disconnected){ut.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(ir.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!t){ut.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}const i=new jv(e,this,{...r,_stream:t});return this._addConnection(e,i),i}_addConnection(e,t){ut.log(`add connection ${t.type}:${t.connectionId} to peerId:${e}`),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(t)}_removeConnection(e){const t=this._connections.get(e.peer);if(t){const r=t.indexOf(e);r!==-1&&t.splice(r,1)}this._lostMessages.delete(e.connectionId)}getConnection(e,t){const r=this._connections.get(e);if(!r)return null;for(const i of r)if(i.connectionId===t)return i;return null}_delayedAbort(e,t){setTimeout(()=>{this._abort(e,t)},0)}_abort(e,t){ut.error("Aborting!"),this.emitError(e,t),this._lastServerId?this.disconnect():this.destroy()}destroy(){this.destroyed||(ut.log(`Destroy peer with ID:${this.id}`),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))}_cleanup(){for(const e of this._connections.keys())this._cleanupPeer(e),this._connections.delete(e);this.socket.removeAllListeners()}_cleanupPeer(e){const t=this._connections.get(e);if(t)for(const r of t)r.close()}disconnect(){if(this.disconnected)return;const e=this.id;ut.log(`Disconnect peer with ID:${e}`),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}reconnect(){if(this.disconnected&&!this.destroyed)ut.log(`Attempting reconnection to server with ID ${this._lastServerId}`),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)ut.error("In a hurry? We're still trying to make the initial connection!");else throw new Error(`Peer ${this.id} cannot reconnect because it is not disconnected from the server!`)}}listAllPeers(e=t=>{}){this._api.listAllPeers().then(t=>e(t)).catch(t=>this._abort(ir.ServerError,t))}};OT=new WeakMap,Yd(Lp,OT,Lp.DEFAULT_KEY="peerjs");let RT=Lp;var E5=RT;let Ln;function Kge(){Ln==null||Ln.destroy(),Ln=void 0}window.addEventListener("beforeunload",Kge);function b5(n,e){n.on("open",()=>{const{forward:t,disconnect:r}=QL(i=>n.send(i));n.on("close",()=>{r(),un(hs.name(),`remote ${n.peer} disconnected`)}),n.on("data",t),e==null||e()}),n.on("error",t=>{const r=(Ln==null?void 0:Ln.id)??"";An(hs.name(),`${r}-${n.peer}`,t.message)})}function Yge(n){un(hs.name(),"connecting..."),Ln=new E5(n),Ln.on("open",()=>{Z(Ln)&&(Ln.on("connection",b5),Ln.on("close",()=>un(hs.name(),"closed")),$L(hs.name(),n))}),Ln.on("error",e=>An(hs.name(),(Ln==null?void 0:Ln.id)??"",e.message))}function Zge(n,e){un(hs.name(),`connecting to ${e}`),Ln=new E5(n),Ln.on("open",()=>{if(Z(Ln)){Ln.on("close",()=>un(hs.name(),"closed"));const t=Ln.connect(e,{reliable:!0});b5(t,()=>{un(hs.name(),"connected"),U9(hs.name(),n)})}}),Ln.on("error",t=>An(hs.name(),(Ln==null?void 0:Ln.id)??"",t.message))}const hs=mh("peer",["second"],n=>{switch(n.target){case"create":n.player===Xi()&&(n.data?Zge(n.player,n.data):Yge(n.player));break;case"joincode":{n.player===Xi()&&_a("peer:joincode",async()=>{if(Z(n.player))if(!Z(Ln))jL(hs.name(),"",n.player);else{const e=`${location.origin}/join/#${Ln.id}`,t=await eb(e);rb(hs.name(),t,t),un(hs.name(),"ready to join")}});break}}}),Jge=mh("gadgetclient",[],n=>{const{desync:e}=kc.getState();switch(n.target){case"reset":n.player===Xi()&&kc.setState({desync:!1,gadget:n.data});break;case"patch":n.player===Xi()&&!e&&kc.setState(t=>{try{const{newDocument:r}=iy(t.gadget,n.data,!0,!1);return{...t,gadget:r}}catch(r){r instanceof ew&&(kc.setState({desync:!0}),Jge.reply(n,"desync",void 0,n.player))}return t});break}});mh("tape",[],n=>{const{layout:e,terminal:t,editor:r}=cs.getState();function i(o){let a=[[gr(),o.target,o.sender,...o.data],...t.logs];a.length>HN&&(a=a.slice(0,HN)),cs.setState(c=>({terminal:{...c.terminal,logs:a}}))}function s(o){let c=e+(o?1:-1);if(c<0&&(c+=Bi.MAX),c>=Bi.MAX&&(c-=Bi.MAX),!r.open)switch(c){case Bi.SPLIT_Y:case Bi.SPLIT_Y_ALT:c=Bi.TOP;break}cs.setState({layout:c})}switch(n.target){case"info":t.level>=N_.INFO&&i(n);break;case"debug":t.level>=N_.DEBUG&&i(n);break;case"error":t.level>N_.OFF&&i(n);break;case"crash":cs.setState(o=>({layout:Bi.FULL,terminal:{...o.terminal,open:!0}}));break;case"terminal:open":cs.setState(o=>({terminal:{...o.terminal,open:!0}}));break;case"terminal:close":cs.setState(o=>({terminal:{...o.terminal,open:!1}}));break;case"terminal:inclayout":g9(n.data)&&s(n.data);break;case"editor:open":if(cn(n.data)&&Z(n.player)){const{player:o}=n,[a,c,l,u]=n.data??["","",""];cs.setState(h=>({terminal:{...h.terminal,open:!0},editor:{open:!0,player:o,book:a,page:c,type:l,title:u}}))}break;case"editor:close":cs.setState(o=>({editor:{...o.editor,open:!1}}));break}});JT({OrthographicCamera:ey});function Qge(){const n=Ma(d=>d.viewport),e=ke.useRef(null),{width:t,height:r}=n.getCurrentViewport(),i=WA(_le);i.minFilter=Er,i.magFilter=Er;const[s]=ke.useState(()=>new ile);ke.useEffect(()=>{if(!ole)return;document.body.appendChild(s.dom),s.showPanel(0),s.dom.style.cssText="position:fixed;bottom:0;left:0;";const d=Oj(()=>s.begin()),m=Lj(()=>s.end());return()=>{document.body.removeChild(s.dom),d(),m()}},[s]);const[o,a]=ke.useState();ke.useEffect(()=>{nle({benchmarksURL:"/benchmarks-min"}).then(a).catch(d=>An("gpu","detect",d))},[]);const c=!cle&&o&&o.tier>2&&!o.isMobile,l=Ma(({set:d})=>d),u=Ma(({size:d})=>d),h=Ma(({camera:d})=>d);return ke.useLayoutEffect(()=>{var d;(d=e.current)==null||d.updateProjectionMatrix()}),ke.useLayoutEffect(()=>{const d=h;return l(()=>({camera:e.current})),()=>l(()=>({camera:d}))},[l,h,e]),ve.jsxs(ve.Fragment,{children:[ve.jsx("orthographicCamera",{ref:e,left:u.width/-2,right:u.width/2,top:u.height/2,bottom:u.height/-2,near:1,far:2e3,position:[0,0,1e3]}),ve.jsx("group",{"scale-x":-1,"rotation-z":Math.PI,children:ve.jsx("group",{position:[t*-.5,r*-.5,0],children:ve.jsxs($m,{children:[ve.jsx(Qme,{}),ve.jsx(wge,{})]})})}),c&&ve.jsx(Kce,{children:ve.jsx(gle,{splat:i,viewheight:r})})]})}JT({BufferGeometry:jo,Group:mp,Mesh:Io,MeshBasicMaterial:$T,OrthographicCamera:ey,PlaneGeometry:pm,Points:tj});document.addEventListener("keydown",()=>{Cd()});window.addEventListener("touchstart",()=>{Cd()});window.addEventListener("click",()=>{Cd()});window.addEventListener("dragover",n=>{n.preventDefault()});window.addEventListener("contextmenu",n=>{Cd(),n.preventDefault()});window.addEventListener("paste",n=>{var t;if(!((t=n.clipboardData)!=null&&t.files.length))return;Cd(),n.preventDefault(),[...n.clipboardData.files].forEach(r=>QE("loadfile",r,Xi()))});window.addEventListener("drop",n=>{var e,t;Cd(),n.preventDefault(),(e=n.dataTransfer)!=null&&e.items?[...n.dataTransfer.items].forEach(i=>{if(i.kind==="file"){const s=i.getAsFile();Z(s)&&QE("loadfile",s,Xi())}}):[...((t=n.dataTransfer)==null?void 0:t.files)??[]].forEach(i=>QE("loadfile",i,Xi()))});function e0e(){return ve.jsx(Qge,{})}const SO=new xe,EO=new xe,bO=n=>({...Hj(n),filter:e=>{const t=e.filter(o=>!(!o.object.visible||(o.object.userData.clippingPlanes??[]).some(c=>(c.projectPoint(o.point,SO),EO.subVectors(o.point,SO).normalize().round(),c.normal.equals(EO)===!1)))),r=t.findIndex(o=>o.object.userData.blocking),i=r===-1?t:t.slice(0,r+1);let s="default";return i.some(o=>o.object.userData.cursor?(s=o.object.userData.cursor,!0):!1),document.querySelectorAll("html, body").forEach(o=>{o.style.cursor=s}),i}}),TO=document.querySelector("canvas");if(Z(TO)){const n=Bj(TO),e={dpr:1,flat:!0,linear:!0,shadows:!1,gl:{alpha:!1,stencil:!1,antialias:!1,preserveDrawingBuffer:!0}};n.configure({...e,events:bO,onCreated({gl:r}){r.localClippingEnabled=!0}});const t=Wj((r,i)=>{n.configure({...e,events:bO,size:{width:r,height:i,top:0,left:0},onCreated({gl:s}){s.localClippingEnabled=!0}})},256);window.addEventListener("resize",()=>{t(N2(window.innerWidth),N2(window.innerHeight))}),n.render(ve.jsx(e0e,{}))}});export default t0e(); diff --git a/assets/index-VzaR3_tn.js b/assets/index-VzaR3_tn.js deleted file mode 100644 index 080715bb..00000000 --- a/assets/index-VzaR3_tn.js +++ /dev/null @@ -1,4904 +0,0 @@ -var KB=Object.defineProperty;var YB=(t,e,n)=>e in t?KB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var ZB=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var vt=(t,e,n)=>YB(t,typeof e!="symbol"?e+"":e,n);var kme=ZB((Os,Ls)=>{(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(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"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(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 r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var To=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function JB(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}),n}var YI={exports:{}},Nv={},ZI={exports:{}},Jt={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Yp=Symbol.for("react.element"),QB=Symbol.for("react.portal"),e5=Symbol.for("react.fragment"),t5=Symbol.for("react.strict_mode"),n5=Symbol.for("react.profiler"),r5=Symbol.for("react.provider"),i5=Symbol.for("react.context"),s5=Symbol.for("react.forward_ref"),o5=Symbol.for("react.suspense"),a5=Symbol.for("react.memo"),c5=Symbol.for("react.lazy"),WC=Symbol.iterator;function l5(t){return t===null||typeof t!="object"?null:(t=WC&&t[WC]||t["@@iterator"],typeof t=="function"?t:null)}var JI={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},QI=Object.assign,eO={};function cd(t,e,n){this.props=t,this.context=e,this.refs=eO,this.updater=n||JI}cd.prototype.isReactComponent={};cd.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};cd.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function tO(){}tO.prototype=cd.prototype;function ub(t,e,n){this.props=t,this.context=e,this.refs=eO,this.updater=n||JI}var hb=ub.prototype=new tO;hb.constructor=ub;QI(hb,cd.prototype);hb.isPureReactComponent=!0;var jC=Array.isArray,nO=Object.prototype.hasOwnProperty,fb={current:null},rO={key:!0,ref:!0,__self:!0,__source:!0};function iO(t,e,n){var r,i={},s=null,o=null;if(e!=null)for(r in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(s=""+e.key),e)nO.call(e,r)&&!rO.hasOwnProperty(r)&&(i[r]=e[r]);var a=arguments.length-2;if(a===1)i.children=n;else if(1>8&255]+vi[t>>16&255]+vi[t>>24&255]+"-"+vi[e&255]+vi[e>>8&255]+"-"+vi[e>>16&15|64]+vi[e>>24&255]+"-"+vi[n&63|128]+vi[n>>8&255]+"-"+vi[n>>16&255]+vi[n>>24&255]+vi[r&255]+vi[r>>8&255]+vi[r>>16&255]+vi[r>>24&255]).toLowerCase()}function Di(t,e,n){return Math.max(e,Math.min(n,t))}function xb(t,e){return(t%e+e)%e}function sz(t,e,n,r,i){return r+(t-e)*(i-r)/(n-e)}function oz(t,e,n){return t!==e?(n-t)/(e-t):0}function gp(t,e,n){return(1-n)*t+n*e}function az(t,e,n,r){return gp(t,e,1-Math.exp(-n*r))}function cz(t,e=1){return e-Math.abs(xb(t,e*2)-e)}function lz(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*(3-2*t))}function uz(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*t*(t*(t*6-15)+10))}function hz(t,e){return t+Math.floor(Math.random()*(e-t+1))}function fz(t,e){return t+Math.random()*(e-t)}function dz(t){return t*(.5-Math.random())}function pz(t){t!==void 0&&(eR=t);let e=eR+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function mz(t){return t*mp}function gz(t){return t*bp}function _z(t){return(t&t-1)===0&&t!==0}function vz(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function yz(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function xz(t,e,n,r,i){const s=Math.cos,o=Math.sin,a=s(n/2),c=o(n/2),l=s((e+r)/2),u=o((e+r)/2),h=s((e-r)/2),p=o((e-r)/2),m=s((r-e)/2),g=o((r-e)/2);switch(i){case"XYX":t.set(a*u,c*h,c*p,a*l);break;case"YZY":t.set(c*p,a*u,c*h,a*l);break;case"ZXZ":t.set(c*h,c*p,a*u,a*l);break;case"XZX":t.set(a*u,c*g,c*m,a*l);break;case"YXY":t.set(c*m,a*u,c*g,a*l);break;case"ZYZ":t.set(c*g,c*m,a*u,a*l);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function sf(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function ki(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(t*4294967295);case Uint16Array:return Math.round(t*65535);case Uint8Array:return Math.round(t*255);case Int32Array:return Math.round(t*2147483647);case Int16Array:return Math.round(t*32767);case Int8Array:return Math.round(t*127);default:throw new Error("Invalid component type.")}}const Sz={DEG2RAD:mp,RAD2DEG:bp,generateUUID:ud,clamp:Di,euclideanModulo:xb,mapLinear:sz,inverseLerp:oz,lerp:gp,damp:az,pingpong:cz,smoothstep:lz,smootherstep:uz,randInt:hz,randFloat:fz,randFloatSpread:dz,seededRandom:pz,degToRad:mz,radToDeg:gz,isPowerOfTwo:_z,ceilPowerOfTwo:vz,floorPowerOfTwo:yz,setQuaternionFromProperEuler:xz,normalize:ki,denormalize:sf};class St{constructor(e=0,n=0){St.prototype.isVector2=!0,this.x=e,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,n){return this.x=e,this.y=n,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const n=this.x,r=this.y,i=e.elements;return this.x=i[0]*n+i[3]*r+i[6],this.y=i[1]*n+i[4]*r+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(Di(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y;return n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this}rotateAround(e,n){const r=Math.cos(n),i=Math.sin(n),s=this.x-e.x,o=this.y-e.y;return this.x=s*r-o*i+e.x,this.y=s*i+o*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Dt{constructor(e,n,r,i,s,o,a,c,l){Dt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,r,i,s,o,a,c,l)}set(e,n,r,i,s,o,a,c,l){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=n,u[4]=s,u[5]=c,u[6]=r,u[7]=o,u[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],this}extractBasis(e,n,r){return e.setFromMatrix3Column(this,0),n.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const n=e.elements;return this.set(n[0],n[4],n[8],n[1],n[5],n[9],n[2],n[6],n[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,i=n.elements,s=this.elements,o=r[0],a=r[3],c=r[6],l=r[1],u=r[4],h=r[7],p=r[2],m=r[5],g=r[8],v=i[0],y=i[3],_=i[6],S=i[1],E=i[4],b=i[7],N=i[2],R=i[5],M=i[8];return s[0]=o*v+a*S+c*N,s[3]=o*y+a*E+c*R,s[6]=o*_+a*b+c*M,s[1]=l*v+u*S+h*N,s[4]=l*y+u*E+h*R,s[7]=l*_+u*b+h*M,s[2]=p*v+m*S+g*N,s[5]=p*y+m*E+g*R,s[8]=p*_+m*b+g*M,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[3]*=e,n[6]*=e,n[1]*=e,n[4]*=e,n[7]*=e,n[2]*=e,n[5]*=e,n[8]*=e,this}determinant(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],u=e[8];return n*o*u-n*a*l-r*s*u+r*a*c+i*s*l-i*o*c}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],u=e[8],h=u*o-a*l,p=a*c-u*s,m=l*s-o*c,g=n*h+r*p+i*m;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return e[0]=h*v,e[1]=(i*l-u*r)*v,e[2]=(a*r-i*o)*v,e[3]=p*v,e[4]=(u*n-i*c)*v,e[5]=(i*s-a*n)*v,e[6]=m*v,e[7]=(r*c-l*n)*v,e[8]=(o*n-r*s)*v,this}transpose(){let e;const n=this.elements;return e=n[1],n[1]=n[3],n[3]=e,e=n[2],n[2]=n[6],n[6]=e,e=n[5],n[5]=n[7],n[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const n=this.elements;return e[0]=n[0],e[1]=n[3],e[2]=n[6],e[3]=n[1],e[4]=n[4],e[5]=n[7],e[6]=n[2],e[7]=n[5],e[8]=n[8],this}setUvTransform(e,n,r,i,s,o,a){const c=Math.cos(s),l=Math.sin(s);return this.set(r*c,r*l,-r*(c*o+l*a)+o+e,-i*l,i*c,-i*(-l*o+c*a)+a+n,0,0,1),this}scale(e,n){return this.premultiply(f1.makeScale(e,n)),this}rotate(e){return this.premultiply(f1.makeRotation(-e)),this}translate(e,n){return this.premultiply(f1.makeTranslation(e,n)),this}makeTranslation(e,n){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,n,0,0,1),this}makeRotation(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,r,n,0,0,0,1),this}makeScale(e,n){return this.set(e,0,0,0,n,0,0,0,1),this}equals(e){const n=this.elements,r=e.elements;for(let i=0;i<9;i++)if(n[i]!==r[i])return!1;return!0}fromArray(e,n=0){for(let r=0;r<9;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const f1=new Dt;function EO(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function Tp(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function Ez(){const t=Tp("canvas");return t.style.display="block",t}const tR={};function np(t){t in tR||(tR[t]=!0,console.warn(t))}function wz(t,e,n){return new Promise(function(r,i){function s(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:i();break;case t.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:r()}}setTimeout(s,n)})}function bz(t){const e=t.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function Tz(t){const e=t.elements;e[11]===-1?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=-e[14]+1)}const hn={enabled:!0,workingColorSpace:jl,spaces:{},convert:function(t,e,n){return this.enabled===!1||e===n||!e||!n||(this.spaces[e].transfer===Tn&&(t.r=Ec(t.r),t.g=Ec(t.g),t.b=Ec(t.b)),this.spaces[e].primaries!==this.spaces[n].primaries&&(t.applyMatrix3(this.spaces[e].toXYZ),t.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===Tn&&(t.r=wf(t.r),t.g=wf(t.g),t.b=wf(t.b))),t},fromWorkingColorSpace:function(t,e){return this.convert(t,this.workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this.workingColorSpace)},getPrimaries:function(t){return this.spaces[t].primaries},getTransfer:function(t){return t===pa?Lv:this.spaces[t].transfer},getLuminanceCoefficients:function(t,e=this.workingColorSpace){return t.fromArray(this.spaces[e].luminanceCoefficients)},define:function(t){Object.assign(this.spaces,t)},_getMatrix:function(t,e,n){return t.copy(this.spaces[e].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(t){return this.spaces[t].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(t=this.workingColorSpace){return this.spaces[t].workingColorSpaceConfig.unpackColorSpace}};function Ec(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function wf(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}const nR=[.64,.33,.3,.6,.15,.06],rR=[.2126,.7152,.0722],iR=[.3127,.329],sR=new Dt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),oR=new Dt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);hn.define({[jl]:{primaries:nR,whitePoint:iR,transfer:Lv,toXYZ:sR,fromXYZ:oR,luminanceCoefficients:rR,workingColorSpaceConfig:{unpackColorSpace:pr},outputColorSpaceConfig:{drawingBufferColorSpace:pr}},[pr]:{primaries:nR,whitePoint:iR,transfer:Tn,toXYZ:sR,fromXYZ:oR,luminanceCoefficients:rR,outputColorSpaceConfig:{drawingBufferColorSpace:pr}}});let Uh;class Az{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Uh===void 0&&(Uh=Tp("canvas")),Uh.width=e.width,Uh.height=e.height;const r=Uh.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),n=Uh}return n.width>2048||n.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),n.toDataURL("image/jpeg",.6)):n.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const n=Tp("canvas");n.width=e.width,n.height=e.height;const r=n.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const i=r.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o0&&(r.userData=this.userData),n||(e.textures[this.uuid]=r),r}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==lO)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case tE:e.x=e.x-Math.floor(e.x);break;case Ou:e.x=e.x<0?0:1;break;case nE:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case tE:e.y=e.y-Math.floor(e.y);break;case Ou:e.y=e.y<0?0:1;break;case nE:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}or.DEFAULT_IMAGE=null;or.DEFAULT_MAPPING=lO;or.DEFAULT_ANISOTROPY=1;class gr{constructor(e=0,n=0,r=0,i=1){gr.prototype.isVector4=!0,this.x=e,this.y=n,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,n,r,i){return this.x=e,this.y=n,this.z=r,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;case 3:this.w=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this.w=e.w+n.w,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this.w+=e.w*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this.w=e.w-n.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const n=this.x,r=this.y,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*n+o[4]*r+o[8]*i+o[12]*s,this.y=o[1]*n+o[5]*r+o[9]*i+o[13]*s,this.z=o[2]*n+o[6]*r+o[10]*i+o[14]*s,this.w=o[3]*n+o[7]*r+o[11]*i+o[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const n=Math.sqrt(1-e.w*e.w);return n<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/n,this.y=e.y/n,this.z=e.z/n),this}setAxisAngleFromRotationMatrix(e){let n,r,i,s;const c=e.elements,l=c[0],u=c[4],h=c[8],p=c[1],m=c[5],g=c[9],v=c[2],y=c[6],_=c[10];if(Math.abs(u-p)<.01&&Math.abs(h-v)<.01&&Math.abs(g-y)<.01){if(Math.abs(u+p)<.1&&Math.abs(h+v)<.1&&Math.abs(g+y)<.1&&Math.abs(l+m+_-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const E=(l+1)/2,b=(m+1)/2,N=(_+1)/2,R=(u+p)/4,M=(h+v)/4,O=(g+y)/4;return E>b&&E>N?E<.01?(r=0,i=.707106781,s=.707106781):(r=Math.sqrt(E),i=R/r,s=M/r):b>N?b<.01?(r=.707106781,i=0,s=.707106781):(i=Math.sqrt(b),r=R/i,s=O/i):N<.01?(r=.707106781,i=.707106781,s=0):(s=Math.sqrt(N),r=M/s,i=O/s),this.set(r,i,s,n),this}let S=Math.sqrt((y-g)*(y-g)+(h-v)*(h-v)+(p-u)*(p-u));return Math.abs(S)<.001&&(S=1),this.x=(y-g)/S,this.y=(h-v)/S,this.z=(p-u)/S,this.w=Math.acos((l+m+_-1)/2),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this.w=n[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this.z=Math.max(e.z,Math.min(n.z,this.z)),this.w=Math.max(e.w,Math.min(n.w,this.w)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this.z=Math.max(e,Math.min(n,this.z)),this.w=Math.max(e,Math.min(n,this.w)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this.w+=(e.w-this.w)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this.w=e.w+(n.w-e.w)*r,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this.w=e[n+3],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e[n+3]=this.w,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this.w=e.getW(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Rz extends zc{constructor(e=1,n=1,r={}){super(),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=1,this.scissor=new gr(0,0,e,n),this.scissorTest=!1,this.viewport=new gr(0,0,e,n);const i={width:e,height:n,depth:1};r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:is,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},r);const s=new or(i,r.mapping,r.wrapS,r.wrapT,r.magFilter,r.minFilter,r.format,r.type,r.anisotropy,r.colorSpace);s.flipY=!1,s.generateMipmaps=r.generateMipmaps,s.internalFormat=r.internalFormat,this.textures=[];const o=r.count;for(let a=0;a=0?1:-1,E=1-_*_;if(E>Number.EPSILON){const N=Math.sqrt(E),R=Math.atan2(N,_*S);y=Math.sin(y*R)/N,a=Math.sin(a*R)/N}const b=a*S;if(c=c*y+p*b,l=l*y+m*b,u=u*y+g*b,h=h*y+v*b,y===1-a){const N=1/Math.sqrt(c*c+l*l+u*u+h*h);c*=N,l*=N,u*=N,h*=N}}e[n]=c,e[n+1]=l,e[n+2]=u,e[n+3]=h}static multiplyQuaternionsFlat(e,n,r,i,s,o){const a=r[i],c=r[i+1],l=r[i+2],u=r[i+3],h=s[o],p=s[o+1],m=s[o+2],g=s[o+3];return e[n]=a*g+u*h+c*m-l*p,e[n+1]=c*g+u*p+l*h-a*m,e[n+2]=l*g+u*m+a*p-c*h,e[n+3]=u*g-a*h-c*p-l*m,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,n,r,i){return this._x=e,this._y=n,this._z=r,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,n=!0){const r=e._x,i=e._y,s=e._z,o=e._order,a=Math.cos,c=Math.sin,l=a(r/2),u=a(i/2),h=a(s/2),p=c(r/2),m=c(i/2),g=c(s/2);switch(o){case"XYZ":this._x=p*u*h+l*m*g,this._y=l*m*h-p*u*g,this._z=l*u*g+p*m*h,this._w=l*u*h-p*m*g;break;case"YXZ":this._x=p*u*h+l*m*g,this._y=l*m*h-p*u*g,this._z=l*u*g-p*m*h,this._w=l*u*h+p*m*g;break;case"ZXY":this._x=p*u*h-l*m*g,this._y=l*m*h+p*u*g,this._z=l*u*g+p*m*h,this._w=l*u*h-p*m*g;break;case"ZYX":this._x=p*u*h-l*m*g,this._y=l*m*h+p*u*g,this._z=l*u*g-p*m*h,this._w=l*u*h+p*m*g;break;case"YZX":this._x=p*u*h+l*m*g,this._y=l*m*h+p*u*g,this._z=l*u*g-p*m*h,this._w=l*u*h-p*m*g;break;case"XZY":this._x=p*u*h-l*m*g,this._y=l*m*h-p*u*g,this._z=l*u*g+p*m*h,this._w=l*u*h+p*m*g;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return n===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const r=n/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,r=n[0],i=n[4],s=n[8],o=n[1],a=n[5],c=n[9],l=n[2],u=n[6],h=n[10],p=r+a+h;if(p>0){const m=.5/Math.sqrt(p+1);this._w=.25/m,this._x=(u-c)*m,this._y=(s-l)*m,this._z=(o-i)*m}else if(r>a&&r>h){const m=2*Math.sqrt(1+r-a-h);this._w=(u-c)/m,this._x=.25*m,this._y=(i+o)/m,this._z=(s+l)/m}else if(a>h){const m=2*Math.sqrt(1+a-r-h);this._w=(s-l)/m,this._x=(i+o)/m,this._y=.25*m,this._z=(c+u)/m}else{const m=2*Math.sqrt(1+h-r-a);this._w=(o-i)/m,this._x=(s+l)/m,this._y=(c+u)/m,this._z=.25*m}return this._onChangeCallback(),this}setFromUnitVectors(e,n){let r=e.dot(n)+1;return rMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*n.z-e.z*n.y,this._y=e.z*n.x-e.x*n.z,this._z=e.x*n.y-e.y*n.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Di(this.dot(e),-1,1)))}rotateTowards(e,n){const r=this.angleTo(e);if(r===0)return this;const i=Math.min(1,n/r);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,n){const r=e._x,i=e._y,s=e._z,o=e._w,a=n._x,c=n._y,l=n._z,u=n._w;return this._x=r*u+o*a+i*l-s*c,this._y=i*u+o*c+s*a-r*l,this._z=s*u+o*l+r*c-i*a,this._w=o*u-r*a-i*c-s*l,this._onChangeCallback(),this}slerp(e,n){if(n===0)return this;if(n===1)return this.copy(e);const r=this._x,i=this._y,s=this._z,o=this._w;let a=o*e._w+r*e._x+i*e._y+s*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=o,this._x=r,this._y=i,this._z=s,this;const c=1-a*a;if(c<=Number.EPSILON){const m=1-n;return this._w=m*o+n*this._w,this._x=m*r+n*this._x,this._y=m*i+n*this._y,this._z=m*s+n*this._z,this.normalize(),this}const l=Math.sqrt(c),u=Math.atan2(l,a),h=Math.sin((1-n)*u)/l,p=Math.sin(n*u)/l;return this._w=o*h+this._w*p,this._x=r*h+this._x*p,this._y=i*h+this._y*p,this._z=s*h+this._z*p,this._onChangeCallback(),this}slerpQuaternions(e,n,r){return this.copy(e).slerp(n,r)}random(){const e=2*Math.PI*Math.random(),n=2*Math.PI*Math.random(),r=Math.random(),i=Math.sqrt(1-r),s=Math.sqrt(r);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(n),s*Math.cos(n))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,n=0){return this._x=e[n],this._y=e[n+1],this._z=e[n+2],this._w=e[n+3],this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._w,e}fromBufferAttribute(e,n){return this._x=e.getX(n),this._y=e.getY(n),this._z=e.getZ(n),this._w=e.getW(n),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class xe{constructor(e=0,n=0,r=0){xe.prototype.isVector3=!0,this.x=e,this.y=n,this.z=r}set(e,n,r){return r===void 0&&(r=this.z),this.x=e,this.y=n,this.z=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,n){return this.x=e.x*n.x,this.y=e.y*n.y,this.z=e.z*n.z,this}applyEuler(e){return this.applyQuaternion(aR.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(aR.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[3]*r+s[6]*i,this.y=s[1]*n+s[4]*r+s[7]*i,this.z=s[2]*n+s[5]*r+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*n+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*n+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*n+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*n+s[6]*r+s[10]*i+s[14])*o,this}applyQuaternion(e){const n=this.x,r=this.y,i=this.z,s=e.x,o=e.y,a=e.z,c=e.w,l=2*(o*i-a*r),u=2*(a*n-s*i),h=2*(s*r-o*n);return this.x=n+c*l+o*h-a*u,this.y=r+c*u+a*l-s*h,this.z=i+c*h+s*u-o*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const n=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[4]*r+s[8]*i,this.y=s[1]*n+s[5]*r+s[9]*i,this.z=s[2]*n+s[6]*r+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this.z=Math.max(e.z,Math.min(n.z,this.z)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this.z=Math.max(e,Math.min(n,this.z)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,n){const r=e.x,i=e.y,s=e.z,o=n.x,a=n.y,c=n.z;return this.x=i*c-s*a,this.y=s*o-r*c,this.z=r*a-i*o,this}projectOnVector(e){const n=e.lengthSq();if(n===0)return this.set(0,0,0);const r=e.dot(this)/n;return this.copy(e).multiplyScalar(r)}projectOnPlane(e){return p1.copy(this).projectOnVector(e),this.sub(p1)}reflect(e){return this.sub(p1.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(Di(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y,i=this.z-e.z;return n*n+r*r+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,n,r){const i=Math.sin(n)*e;return this.x=i*Math.sin(r),this.y=Math.cos(n)*e,this.z=i*Math.cos(r),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,n,r){return this.x=e*Math.sin(n),this.y=r,this.z=e*Math.cos(n),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this}setFromMatrixScale(e){const n=this.setFromMatrixColumn(e,0).length(),r=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=r,this.z=i,this}setFromMatrixColumn(e,n){return this.fromArray(e.elements,n*4)}setFromMatrix3Column(e,n){return this.fromArray(e.elements,n*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,n=Math.random()*2-1,r=Math.sqrt(1-n*n);return this.x=r*Math.cos(e),this.y=n,this.z=r*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const p1=new xe,aR=new Zp;class Jp{constructor(e=new xe(1/0,1/0,1/0),n=new xe(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=n}set(e,n){return this.min.copy(e),this.max.copy(n),this}setFromArray(e){this.makeEmpty();for(let n=0,r=e.length;n=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,n){return n.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,vo),vo.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let n,r;return e.normal.x>0?(n=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(n=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(n+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(n+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(n+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(n+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),n<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Vd),Kg.subVectors(this.max,Vd),Fh.subVectors(e.a,Vd),Bh.subVectors(e.b,Vd),zh.subVectors(e.c,Vd),hl.subVectors(Bh,Fh),fl.subVectors(zh,Bh),lu.subVectors(Fh,zh);let n=[0,-hl.z,hl.y,0,-fl.z,fl.y,0,-lu.z,lu.y,hl.z,0,-hl.x,fl.z,0,-fl.x,lu.z,0,-lu.x,-hl.y,hl.x,0,-fl.y,fl.x,0,-lu.y,lu.x,0];return!m1(n,Fh,Bh,zh,Kg)||(n=[1,0,0,0,1,0,0,0,1],!m1(n,Fh,Bh,zh,Kg))?!1:(Yg.crossVectors(hl,fl),n=[Yg.x,Yg.y,Yg.z],m1(n,Fh,Bh,zh,Kg))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,vo).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(vo).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Qa[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Qa[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Qa[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Qa[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Qa[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Qa[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Qa[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Qa[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Qa),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Qa=[new xe,new xe,new xe,new xe,new xe,new xe,new xe,new xe],vo=new xe,Xg=new Jp,Fh=new xe,Bh=new xe,zh=new xe,hl=new xe,fl=new xe,lu=new xe,Vd=new xe,Kg=new xe,Yg=new xe,uu=new xe;function m1(t,e,n,r,i){for(let s=0,o=t.length-3;s<=o;s+=3){uu.fromArray(t,s);const a=i.x*Math.abs(uu.x)+i.y*Math.abs(uu.y)+i.z*Math.abs(uu.z),c=e.dot(uu),l=n.dot(uu),u=r.dot(uu);if(Math.max(-Math.max(c,l,u),Math.min(c,l,u))>a)return!1}return!0}const kz=new Jp,Hd=new xe,g1=new xe;class Pv{constructor(e=new xe,n=-1){this.isSphere=!0,this.center=e,this.radius=n}set(e,n){return this.center.copy(e),this.radius=n,this}setFromPoints(e,n){const r=this.center;n!==void 0?r.copy(n):kz.setFromPoints(e).getCenter(r);let i=0;for(let s=0,o=e.length;sthis.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Hd.subVectors(e,this.center);const n=Hd.lengthSq();if(n>this.radius*this.radius){const r=Math.sqrt(n),i=(r-this.radius)*.5;this.center.addScaledVector(Hd,i/r),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(g1.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Hd.copy(e.center).add(g1)),this.expandByPoint(Hd.copy(e.center).sub(g1))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const ec=new xe,_1=new xe,Zg=new xe,dl=new xe,v1=new xe,Jg=new xe,y1=new xe;class Sb{constructor(e=new xe,n=new xe(0,0,-1)){this.origin=e,this.direction=n}set(e,n){return this.origin.copy(e),this.direction.copy(n),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,n){return n.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,ec)),this}closestPointToPoint(e,n){n.subVectors(e,this.origin);const r=n.dot(this.direction);return r<0?n.copy(this.origin):n.copy(this.origin).addScaledVector(this.direction,r)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const n=ec.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(ec.copy(this.origin).addScaledVector(this.direction,n),ec.distanceToSquared(e))}distanceSqToSegment(e,n,r,i){_1.copy(e).add(n).multiplyScalar(.5),Zg.copy(n).sub(e).normalize(),dl.copy(this.origin).sub(_1);const s=e.distanceTo(n)*.5,o=-this.direction.dot(Zg),a=dl.dot(this.direction),c=-dl.dot(Zg),l=dl.lengthSq(),u=Math.abs(1-o*o);let h,p,m,g;if(u>0)if(h=o*c-a,p=o*a-c,g=s*u,h>=0)if(p>=-g)if(p<=g){const v=1/u;h*=v,p*=v,m=h*(h+o*p+2*a)+p*(o*h+p+2*c)+l}else p=s,h=Math.max(0,-(o*p+a)),m=-h*h+p*(p+2*c)+l;else p=-s,h=Math.max(0,-(o*p+a)),m=-h*h+p*(p+2*c)+l;else p<=-g?(h=Math.max(0,-(-o*s+a)),p=h>0?-s:Math.min(Math.max(-s,-c),s),m=-h*h+p*(p+2*c)+l):p<=g?(h=0,p=Math.min(Math.max(-s,-c),s),m=p*(p+2*c)+l):(h=Math.max(0,-(o*s+a)),p=h>0?s:Math.min(Math.max(-s,-c),s),m=-h*h+p*(p+2*c)+l);else p=o>0?-s:s,h=Math.max(0,-(o*p+a)),m=-h*h+p*(p+2*c)+l;return r&&r.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(_1).addScaledVector(Zg,p),m}intersectSphere(e,n){ec.subVectors(e.center,this.origin);const r=ec.dot(this.direction),i=ec.dot(ec)-r*r,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),a=r-o,c=r+o;return c<0?null:a<0?this.at(c,n):this.at(a,n)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const n=e.normal.dot(this.direction);if(n===0)return e.distanceToPoint(this.origin)===0?0:null;const r=-(this.origin.dot(e.normal)+e.constant)/n;return r>=0?r:null}intersectPlane(e,n){const r=this.distanceToPlane(e);return r===null?null:this.at(r,n)}intersectsPlane(e){const n=e.distanceToPoint(this.origin);return n===0||e.normal.dot(this.direction)*n<0}intersectBox(e,n){let r,i,s,o,a,c;const l=1/this.direction.x,u=1/this.direction.y,h=1/this.direction.z,p=this.origin;return l>=0?(r=(e.min.x-p.x)*l,i=(e.max.x-p.x)*l):(r=(e.max.x-p.x)*l,i=(e.min.x-p.x)*l),u>=0?(s=(e.min.y-p.y)*u,o=(e.max.y-p.y)*u):(s=(e.max.y-p.y)*u,o=(e.min.y-p.y)*u),r>o||s>i||((s>r||isNaN(r))&&(r=s),(o=0?(a=(e.min.z-p.z)*h,c=(e.max.z-p.z)*h):(a=(e.max.z-p.z)*h,c=(e.min.z-p.z)*h),r>c||a>i)||((a>r||r!==r)&&(r=a),(c=0?r:i,n)}intersectsBox(e){return this.intersectBox(e,ec)!==null}intersectTriangle(e,n,r,i,s){v1.subVectors(n,e),Jg.subVectors(r,e),y1.crossVectors(v1,Jg);let o=this.direction.dot(y1),a;if(o>0){if(i)return null;a=1}else if(o<0)a=-1,o=-o;else return null;dl.subVectors(this.origin,e);const c=a*this.direction.dot(Jg.crossVectors(dl,Jg));if(c<0)return null;const l=a*this.direction.dot(v1.cross(dl));if(l<0||c+l>o)return null;const u=-a*dl.dot(y1);return u<0?null:this.at(u/o,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class ar{constructor(e,n,r,i,s,o,a,c,l,u,h,p,m,g,v,y){ar.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,n,r,i,s,o,a,c,l,u,h,p,m,g,v,y)}set(e,n,r,i,s,o,a,c,l,u,h,p,m,g,v,y){const _=this.elements;return _[0]=e,_[4]=n,_[8]=r,_[12]=i,_[1]=s,_[5]=o,_[9]=a,_[13]=c,_[2]=l,_[6]=u,_[10]=h,_[14]=p,_[3]=m,_[7]=g,_[11]=v,_[15]=y,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new ar().fromArray(this.elements)}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],n[9]=r[9],n[10]=r[10],n[11]=r[11],n[12]=r[12],n[13]=r[13],n[14]=r[14],n[15]=r[15],this}copyPosition(e){const n=this.elements,r=e.elements;return n[12]=r[12],n[13]=r[13],n[14]=r[14],this}setFromMatrix3(e){const n=e.elements;return this.set(n[0],n[3],n[6],0,n[1],n[4],n[7],0,n[2],n[5],n[8],0,0,0,0,1),this}extractBasis(e,n,r){return e.setFromMatrixColumn(this,0),n.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(e,n,r){return this.set(e.x,n.x,r.x,0,e.y,n.y,r.y,0,e.z,n.z,r.z,0,0,0,0,1),this}extractRotation(e){const n=this.elements,r=e.elements,i=1/Vh.setFromMatrixColumn(e,0).length(),s=1/Vh.setFromMatrixColumn(e,1).length(),o=1/Vh.setFromMatrixColumn(e,2).length();return n[0]=r[0]*i,n[1]=r[1]*i,n[2]=r[2]*i,n[3]=0,n[4]=r[4]*s,n[5]=r[5]*s,n[6]=r[6]*s,n[7]=0,n[8]=r[8]*o,n[9]=r[9]*o,n[10]=r[10]*o,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromEuler(e){const n=this.elements,r=e.x,i=e.y,s=e.z,o=Math.cos(r),a=Math.sin(r),c=Math.cos(i),l=Math.sin(i),u=Math.cos(s),h=Math.sin(s);if(e.order==="XYZ"){const p=o*u,m=o*h,g=a*u,v=a*h;n[0]=c*u,n[4]=-c*h,n[8]=l,n[1]=m+g*l,n[5]=p-v*l,n[9]=-a*c,n[2]=v-p*l,n[6]=g+m*l,n[10]=o*c}else if(e.order==="YXZ"){const p=c*u,m=c*h,g=l*u,v=l*h;n[0]=p+v*a,n[4]=g*a-m,n[8]=o*l,n[1]=o*h,n[5]=o*u,n[9]=-a,n[2]=m*a-g,n[6]=v+p*a,n[10]=o*c}else if(e.order==="ZXY"){const p=c*u,m=c*h,g=l*u,v=l*h;n[0]=p-v*a,n[4]=-o*h,n[8]=g+m*a,n[1]=m+g*a,n[5]=o*u,n[9]=v-p*a,n[2]=-o*l,n[6]=a,n[10]=o*c}else if(e.order==="ZYX"){const p=o*u,m=o*h,g=a*u,v=a*h;n[0]=c*u,n[4]=g*l-m,n[8]=p*l+v,n[1]=c*h,n[5]=v*l+p,n[9]=m*l-g,n[2]=-l,n[6]=a*c,n[10]=o*c}else if(e.order==="YZX"){const p=o*c,m=o*l,g=a*c,v=a*l;n[0]=c*u,n[4]=v-p*h,n[8]=g*h+m,n[1]=h,n[5]=o*u,n[9]=-a*u,n[2]=-l*u,n[6]=m*h+g,n[10]=p-v*h}else if(e.order==="XZY"){const p=o*c,m=o*l,g=a*c,v=a*l;n[0]=c*u,n[4]=-h,n[8]=l*u,n[1]=p*h+v,n[5]=o*u,n[9]=m*h-g,n[2]=g*h-m,n[6]=a*u,n[10]=v*h+p}return n[3]=0,n[7]=0,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Iz,e,Oz)}lookAt(e,n,r){const i=this.elements;return bs.subVectors(e,n),bs.lengthSq()===0&&(bs.z=1),bs.normalize(),pl.crossVectors(r,bs),pl.lengthSq()===0&&(Math.abs(r.z)===1?bs.x+=1e-4:bs.z+=1e-4,bs.normalize(),pl.crossVectors(r,bs)),pl.normalize(),Qg.crossVectors(bs,pl),i[0]=pl.x,i[4]=Qg.x,i[8]=bs.x,i[1]=pl.y,i[5]=Qg.y,i[9]=bs.y,i[2]=pl.z,i[6]=Qg.z,i[10]=bs.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,i=n.elements,s=this.elements,o=r[0],a=r[4],c=r[8],l=r[12],u=r[1],h=r[5],p=r[9],m=r[13],g=r[2],v=r[6],y=r[10],_=r[14],S=r[3],E=r[7],b=r[11],N=r[15],R=i[0],M=i[4],O=i[8],C=i[12],I=i[1],U=i[5],L=i[9],P=i[13],T=i[2],H=i[6],V=i[10],B=i[14],z=i[3],W=i[7],K=i[11],j=i[15];return s[0]=o*R+a*I+c*T+l*z,s[4]=o*M+a*U+c*H+l*W,s[8]=o*O+a*L+c*V+l*K,s[12]=o*C+a*P+c*B+l*j,s[1]=u*R+h*I+p*T+m*z,s[5]=u*M+h*U+p*H+m*W,s[9]=u*O+h*L+p*V+m*K,s[13]=u*C+h*P+p*B+m*j,s[2]=g*R+v*I+y*T+_*z,s[6]=g*M+v*U+y*H+_*W,s[10]=g*O+v*L+y*V+_*K,s[14]=g*C+v*P+y*B+_*j,s[3]=S*R+E*I+b*T+N*z,s[7]=S*M+E*U+b*H+N*W,s[11]=S*O+E*L+b*V+N*K,s[15]=S*C+E*P+b*B+N*j,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[4]*=e,n[8]*=e,n[12]*=e,n[1]*=e,n[5]*=e,n[9]*=e,n[13]*=e,n[2]*=e,n[6]*=e,n[10]*=e,n[14]*=e,n[3]*=e,n[7]*=e,n[11]*=e,n[15]*=e,this}determinant(){const e=this.elements,n=e[0],r=e[4],i=e[8],s=e[12],o=e[1],a=e[5],c=e[9],l=e[13],u=e[2],h=e[6],p=e[10],m=e[14],g=e[3],v=e[7],y=e[11],_=e[15];return g*(+s*c*h-i*l*h-s*a*p+r*l*p+i*a*m-r*c*m)+v*(+n*c*m-n*l*p+s*o*p-i*o*m+i*l*u-s*c*u)+y*(+n*l*h-n*a*m-s*o*h+r*o*m+s*a*u-r*l*u)+_*(-i*a*u-n*c*h+n*a*p+i*o*h-r*o*p+r*c*u)}transpose(){const e=this.elements;let n;return n=e[1],e[1]=e[4],e[4]=n,n=e[2],e[2]=e[8],e[8]=n,n=e[6],e[6]=e[9],e[9]=n,n=e[3],e[3]=e[12],e[12]=n,n=e[7],e[7]=e[13],e[13]=n,n=e[11],e[11]=e[14],e[14]=n,this}setPosition(e,n,r){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=n,i[14]=r),this}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],u=e[8],h=e[9],p=e[10],m=e[11],g=e[12],v=e[13],y=e[14],_=e[15],S=h*y*l-v*p*l+v*c*m-a*y*m-h*c*_+a*p*_,E=g*p*l-u*y*l-g*c*m+o*y*m+u*c*_-o*p*_,b=u*v*l-g*h*l+g*a*m-o*v*m-u*a*_+o*h*_,N=g*h*c-u*v*c-g*a*p+o*v*p+u*a*y-o*h*y,R=n*S+r*E+i*b+s*N;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/R;return e[0]=S*M,e[1]=(v*p*s-h*y*s-v*i*m+r*y*m+h*i*_-r*p*_)*M,e[2]=(a*y*s-v*c*s+v*i*l-r*y*l-a*i*_+r*c*_)*M,e[3]=(h*c*s-a*p*s-h*i*l+r*p*l+a*i*m-r*c*m)*M,e[4]=E*M,e[5]=(u*y*s-g*p*s+g*i*m-n*y*m-u*i*_+n*p*_)*M,e[6]=(g*c*s-o*y*s-g*i*l+n*y*l+o*i*_-n*c*_)*M,e[7]=(o*p*s-u*c*s+u*i*l-n*p*l-o*i*m+n*c*m)*M,e[8]=b*M,e[9]=(g*h*s-u*v*s-g*r*m+n*v*m+u*r*_-n*h*_)*M,e[10]=(o*v*s-g*a*s+g*r*l-n*v*l-o*r*_+n*a*_)*M,e[11]=(u*a*s-o*h*s-u*r*l+n*h*l+o*r*m-n*a*m)*M,e[12]=N*M,e[13]=(u*v*i-g*h*i+g*r*p-n*v*p-u*r*y+n*h*y)*M,e[14]=(g*a*i-o*v*i-g*r*c+n*v*c+o*r*y-n*a*y)*M,e[15]=(o*h*i-u*a*i+u*r*c-n*h*c-o*r*p+n*a*p)*M,this}scale(e){const n=this.elements,r=e.x,i=e.y,s=e.z;return n[0]*=r,n[4]*=i,n[8]*=s,n[1]*=r,n[5]*=i,n[9]*=s,n[2]*=r,n[6]*=i,n[10]*=s,n[3]*=r,n[7]*=i,n[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,n=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],r=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(n,r,i))}makeTranslation(e,n,r){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,n,0,0,1,r,0,0,0,1),this}makeRotationX(e){const n=Math.cos(e),r=Math.sin(e);return this.set(1,0,0,0,0,n,-r,0,0,r,n,0,0,0,0,1),this}makeRotationY(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,0,r,0,0,1,0,0,-r,0,n,0,0,0,0,1),this}makeRotationZ(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,0,r,n,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,n){const r=Math.cos(n),i=Math.sin(n),s=1-r,o=e.x,a=e.y,c=e.z,l=s*o,u=s*a;return this.set(l*o+r,l*a-i*c,l*c+i*a,0,l*a+i*c,u*a+r,u*c-i*o,0,l*c-i*a,u*c+i*o,s*c*c+r,0,0,0,0,1),this}makeScale(e,n,r){return this.set(e,0,0,0,0,n,0,0,0,0,r,0,0,0,0,1),this}makeShear(e,n,r,i,s,o){return this.set(1,r,s,0,e,1,o,0,n,i,1,0,0,0,0,1),this}compose(e,n,r){const i=this.elements,s=n._x,o=n._y,a=n._z,c=n._w,l=s+s,u=o+o,h=a+a,p=s*l,m=s*u,g=s*h,v=o*u,y=o*h,_=a*h,S=c*l,E=c*u,b=c*h,N=r.x,R=r.y,M=r.z;return i[0]=(1-(v+_))*N,i[1]=(m+b)*N,i[2]=(g-E)*N,i[3]=0,i[4]=(m-b)*R,i[5]=(1-(p+_))*R,i[6]=(y+S)*R,i[7]=0,i[8]=(g+E)*M,i[9]=(y-S)*M,i[10]=(1-(p+v))*M,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,n,r){const i=this.elements;let s=Vh.set(i[0],i[1],i[2]).length();const o=Vh.set(i[4],i[5],i[6]).length(),a=Vh.set(i[8],i[9],i[10]).length();this.determinant()<0&&(s=-s),e.x=i[12],e.y=i[13],e.z=i[14],yo.copy(this);const l=1/s,u=1/o,h=1/a;return yo.elements[0]*=l,yo.elements[1]*=l,yo.elements[2]*=l,yo.elements[4]*=u,yo.elements[5]*=u,yo.elements[6]*=u,yo.elements[8]*=h,yo.elements[9]*=h,yo.elements[10]*=h,n.setFromRotationMatrix(yo),r.x=s,r.y=o,r.z=a,this}makePerspective(e,n,r,i,s,o,a=vc){const c=this.elements,l=2*s/(n-e),u=2*s/(r-i),h=(n+e)/(n-e),p=(r+i)/(r-i);let m,g;if(a===vc)m=-(o+s)/(o-s),g=-2*o*s/(o-s);else if(a===O_)m=-o/(o-s),g=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=l,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=u,c[9]=p,c[13]=0,c[2]=0,c[6]=0,c[10]=m,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,n,r,i,s,o,a=vc){const c=this.elements,l=1/(n-e),u=1/(r-i),h=1/(o-s),p=(n+e)*l,m=(r+i)*u;let g,v;if(a===vc)g=(o+s)*h,v=-2*h;else if(a===O_)g=s*h,v=-1*h;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=2*l,c[4]=0,c[8]=0,c[12]=-p,c[1]=0,c[5]=2*u,c[9]=0,c[13]=-m,c[2]=0,c[6]=0,c[10]=v,c[14]=-g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const n=this.elements,r=e.elements;for(let i=0;i<16;i++)if(n[i]!==r[i])return!1;return!0}fromArray(e,n=0){for(let r=0;r<16;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e[n+9]=r[9],e[n+10]=r[10],e[n+11]=r[11],e[n+12]=r[12],e[n+13]=r[13],e[n+14]=r[14],e[n+15]=r[15],e}}const Vh=new xe,yo=new ar,Iz=new xe(0,0,0),Oz=new xe(1,1,1),pl=new xe,Qg=new xe,bs=new xe,cR=new ar,lR=new Zp;class kc{constructor(e=0,n=0,r=0,i=kc.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,n,r,i=this._order){return this._x=e,this._y=n,this._z=r,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,n=this._order,r=!0){const i=e.elements,s=i[0],o=i[4],a=i[8],c=i[1],l=i[5],u=i[9],h=i[2],p=i[6],m=i[10];switch(n){case"XYZ":this._y=Math.asin(Di(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,m),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(p,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Di(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,m),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(Di(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-h,m),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-Di(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(p,m),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(Di(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(a,m));break;case"XZY":this._z=Math.asin(-Di(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(p,l),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-u,m),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+n)}return this._order=n,r===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,r){return cR.makeRotationFromQuaternion(e),this.setFromRotationMatrix(cR,n,r)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return lR.setFromEuler(this),this.setFromQuaternion(lR,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}kc.DEFAULT_ORDER="XYZ";class bf{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let n=0;n1){for(let r=0;r0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map(a=>({boxInitialized:a.boxInitialized,boxMin:a.box.min.toArray(),boxMax:a.box.max.toArray(),sphereInitialized:a.sphereInitialized,sphereRadius:a.sphere.radius,sphereCenter:a.sphere.center.toArray()})),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()}));function s(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,u=c.length;l0){i.children=[];for(let a=0;a0){i.animations=[];for(let a=0;a0&&(r.geometries=a),c.length>0&&(r.materials=c),l.length>0&&(r.textures=l),u.length>0&&(r.images=u),h.length>0&&(r.shapes=h),p.length>0&&(r.skeletons=p),m.length>0&&(r.animations=m),g.length>0&&(r.nodes=g)}return r.object=i,r;function o(a){const c=[];for(const l in a){const u=a[l];delete u.metadata,c.push(u)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,n=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),n===!0)for(let r=0;r0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,n,r,i,s){xo.subVectors(i,n),nc.subVectors(r,n),S1.subVectors(e,n);const o=xo.dot(xo),a=xo.dot(nc),c=xo.dot(S1),l=nc.dot(nc),u=nc.dot(S1),h=o*l-a*a;if(h===0)return s.set(0,0,0),null;const p=1/h,m=(l*c-a*u)*p,g=(o*u-a*c)*p;return s.set(1-m-g,g,m)}static containsPoint(e,n,r,i){return this.getBarycoord(e,n,r,i,rc)===null?!1:rc.x>=0&&rc.y>=0&&rc.x+rc.y<=1}static getInterpolation(e,n,r,i,s,o,a,c){return this.getBarycoord(e,n,r,i,rc)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,rc.x),c.addScaledVector(o,rc.y),c.addScaledVector(a,rc.z),c)}static getInterpolatedAttribute(e,n,r,i,s,o){return T1.setScalar(0),A1.setScalar(0),M1.setScalar(0),T1.fromBufferAttribute(e,n),A1.fromBufferAttribute(e,r),M1.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(T1,s.x),o.addScaledVector(A1,s.y),o.addScaledVector(M1,s.z),o}static isFrontFacing(e,n,r,i){return xo.subVectors(r,n),nc.subVectors(e,n),xo.cross(nc).dot(i)<0}set(e,n,r){return this.a.copy(e),this.b.copy(n),this.c.copy(r),this}setFromPointsAndIndices(e,n,r,i){return this.a.copy(e[n]),this.b.copy(e[r]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,n,r,i){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return xo.subVectors(this.c,this.b),nc.subVectors(this.a,this.b),xo.cross(nc).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return bo.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return bo.getBarycoord(e,this.a,this.b,this.c,n)}getInterpolation(e,n,r,i,s){return bo.getInterpolation(e,this.a,this.b,this.c,n,r,i,s)}containsPoint(e){return bo.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return bo.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const r=this.a,i=this.b,s=this.c;let o,a;Wh.subVectors(i,r),jh.subVectors(s,r),E1.subVectors(e,r);const c=Wh.dot(E1),l=jh.dot(E1);if(c<=0&&l<=0)return n.copy(r);w1.subVectors(e,i);const u=Wh.dot(w1),h=jh.dot(w1);if(u>=0&&h<=u)return n.copy(i);const p=c*h-u*l;if(p<=0&&c>=0&&u<=0)return o=c/(c-u),n.copy(r).addScaledVector(Wh,o);b1.subVectors(e,s);const m=Wh.dot(b1),g=jh.dot(b1);if(g>=0&&m<=g)return n.copy(s);const v=m*l-c*g;if(v<=0&&l>=0&&g<=0)return a=l/(l-g),n.copy(r).addScaledVector(jh,a);const y=u*g-m*h;if(y<=0&&h-u>=0&&m-g>=0)return mR.subVectors(s,i),a=(h-u)/(h-u+(m-g)),n.copy(i).addScaledVector(mR,a);const _=1/(y+v+p);return o=v*_,a=p*_,n.copy(r).addScaledVector(Wh,o).addScaledVector(jh,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const TO={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ml={h:0,s:0,l:0},t0={h:0,s:0,l:0};function C1(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*6*(2/3-n):t}class ln{constructor(e,n,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,n,r)}set(e,n,r){if(n===void 0&&r===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,n,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=pr){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,hn.toWorkingColorSpace(this,n),this}setRGB(e,n,r,i=hn.workingColorSpace){return this.r=e,this.g=n,this.b=r,hn.toWorkingColorSpace(this,i),this}setHSL(e,n,r,i=hn.workingColorSpace){if(e=xb(e,1),n=Di(n,0,1),r=Di(r,0,1),n===0)this.r=this.g=this.b=r;else{const s=r<=.5?r*(1+n):r+n-r*n,o=2*r-s;this.r=C1(o,s,e+1/3),this.g=C1(o,s,e),this.b=C1(o,s,e-1/3)}return hn.toWorkingColorSpace(this,i),this}setStyle(e,n=pr){function r(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,n);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,n);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,n);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,n);if(o===6)return this.setHex(parseInt(s,16),n);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,n);return this}setColorName(e,n=pr){const r=TO[e.toLowerCase()];return r!==void 0?this.setHex(r,n):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Ec(e.r),this.g=Ec(e.g),this.b=Ec(e.b),this}copyLinearToSRGB(e){return this.r=wf(e.r),this.g=wf(e.g),this.b=wf(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=pr){return hn.fromWorkingColorSpace(yi.copy(this),e),Math.round(Di(yi.r*255,0,255))*65536+Math.round(Di(yi.g*255,0,255))*256+Math.round(Di(yi.b*255,0,255))}getHexString(e=pr){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=hn.workingColorSpace){hn.fromWorkingColorSpace(yi.copy(this),n);const r=yi.r,i=yi.g,s=yi.b,o=Math.max(r,i,s),a=Math.min(r,i,s);let c,l;const u=(a+o)/2;if(a===o)c=0,l=0;else{const h=o-a;switch(l=u<=.5?h/(o+a):h/(2-o-a),o){case r:c=(i-s)/h+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const n in e){const r=e[n];if(r===void 0){console.warn(`THREE.Material: parameter '${n}' has value of undefined.`);continue}const i=this[n];if(i===void 0){console.warn(`THREE.Material: '${n}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.copy(r):this[n]=r}}toJSON(e){const n=e===void 0||typeof e=="string";n&&(e={textures:{},images:{}});const r={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(r.dispersion=this.dispersion),this.iridescence!==void 0&&(r.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(r.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(r.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(r.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(r.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapRotation!==void 0&&(r.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==Sf&&(r.blending=this.blending),this.side!==Nc&&(r.side=this.side),this.vertexColors===!0&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=!0),this.blendSrc!==WS&&(r.blendSrc=this.blendSrc),this.blendDst!==jS&&(r.blendDst=this.blendDst),this.blendEquation!==Ru&&(r.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(r.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(r.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(r.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(r.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(r.blendAlpha=this.blendAlpha),this.depthFunc!==Pf&&(r.depthFunc=this.depthFunc),this.depthTest===!1&&(r.depthTest=this.depthTest),this.depthWrite===!1&&(r.depthWrite=this.depthWrite),this.colorWrite===!1&&(r.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(r.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==ZC&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Dh&&(r.stencilFail=this.stencilFail),this.stencilZFail!==Dh&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==Dh&&(r.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(r.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaHash===!0&&(r.alphaHash=!0),this.alphaToCoverage===!0&&(r.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=!0),this.forceSinglePass===!0&&(r.forceSinglePass=!0),this.wireframe===!0&&(r.wireframe=!0),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=!0),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),this.fog===!1&&(r.fog=!1),Object.keys(this.userData).length>0&&(r.userData=this.userData);function i(s){const o=[];for(const a in s){const c=s[a];delete c.metadata,o.push(c)}return o}if(n){const s=i(e.textures),o=i(e.images);s.length>0&&(r.textures=s),o.length>0&&(r.images=o)}return r}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const n=e.clippingPlanes;let r=null;if(n!==null){const i=n.length;r=new Array(i);for(let s=0;s!==i;++s)r[s]=n[s].clone()}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class Eb extends Vc{static get type(){return"MeshBasicMaterial"}constructor(e){super(),this.isMeshBasicMaterial=!0,this.color=new ln(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new kc,this.combine=aO,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Er=new xe,n0=new St;class Jn{constructor(e,n,r=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=r,this.usage=JC,this.updateRanges=[],this.gpuType=_a,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,n,r){e*=this.itemSize,r*=n.itemSize;for(let i=0,s=this.itemSize;in.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),n.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Jp);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new xe(-1/0,-1/0,-1/0),new xe(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let r=0,i=n.length;r0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const n=this.index;n!==null&&(e.data.index={type:n.array.constructor.name,array:Array.prototype.slice.call(n.array)});const r=this.attributes;for(const c in r){const l=r[c];e.data.attributes[c]=l.toJSON(e.data)}const i={};let s=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],u=[];for(let h=0,p=l.length;h0&&(i[c]=u,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const n={};this.name=e.name;const r=e.index;r!==null&&this.setIndex(r.clone(n));const i=e.attributes;for(const l in i){const u=i[l];this.setAttribute(l,u.clone(n))}const s=e.morphAttributes;for(const l in s){const u=[],h=s[l];for(let p=0,m=h.length;p0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s(e.far-e.near)**2))&&(gR.copy(s).invert(),hu.copy(e.ray).applyMatrix4(gR),!(r.boundingBox!==null&&hu.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,n,hu)))}_computeIntersections(e,n,r){let i;const s=this.geometry,o=this.material,a=s.index,c=s.attributes.position,l=s.attributes.uv,u=s.attributes.uv1,h=s.attributes.normal,p=s.groups,m=s.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,v=p.length;gn.far?null:{distance:l,point:c0.clone(),object:t}}function l0(t,e,n,r,i,s,o,a,c,l){t.getVertexPosition(a,i0),t.getVertexPosition(c,s0),t.getVertexPosition(l,o0);const u=zz(t,e,n,r,i0,s0,o0,vR);if(u){const h=new xe;bo.getBarycoord(vR,i0,s0,o0,h),i&&(u.uv=bo.getInterpolatedAttribute(i,a,c,l,h,new St)),s&&(u.uv1=bo.getInterpolatedAttribute(s,a,c,l,h,new St)),o&&(u.normal=bo.getInterpolatedAttribute(o,a,c,l,h,new xe),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));const p={a,b:c,c:l,normal:new xe,materialIndex:0};bo.getNormal(i0,s0,o0,p.normal),u.face=p,u.barycoord=h}return u}class Qp extends Bo{constructor(e=1,n=1,r=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:r,widthSegments:i,heightSegments:s,depthSegments:o};const a=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const c=[],l=[],u=[],h=[];let p=0,m=0;g("z","y","x",-1,-1,r,n,e,o,s,0),g("z","y","x",1,-1,r,n,-e,o,s,1),g("x","z","y",1,1,e,r,n,i,o,2),g("x","z","y",1,-1,e,r,-n,i,o,3),g("x","y","z",1,-1,e,n,r,i,s,4),g("x","y","z",-1,-1,e,n,-r,i,s,5),this.setIndex(c),this.setAttribute("position",new Bu(l,3)),this.setAttribute("normal",new Bu(u,3)),this.setAttribute("uv",new Bu(h,2));function g(v,y,_,S,E,b,N,R,M,O,C){const I=b/M,U=N/O,L=b/2,P=N/2,T=R/2,H=M+1,V=O+1;let B=0,z=0;const W=new xe;for(let K=0;K0?1:-1,u.push(W.x,W.y,W.z),h.push(Y/M),h.push(1-K/O),B+=1}}for(let K=0;K0&&(n.defines=this.defines),n.vertexShader=this.vertexShader,n.fragmentShader=this.fragmentShader,n.lights=this.lights,n.clipping=this.clipping;const r={};for(const i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(n.extensions=r),n}}class Dv extends cs{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ar,this.projectionMatrix=new ar,this.projectionMatrixInverse=new ar,this.coordinateSystem=vc}copy(e,n){return super.copy(e,n),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,n){super.updateWorldMatrix(e,n),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const gl=new xe,yR=new St,xR=new St;class Ms extends Dv{constructor(e=50,n=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,this.focus=10,this.aspect=n,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const n=.5*this.getFilmHeight()/e;this.fov=bp*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(mp*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return bp*2*Math.atan(Math.tan(mp*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,n,r){gl.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(gl.x,gl.y).multiplyScalar(-e/gl.z),gl.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),r.set(gl.x,gl.y).multiplyScalar(-e/gl.z)}getViewSize(e,n){return this.getViewBounds(e,yR,xR),n.subVectors(xR,yR)}setViewOffset(e,n,r,i,s,o){this.aspect=e/n,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let n=e*Math.tan(mp*.5*this.fov)/this.zoom,r=2*n,i=this.aspect*r,s=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,l=o.fullHeight;s+=o.offsetX*i/c,n-=o.offsetY*r/l,i*=o.width/c,r*=o.height/l}const a=this.filmOffset;a!==0&&(s+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,n,n-r,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.fov=this.fov,n.object.zoom=this.zoom,n.object.near=this.near,n.object.far=this.far,n.object.focus=this.focus,n.object.aspect=this.aspect,this.view!==null&&(n.object.view=Object.assign({},this.view)),n.object.filmGauge=this.filmGauge,n.object.filmOffset=this.filmOffset,n}}const qh=-90,Xh=1;class jz extends cs{constructor(e,n,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Ms(qh,Xh,e,n);i.layers=this.layers,this.add(i);const s=new Ms(qh,Xh,e,n);s.layers=this.layers,this.add(s);const o=new Ms(qh,Xh,e,n);o.layers=this.layers,this.add(o);const a=new Ms(qh,Xh,e,n);a.layers=this.layers,this.add(a);const c=new Ms(qh,Xh,e,n);c.layers=this.layers,this.add(c);const l=new Ms(qh,Xh,e,n);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[r,i,s,o,a,c]=n;for(const l of n)this.remove(l);if(e===vc)r.up.set(0,1,0),r.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===O_)r.up.set(0,-1,0),r.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of n)this.add(l),l.updateMatrixWorld()}update(e,n){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,a,c,l,u]=this.children,h=e.getRenderTarget(),p=e.getActiveCubeFace(),m=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;const v=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(n,s),e.setRenderTarget(r,1,i),e.render(n,o),e.setRenderTarget(r,2,i),e.render(n,a),e.setRenderTarget(r,3,i),e.render(n,c),e.setRenderTarget(r,4,i),e.render(n,l),r.texture.generateMipmaps=v,e.setRenderTarget(r,5,i),e.render(n,u),e.setRenderTarget(h,p,m),e.xr.enabled=g,r.texture.needsPMREMUpdate=!0}}class RO extends or{constructor(e,n,r,i,s,o,a,c,l,u){e=e!==void 0?e:[],n=n!==void 0?n:Df,super(e,n,r,i,s,o,a,c,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class $z extends Us{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];this.texture=new RO(i,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=n.generateMipmaps!==void 0?n.generateMipmaps:!1,this.texture.minFilter=n.minFilter!==void 0?n.minFilter:is}fromEquirectangularTexture(e,n){this.texture.type=n.type,this.texture.colorSpace=n.colorSpace,this.texture.generateMipmaps=n.generateMipmaps,this.texture.minFilter=n.minFilter,this.texture.magFilter=n.magFilter;const r={uniforms:{tEquirect:{value:null}},vertexShader:` - - varying vec3 vWorldDirection; - - vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); - - } - - void main() { - - vWorldDirection = transformDirection( position, modelMatrix ); - - #include - #include - - } - `,fragmentShader:` - - uniform sampler2D tEquirect; - - varying vec3 vWorldDirection; - - #include - - void main() { - - vec3 direction = normalize( vWorldDirection ); - - vec2 sampleUV = equirectUv( direction ); - - gl_FragColor = texture2D( tEquirect, sampleUV ); - - } - `},i=new Qp(5,5,5),s=new Gi({name:"CubemapFromEquirect",uniforms:Ff(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:ri,blending:Ro});s.uniforms.tEquirect.value=n;const o=new Ao(i,s),a=n.minFilter;return n.minFilter===Lu&&(n.minFilter=is),new jz(1,10,this).update(e,o),n.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,n,r,i){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,r,i);e.setRenderTarget(s)}}const k1=new xe,qz=new xe,Xz=new Dt;class Eo{constructor(e=new xe(1,0,0),n=0){this.isPlane=!0,this.normal=e,this.constant=n}set(e,n){return this.normal.copy(e),this.constant=n,this}setComponents(e,n,r,i){return this.normal.set(e,n,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,r){const i=k1.subVectors(r,n).cross(qz.subVectors(e,n)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,n){return n.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,n){const r=e.delta(k1),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?n.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/i;return s<0||s>1?null:n.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const n=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return n<0&&r>0||r<0&&n>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,n){const r=n||Xz.getNormalMatrix(e),i=this.coplanarPoint(k1).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-i.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const fu=new Pv,u0=new xe;class NO{constructor(e=new Eo,n=new Eo,r=new Eo,i=new Eo,s=new Eo,o=new Eo){this.planes=[e,n,r,i,s,o]}set(e,n,r,i,s,o){const a=this.planes;return a[0].copy(e),a[1].copy(n),a[2].copy(r),a[3].copy(i),a[4].copy(s),a[5].copy(o),this}copy(e){const n=this.planes;for(let r=0;r<6;r++)n[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,n=vc){const r=this.planes,i=e.elements,s=i[0],o=i[1],a=i[2],c=i[3],l=i[4],u=i[5],h=i[6],p=i[7],m=i[8],g=i[9],v=i[10],y=i[11],_=i[12],S=i[13],E=i[14],b=i[15];if(r[0].setComponents(c-s,p-l,y-m,b-_).normalize(),r[1].setComponents(c+s,p+l,y+m,b+_).normalize(),r[2].setComponents(c+o,p+u,y+g,b+S).normalize(),r[3].setComponents(c-o,p-u,y-g,b-S).normalize(),r[4].setComponents(c-a,p-h,y-v,b-E).normalize(),n===vc)r[5].setComponents(c+a,p+h,y+v,b+E).normalize();else if(n===O_)r[5].setComponents(a,h,v,E).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+n);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),fu.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),fu.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(fu)}intersectsSprite(e){return fu.center.set(0,0,0),fu.radius=.7071067811865476,fu.applyMatrix4(e.matrixWorld),this.intersectsSphere(fu)}intersectsSphere(e){const n=this.planes,r=e.center,i=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(r)0?e.max.x:e.min.x,u0.y=i.normal.y>0?e.max.y:e.min.y,u0.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(u0)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let r=0;r<6;r++)if(n[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function kO(){let t=null,e=!1,n=null,r=null;function i(s,o){n(s,o),r=t.requestAnimationFrame(i)}return{start:function(){e!==!0&&n!==null&&(r=t.requestAnimationFrame(i),e=!0)},stop:function(){t.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function Kz(t){const e=new WeakMap;function n(a,c){const l=a.array,u=a.usage,h=l.byteLength,p=t.createBuffer();t.bindBuffer(c,p),t.bufferData(c,l,u),a.onUploadCallback();let m;if(l instanceof Float32Array)m=t.FLOAT;else if(l instanceof Uint16Array)a.isFloat16BufferAttribute?m=t.HALF_FLOAT:m=t.UNSIGNED_SHORT;else if(l instanceof Int16Array)m=t.SHORT;else if(l instanceof Uint32Array)m=t.UNSIGNED_INT;else if(l instanceof Int32Array)m=t.INT;else if(l instanceof Int8Array)m=t.BYTE;else if(l instanceof Uint8Array)m=t.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)m=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:p,type:m,bytesPerElement:l.BYTES_PER_ELEMENT,version:a.version,size:h}}function r(a,c,l){const u=c.array,h=c.updateRanges;if(t.bindBuffer(l,a),h.length===0)t.bufferSubData(l,0,u);else{h.sort((m,g)=>m.start-g.start);let p=0;for(let m=1;m 0 - vec4 plane; - #ifdef ALPHA_TO_COVERAGE - float distanceToPlane, distanceGradient; - float clipOpacity = 1.0; - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; - distanceGradient = fwidth( distanceToPlane ) / 2.0; - clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); - if ( clipOpacity == 0.0 ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - float unionClipOpacity = 1.0; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; - distanceGradient = fwidth( distanceToPlane ) / 2.0; - unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); - } - #pragma unroll_loop_end - clipOpacity *= 1.0 - unionClipOpacity; - #endif - diffuseColor.a *= clipOpacity; - if ( diffuseColor.a == 0.0 ) discard; - #else - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - bool clipped = true; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; - } - #pragma unroll_loop_end - if ( clipped ) discard; - #endif - #endif -#endif`,f8=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; - uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,d8=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; -#endif`,p8=`#if NUM_CLIPPING_PLANES > 0 - vClipPosition = - mvPosition.xyz; -#endif`,m8=`#if defined( USE_COLOR_ALPHA ) - diffuseColor *= vColor; -#elif defined( USE_COLOR ) - diffuseColor.rgb *= vColor; -#endif`,g8=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) - varying vec3 vColor; -#endif`,_8=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - varying vec3 vColor; -#endif`,v8=`#if defined( USE_COLOR_ALPHA ) - vColor = vec4( 1.0 ); -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - vColor = vec3( 1.0 ); -#endif -#ifdef USE_COLOR - vColor *= color; -#endif -#ifdef USE_INSTANCING_COLOR - vColor.xyz *= instanceColor.xyz; -#endif -#ifdef USE_BATCHING_COLOR - vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); - vColor.xyz *= batchingColor.xyz; -#endif`,y8=`#define PI 3.141592653589793 -#define PI2 6.283185307179586 -#define PI_HALF 1.5707963267948966 -#define RECIPROCAL_PI 0.3183098861837907 -#define RECIPROCAL_PI2 0.15915494309189535 -#define EPSILON 1e-6 -#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -#define whiteComplement( a ) ( 1.0 - saturate( a ) ) -float pow2( const in float x ) { return x*x; } -vec3 pow2( const in vec3 x ) { return x*x; } -float pow3( const in float x ) { return x*x*x; } -float pow4( const in float x ) { float x2 = x*x; return x2*x2; } -float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } -float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } -highp float rand( const in vec2 uv ) { - const highp float a = 12.9898, b = 78.233, c = 43758.5453; - highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); - return fract( sin( sn ) * c ); -} -#ifdef HIGH_PRECISION - float precisionSafeLength( vec3 v ) { return length( v ); } -#else - float precisionSafeLength( vec3 v ) { - float maxComponent = max3( abs( v ) ); - return length( v / maxComponent ) * maxComponent; - } -#endif -struct IncidentLight { - vec3 color; - vec3 direction; - bool visible; -}; -struct ReflectedLight { - vec3 directDiffuse; - vec3 directSpecular; - vec3 indirectDiffuse; - vec3 indirectSpecular; -}; -#ifdef USE_ALPHAHASH - varying vec3 vPosition; -#endif -vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); -} -vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); -} -mat3 transposeMat3( const in mat3 m ) { - mat3 tmp; - tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); - tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); - tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); - return tmp; -} -bool isPerspectiveMatrix( mat4 m ) { - return m[ 2 ][ 3 ] == - 1.0; -} -vec2 equirectUv( in vec3 dir ) { - float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; - float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; - return vec2( u, v ); -} -vec3 BRDF_Lambert( const in vec3 diffuseColor ) { - return RECIPROCAL_PI * diffuseColor; -} -vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} -float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,x8=`#ifdef ENVMAP_TYPE_CUBE_UV - #define cubeUV_minMipLevel 4.0 - #define cubeUV_minTileSize 16.0 - float getFace( vec3 direction ) { - vec3 absDirection = abs( direction ); - float face = - 1.0; - if ( absDirection.x > absDirection.z ) { - if ( absDirection.x > absDirection.y ) - face = direction.x > 0.0 ? 0.0 : 3.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } else { - if ( absDirection.z > absDirection.y ) - face = direction.z > 0.0 ? 2.0 : 5.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } - return face; - } - vec2 getUV( vec3 direction, float face ) { - vec2 uv; - if ( face == 0.0 ) { - uv = vec2( direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 1.0 ) { - uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); - } else if ( face == 2.0 ) { - uv = vec2( - direction.x, direction.y ) / abs( direction.z ); - } else if ( face == 3.0 ) { - uv = vec2( - direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 4.0 ) { - uv = vec2( - direction.x, direction.z ) / abs( direction.y ); - } else { - uv = vec2( direction.x, direction.y ) / abs( direction.z ); - } - return 0.5 * ( uv + 1.0 ); - } - vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { - float face = getFace( direction ); - float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); - mipInt = max( mipInt, cubeUV_minMipLevel ); - float faceSize = exp2( mipInt ); - highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; - if ( face > 2.0 ) { - uv.y += faceSize; - face -= 3.0; - } - uv.x += face * faceSize; - uv.x += filterInt * 3.0 * cubeUV_minTileSize; - uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); - uv.x *= CUBEUV_TEXEL_WIDTH; - uv.y *= CUBEUV_TEXEL_HEIGHT; - #ifdef texture2DGradEXT - return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; - #else - return texture2D( envMap, uv ).rgb; - #endif - } - #define cubeUV_r0 1.0 - #define cubeUV_m0 - 2.0 - #define cubeUV_r1 0.8 - #define cubeUV_m1 - 1.0 - #define cubeUV_r4 0.4 - #define cubeUV_m4 2.0 - #define cubeUV_r5 0.305 - #define cubeUV_m5 3.0 - #define cubeUV_r6 0.21 - #define cubeUV_m6 4.0 - float roughnessToMip( float roughness ) { - float mip = 0.0; - if ( roughness >= cubeUV_r1 ) { - mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; - } else if ( roughness >= cubeUV_r4 ) { - mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; - } else if ( roughness >= cubeUV_r5 ) { - mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; - } else if ( roughness >= cubeUV_r6 ) { - mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; - } else { - mip = - 2.0 * log2( 1.16 * roughness ); } - return mip; - } - vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { - float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); - float mipF = fract( mip ); - float mipInt = floor( mip ); - vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); - if ( mipF == 0.0 ) { - return vec4( color0, 1.0 ); - } else { - vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); - return vec4( mix( color0, color1, mipF ), 1.0 ); - } - } -#endif`,S8=`vec3 transformedNormal = objectNormal; -#ifdef USE_TANGENT - vec3 transformedTangent = objectTangent; -#endif -#ifdef USE_BATCHING - mat3 bm = mat3( batchingMatrix ); - transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); - transformedNormal = bm * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = bm * transformedTangent; - #endif -#endif -#ifdef USE_INSTANCING - mat3 im = mat3( instanceMatrix ); - transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); - transformedNormal = im * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = im * transformedTangent; - #endif -#endif -transformedNormal = normalMatrix * transformedNormal; -#ifdef FLIP_SIDED - transformedNormal = - transformedNormal; -#endif -#ifdef USE_TANGENT - transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; - #ifdef FLIP_SIDED - transformedTangent = - transformedTangent; - #endif -#endif`,E8=`#ifdef USE_DISPLACEMENTMAP - uniform sampler2D displacementMap; - uniform float displacementScale; - uniform float displacementBias; -#endif`,w8=`#ifdef USE_DISPLACEMENTMAP - transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,b8=`#ifdef USE_EMISSIVEMAP - vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); - #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE - emissiveColor = sRGBTransferEOTF( emissiveColor ); - #endif - totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,T8=`#ifdef USE_EMISSIVEMAP - uniform sampler2D emissiveMap; -#endif`,A8="gl_FragColor = linearToOutputTexel( gl_FragColor );",M8=`vec4 LinearTransferOETF( in vec4 value ) { - return value; -} -vec4 sRGBTransferEOTF( in vec4 value ) { - return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); -} -vec4 sRGBTransferOETF( in vec4 value ) { - return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); -}`,C8=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vec3 cameraToFrag; - if ( isOrthographic ) { - cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToFrag = normalize( vWorldPosition - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vec3 reflectVec = reflect( cameraToFrag, worldNormal ); - #else - vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); - #endif - #else - vec3 reflectVec = vReflect; - #endif - #ifdef ENVMAP_TYPE_CUBE - vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); - #else - vec4 envColor = vec4( 0.0 ); - #endif - #ifdef ENVMAP_BLENDING_MULTIPLY - outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_MIX ) - outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_ADD ) - outgoingLight += envColor.xyz * specularStrength * reflectivity; - #endif -#endif`,R8=`#ifdef USE_ENVMAP - uniform float envMapIntensity; - uniform float flipEnvMap; - uniform mat3 envMapRotation; - #ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; - #else - uniform sampler2D envMap; - #endif - -#endif`,N8=`#ifdef USE_ENVMAP - uniform float reflectivity; - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - varying vec3 vWorldPosition; - uniform float refractionRatio; - #else - varying vec3 vReflect; - #endif -#endif`,k8=`#ifdef USE_ENVMAP - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - - varying vec3 vWorldPosition; - #else - varying vec3 vReflect; - uniform float refractionRatio; - #endif -#endif`,I8=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vWorldPosition = worldPosition.xyz; - #else - vec3 cameraToVertex; - if ( isOrthographic ) { - cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vReflect = reflect( cameraToVertex, worldNormal ); - #else - vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); - #endif - #endif -#endif`,O8=`#ifdef USE_FOG - vFogDepth = - mvPosition.z; -#endif`,L8=`#ifdef USE_FOG - varying float vFogDepth; -#endif`,P8=`#ifdef USE_FOG - #ifdef FOG_EXP2 - float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); - #else - float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); - #endif - gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); -#endif`,D8=`#ifdef USE_FOG - uniform vec3 fogColor; - varying float vFogDepth; - #ifdef FOG_EXP2 - uniform float fogDensity; - #else - uniform float fogNear; - uniform float fogFar; - #endif -#endif`,U8=`#ifdef USE_GRADIENTMAP - uniform sampler2D gradientMap; -#endif -vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { - float dotNL = dot( normal, lightDirection ); - vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); - #ifdef USE_GRADIENTMAP - return vec3( texture2D( gradientMap, coord ).r ); - #else - vec2 fw = fwidth( coord ) * 0.5; - return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); - #endif -}`,F8=`#ifdef USE_LIGHTMAP - uniform sampler2D lightMap; - uniform float lightMapIntensity; -#endif`,B8=`LambertMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,z8=`varying vec3 vViewPosition; -struct LambertMaterial { - vec3 diffuseColor; - float specularStrength; -}; -void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Lambert -#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,V8=`uniform bool receiveShadow; -uniform vec3 ambientLightColor; -#if defined( USE_LIGHT_PROBES ) - uniform vec3 lightProbe[ 9 ]; -#endif -vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { - float x = normal.x, y = normal.y, z = normal.z; - vec3 result = shCoefficients[ 0 ] * 0.886227; - result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; - result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; - result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; - result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; - result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; - result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); - result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; - result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); - return result; -} -vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); - return irradiance; -} -vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { - vec3 irradiance = ambientLightColor; - return irradiance; -} -float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { - float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); - if ( cutoffDistance > 0.0 ) { - distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); - } - return distanceFalloff; -} -float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { - return smoothstep( coneCosine, penumbraCosine, angleCosine ); -} -#if NUM_DIR_LIGHTS > 0 - struct DirectionalLight { - vec3 direction; - vec3 color; - }; - uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; - void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { - light.color = directionalLight.color; - light.direction = directionalLight.direction; - light.visible = true; - } -#endif -#if NUM_POINT_LIGHTS > 0 - struct PointLight { - vec3 position; - vec3 color; - float distance; - float decay; - }; - uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; - void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = pointLight.position - geometryPosition; - light.direction = normalize( lVector ); - float lightDistance = length( lVector ); - light.color = pointLight.color; - light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } -#endif -#if NUM_SPOT_LIGHTS > 0 - struct SpotLight { - vec3 position; - vec3 direction; - vec3 color; - float distance; - float decay; - float coneCos; - float penumbraCos; - }; - uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; - void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = spotLight.position - geometryPosition; - light.direction = normalize( lVector ); - float angleCos = dot( light.direction, spotLight.direction ); - float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); - if ( spotAttenuation > 0.0 ) { - float lightDistance = length( lVector ); - light.color = spotLight.color * spotAttenuation; - light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } else { - light.color = vec3( 0.0 ); - light.visible = false; - } - } -#endif -#if NUM_RECT_AREA_LIGHTS > 0 - struct RectAreaLight { - vec3 color; - vec3 position; - vec3 halfWidth; - vec3 halfHeight; - }; - uniform sampler2D ltc_1; uniform sampler2D ltc_2; - uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; -#endif -#if NUM_HEMI_LIGHTS > 0 - struct HemisphereLight { - vec3 direction; - vec3 skyColor; - vec3 groundColor; - }; - uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; - vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { - float dotNL = dot( normal, hemiLight.direction ); - float hemiDiffuseWeight = 0.5 * dotNL + 0.5; - vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); - return irradiance; - } -#endif`,H8=`#ifdef USE_ENVMAP - vec3 getIBLIrradiance( const in vec3 normal ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); - return PI * envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 reflectVec = reflect( - viewDir, normal ); - reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); - reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); - return envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - #ifdef USE_ANISOTROPY - vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 bentNormal = cross( bitangent, viewDir ); - bentNormal = normalize( cross( bentNormal, bitangent ) ); - bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); - return getIBLRadiance( viewDir, bentNormal, roughness ); - #else - return vec3( 0.0 ); - #endif - } - #endif -#endif`,G8=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,W8=`varying vec3 vViewPosition; -struct ToonMaterial { - vec3 diffuseColor; -}; -void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Toon -#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,j8=`BlinnPhongMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularColor = specular; -material.specularShininess = shininess; -material.specularStrength = specularStrength;`,$8=`varying vec3 vViewPosition; -struct BlinnPhongMaterial { - vec3 diffuseColor; - vec3 specularColor; - float specularShininess; - float specularStrength; -}; -void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); - reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; -} -void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,q8=`PhysicalMaterial material; -material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); -vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); -float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); -material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; -material.roughness = min( material.roughness, 1.0 ); -#ifdef IOR - material.ior = ior; - #ifdef USE_SPECULAR - float specularIntensityFactor = specularIntensity; - vec3 specularColorFactor = specularColor; - #ifdef USE_SPECULAR_COLORMAP - specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; - #endif - material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); - #else - float specularIntensityFactor = 1.0; - vec3 specularColorFactor = vec3( 1.0 ); - material.specularF90 = 1.0; - #endif - material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); -#else - material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); - material.specularF90 = 1.0; -#endif -#ifdef USE_CLEARCOAT - material.clearcoat = clearcoat; - material.clearcoatRoughness = clearcoatRoughness; - material.clearcoatF0 = vec3( 0.04 ); - material.clearcoatF90 = 1.0; - #ifdef USE_CLEARCOATMAP - material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; - #endif - #ifdef USE_CLEARCOAT_ROUGHNESSMAP - material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; - #endif - material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); - material.clearcoatRoughness += geometryRoughness; - material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); -#endif -#ifdef USE_DISPERSION - material.dispersion = dispersion; -#endif -#ifdef USE_IRIDESCENCE - material.iridescence = iridescence; - material.iridescenceIOR = iridescenceIOR; - #ifdef USE_IRIDESCENCEMAP - material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; - #endif - #ifdef USE_IRIDESCENCE_THICKNESSMAP - material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; - #else - material.iridescenceThickness = iridescenceThicknessMaximum; - #endif -#endif -#ifdef USE_SHEEN - material.sheenColor = sheenColor; - #ifdef USE_SHEEN_COLORMAP - material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; - #endif - material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); - #ifdef USE_SHEEN_ROUGHNESSMAP - material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; - #endif -#endif -#ifdef USE_ANISOTROPY - #ifdef USE_ANISOTROPYMAP - mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); - vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; - vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; - #else - vec2 anisotropyV = anisotropyVector; - #endif - material.anisotropy = length( anisotropyV ); - if( material.anisotropy == 0.0 ) { - anisotropyV = vec2( 1.0, 0.0 ); - } else { - anisotropyV /= material.anisotropy; - material.anisotropy = saturate( material.anisotropy ); - } - material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); - material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; - material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,X8=`struct PhysicalMaterial { - vec3 diffuseColor; - float roughness; - vec3 specularColor; - float specularF90; - float dispersion; - #ifdef USE_CLEARCOAT - float clearcoat; - float clearcoatRoughness; - vec3 clearcoatF0; - float clearcoatF90; - #endif - #ifdef USE_IRIDESCENCE - float iridescence; - float iridescenceIOR; - float iridescenceThickness; - vec3 iridescenceFresnel; - vec3 iridescenceF0; - #endif - #ifdef USE_SHEEN - vec3 sheenColor; - float sheenRoughness; - #endif - #ifdef IOR - float ior; - #endif - #ifdef USE_TRANSMISSION - float transmission; - float transmissionAlpha; - float thickness; - float attenuationDistance; - vec3 attenuationColor; - #endif - #ifdef USE_ANISOTROPY - float anisotropy; - float alphaT; - vec3 anisotropyT; - vec3 anisotropyB; - #endif -}; -vec3 clearcoatSpecularDirect = vec3( 0.0 ); -vec3 clearcoatSpecularIndirect = vec3( 0.0 ); -vec3 sheenSpecularDirect = vec3( 0.0 ); -vec3 sheenSpecularIndirect = vec3(0.0 ); -vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { - float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); - float x2 = x * x; - float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); - return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); -} -float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { - float a2 = pow2( alpha ); - float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); - float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); - return 0.5 / max( gv + gl, EPSILON ); -} -float D_GGX( const in float alpha, const in float dotNH ) { - float a2 = pow2( alpha ); - float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; - return RECIPROCAL_PI * a2 / pow2( denom ); -} -#ifdef USE_ANISOTROPY - float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { - float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); - float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); - float v = 0.5 / ( gv + gl ); - return saturate(v); - } - float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { - float a2 = alphaT * alphaB; - highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); - highp float v2 = dot( v, v ); - float w2 = a2 / v2; - return RECIPROCAL_PI * a2 * pow2 ( w2 ); - } -#endif -#ifdef USE_CLEARCOAT - vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { - vec3 f0 = material.clearcoatF0; - float f90 = material.clearcoatF90; - float roughness = material.clearcoatRoughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - return F * ( V * D ); - } -#endif -vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { - vec3 f0 = material.specularColor; - float f90 = material.specularF90; - float roughness = material.roughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - #ifdef USE_IRIDESCENCE - F = mix( F, material.iridescenceFresnel, material.iridescence ); - #endif - #ifdef USE_ANISOTROPY - float dotTL = dot( material.anisotropyT, lightDir ); - float dotTV = dot( material.anisotropyT, viewDir ); - float dotTH = dot( material.anisotropyT, halfDir ); - float dotBL = dot( material.anisotropyB, lightDir ); - float dotBV = dot( material.anisotropyB, viewDir ); - float dotBH = dot( material.anisotropyB, halfDir ); - float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); - float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); - #else - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - #endif - return F * ( V * D ); -} -vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { - const float LUT_SIZE = 64.0; - const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; - const float LUT_BIAS = 0.5 / LUT_SIZE; - float dotNV = saturate( dot( N, V ) ); - vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); - uv = uv * LUT_SCALE + LUT_BIAS; - return uv; -} -float LTC_ClippedSphereFormFactor( const in vec3 f ) { - float l = length( f ); - return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); -} -vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { - float x = dot( v1, v2 ); - float y = abs( x ); - float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; - float b = 3.4175940 + ( 4.1616724 + y ) * y; - float v = a / b; - float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; - return cross( v1, v2 ) * theta_sintheta; -} -vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { - vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; - vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; - vec3 lightNormal = cross( v1, v2 ); - if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); - vec3 T1, T2; - T1 = normalize( V - N * dot( V, N ) ); - T2 = - cross( N, T1 ); - mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); - vec3 coords[ 4 ]; - coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); - coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); - coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); - coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); - coords[ 0 ] = normalize( coords[ 0 ] ); - coords[ 1 ] = normalize( coords[ 1 ] ); - coords[ 2 ] = normalize( coords[ 2 ] ); - coords[ 3 ] = normalize( coords[ 3 ] ); - vec3 vectorFormFactor = vec3( 0.0 ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); - float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); - return vec3( result ); -} -#if defined( USE_SHEEN ) -float D_Charlie( float roughness, float dotNH ) { - float alpha = pow2( roughness ); - float invAlpha = 1.0 / alpha; - float cos2h = dotNH * dotNH; - float sin2h = max( 1.0 - cos2h, 0.0078125 ); - return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); -} -float V_Neubelt( float dotNV, float dotNL ) { - return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); -} -vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float D = D_Charlie( sheenRoughness, dotNH ); - float V = V_Neubelt( dotNV, dotNL ); - return sheenColor * ( D * V ); -} -#endif -float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - float r2 = roughness * roughness; - float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; - float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; - float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); - return saturate( DG * RECIPROCAL_PI ); -} -vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); - const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); - vec4 r = roughness * c0 + c1; - float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; - vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; - return fab; -} -vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { - vec2 fab = DFGApprox( normal, viewDir, roughness ); - return specularColor * fab.x + specularF90 * fab.y; -} -#ifdef USE_IRIDESCENCE -void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#else -void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#endif - vec2 fab = DFGApprox( normal, viewDir, roughness ); - #ifdef USE_IRIDESCENCE - vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); - #else - vec3 Fr = specularColor; - #endif - vec3 FssEss = Fr * fab.x + specularF90 * fab.y; - float Ess = fab.x + fab.y; - float Ems = 1.0 - Ess; - vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); - singleScatter += FssEss; - multiScatter += Fms * Ems; -} -#if NUM_RECT_AREA_LIGHTS > 0 - void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - vec3 normal = geometryNormal; - vec3 viewDir = geometryViewDir; - vec3 position = geometryPosition; - vec3 lightPos = rectAreaLight.position; - vec3 halfWidth = rectAreaLight.halfWidth; - vec3 halfHeight = rectAreaLight.halfHeight; - vec3 lightColor = rectAreaLight.color; - float roughness = material.roughness; - vec3 rectCoords[ 4 ]; - rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; - rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; - rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; - vec2 uv = LTC_Uv( normal, viewDir, roughness ); - vec4 t1 = texture2D( ltc_1, uv ); - vec4 t2 = texture2D( ltc_2, uv ); - mat3 mInv = mat3( - vec3( t1.x, 0, t1.y ), - vec3( 0, 1, 0 ), - vec3( t1.z, 0, t1.w ) - ); - vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); - reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); - reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); - } -#endif -void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - #ifdef USE_CLEARCOAT - float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); - vec3 ccIrradiance = dotNLcc * directLight.color; - clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); - #endif - #ifdef USE_SHEEN - sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); - #endif - reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { - #ifdef USE_CLEARCOAT - clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); - #endif - #ifdef USE_SHEEN - sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); - #endif - vec3 singleScattering = vec3( 0.0 ); - vec3 multiScattering = vec3( 0.0 ); - vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; - #ifdef USE_IRIDESCENCE - computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); - #else - computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); - #endif - vec3 totalScattering = singleScattering + multiScattering; - vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); - reflectedLight.indirectSpecular += radiance * singleScattering; - reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; - reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; -} -#define RE_Direct RE_Direct_Physical -#define RE_Direct_RectArea RE_Direct_RectArea_Physical -#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical -#define RE_IndirectSpecular RE_IndirectSpecular_Physical -float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { - return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,K8=` -vec3 geometryPosition = - vViewPosition; -vec3 geometryNormal = normal; -vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); -vec3 geometryClearcoatNormal = vec3( 0.0 ); -#ifdef USE_CLEARCOAT - geometryClearcoatNormal = clearcoatNormal; -#endif -#ifdef USE_IRIDESCENCE - float dotNVi = saturate( dot( normal, geometryViewDir ) ); - if ( material.iridescenceThickness == 0.0 ) { - material.iridescence = 0.0; - } else { - material.iridescence = saturate( material.iridescence ); - } - if ( material.iridescence > 0.0 ) { - material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); - material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); - } -#endif -IncidentLight directLight; -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - pointLight = pointLights[ i ]; - getPointLightInfo( pointLight, geometryPosition, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - SpotLight spotLight; - vec4 spotColor; - vec3 spotLightCoord; - bool inSpotLightMap; - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - spotLight = spotLights[ i ]; - getSpotLightInfo( spotLight, geometryPosition, directLight ); - #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX - #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS - #else - #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #endif - #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) - spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; - inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); - spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); - directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; - #endif - #undef SPOT_LIGHT_MAP_INDEX - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) - RectAreaLight rectAreaLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if defined( RE_IndirectDiffuse ) - vec3 iblIrradiance = vec3( 0.0 ); - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - #if defined( USE_LIGHT_PROBES ) - irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); - #endif - #if ( NUM_HEMI_LIGHTS > 0 ) - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - } - #pragma unroll_loop_end - #endif -#endif -#if defined( RE_IndirectSpecular ) - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,Y8=`#if defined( RE_IndirectDiffuse ) - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; - irradiance += lightMapIrradiance; - #endif - #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) - iblIrradiance += getIBLIrradiance( geometryNormal ); - #endif -#endif -#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) - #ifdef USE_ANISOTROPY - radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); - #else - radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); - #endif - #ifdef USE_CLEARCOAT - clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); - #endif -#endif`,Z8=`#if defined( RE_IndirectDiffuse ) - RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif -#if defined( RE_IndirectSpecular ) - RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,J8=`#if defined( USE_LOGDEPTHBUF ) - gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,Q8=`#if defined( USE_LOGDEPTHBUF ) - uniform float logDepthBufFC; - varying float vFragDepth; - varying float vIsPerspective; -#endif`,e6=`#ifdef USE_LOGDEPTHBUF - varying float vFragDepth; - varying float vIsPerspective; -#endif`,t6=`#ifdef USE_LOGDEPTHBUF - vFragDepth = 1.0 + gl_Position.w; - vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,n6=`#ifdef USE_MAP - vec4 sampledDiffuseColor = texture2D( map, vMapUv ); - #ifdef DECODE_VIDEO_TEXTURE - sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); - #endif - diffuseColor *= sampledDiffuseColor; -#endif`,r6=`#ifdef USE_MAP - uniform sampler2D map; -#endif`,i6=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - #if defined( USE_POINTS_UV ) - vec2 uv = vUv; - #else - vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; - #endif -#endif -#ifdef USE_MAP - diffuseColor *= texture2D( map, uv ); -#endif -#ifdef USE_ALPHAMAP - diffuseColor.a *= texture2D( alphaMap, uv ).g; -#endif`,s6=`#if defined( USE_POINTS_UV ) - varying vec2 vUv; -#else - #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - uniform mat3 uvTransform; - #endif -#endif -#ifdef USE_MAP - uniform sampler2D map; -#endif -#ifdef USE_ALPHAMAP - uniform sampler2D alphaMap; -#endif`,o6=`float metalnessFactor = metalness; -#ifdef USE_METALNESSMAP - vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); - metalnessFactor *= texelMetalness.b; -#endif`,a6=`#ifdef USE_METALNESSMAP - uniform sampler2D metalnessMap; -#endif`,c6=`#ifdef USE_INSTANCING_MORPH - float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; - } -#endif`,l6=`#if defined( USE_MORPHCOLORS ) - vColor *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - #if defined( USE_COLOR_ALPHA ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; - #elif defined( USE_COLOR ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; - #endif - } -#endif`,u6=`#ifdef USE_MORPHNORMALS - objectNormal *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; - } -#endif`,h6=`#ifdef USE_MORPHTARGETS - #ifndef USE_INSTANCING_MORPH - uniform float morphTargetBaseInfluence; - uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - #endif - uniform sampler2DArray morphTargetsTexture; - uniform ivec2 morphTargetsTextureSize; - vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { - int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; - int y = texelIndex / morphTargetsTextureSize.x; - int x = texelIndex - y * morphTargetsTextureSize.x; - ivec3 morphUV = ivec3( x, y, morphTargetIndex ); - return texelFetch( morphTargetsTexture, morphUV, 0 ); - } -#endif`,f6=`#ifdef USE_MORPHTARGETS - transformed *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; - } -#endif`,d6=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; -#ifdef FLAT_SHADED - vec3 fdx = dFdx( vViewPosition ); - vec3 fdy = dFdy( vViewPosition ); - vec3 normal = normalize( cross( fdx, fdy ) ); -#else - vec3 normal = normalize( vNormal ); - #ifdef DOUBLE_SIDED - normal *= faceDirection; - #endif -#endif -#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) - #ifdef USE_TANGENT - mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn = getTangentFrame( - vViewPosition, normal, - #if defined( USE_NORMALMAP ) - vNormalMapUv - #elif defined( USE_CLEARCOAT_NORMALMAP ) - vClearcoatNormalMapUv - #else - vUv - #endif - ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn[0] *= faceDirection; - tbn[1] *= faceDirection; - #endif -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - #ifdef USE_TANGENT - mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn2[0] *= faceDirection; - tbn2[1] *= faceDirection; - #endif -#endif -vec3 nonPerturbedNormal = normal;`,p6=`#ifdef USE_NORMALMAP_OBJECTSPACE - normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - #ifdef FLIP_SIDED - normal = - normal; - #endif - #ifdef DOUBLE_SIDED - normal = normal * faceDirection; - #endif - normal = normalize( normalMatrix * normal ); -#elif defined( USE_NORMALMAP_TANGENTSPACE ) - vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - mapN.xy *= normalScale; - normal = normalize( tbn * mapN ); -#elif defined( USE_BUMPMAP ) - normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,m6=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,g6=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,_6=`#ifndef FLAT_SHADED - vNormal = normalize( transformedNormal ); - #ifdef USE_TANGENT - vTangent = normalize( transformedTangent ); - vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); - #endif -#endif`,v6=`#ifdef USE_NORMALMAP - uniform sampler2D normalMap; - uniform vec2 normalScale; -#endif -#ifdef USE_NORMALMAP_OBJECTSPACE - uniform mat3 normalMatrix; -#endif -#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) - mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { - vec3 q0 = dFdx( eye_pos.xyz ); - vec3 q1 = dFdy( eye_pos.xyz ); - vec2 st0 = dFdx( uv.st ); - vec2 st1 = dFdy( uv.st ); - vec3 N = surf_norm; - vec3 q1perp = cross( q1, N ); - vec3 q0perp = cross( N, q0 ); - vec3 T = q1perp * st0.x + q0perp * st1.x; - vec3 B = q1perp * st0.y + q0perp * st1.y; - float det = max( dot( T, T ), dot( B, B ) ); - float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); - return mat3( T * scale, B * scale, N ); - } -#endif`,y6=`#ifdef USE_CLEARCOAT - vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,x6=`#ifdef USE_CLEARCOAT_NORMALMAP - vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; - clearcoatMapN.xy *= clearcoatNormalScale; - clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,S6=`#ifdef USE_CLEARCOATMAP - uniform sampler2D clearcoatMap; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform sampler2D clearcoatNormalMap; - uniform vec2 clearcoatNormalScale; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform sampler2D clearcoatRoughnessMap; -#endif`,E6=`#ifdef USE_IRIDESCENCEMAP - uniform sampler2D iridescenceMap; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform sampler2D iridescenceThicknessMap; -#endif`,w6=`#ifdef OPAQUE -diffuseColor.a = 1.0; -#endif -#ifdef USE_TRANSMISSION -diffuseColor.a *= material.transmissionAlpha; -#endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,b6=`vec3 packNormalToRGB( const in vec3 normal ) { - return normalize( normal ) * 0.5 + 0.5; -} -vec3 unpackRGBToNormal( const in vec3 rgb ) { - return 2.0 * rgb.xyz - 1.0; -} -const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; -const float Inv255 = 1. / 255.; -const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); -const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); -const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); -const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); -vec4 packDepthToRGBA( const in float v ) { - if( v <= 0.0 ) - return vec4( 0., 0., 0., 0. ); - if( v >= 1.0 ) - return vec4( 1., 1., 1., 1. ); - float vuf; - float af = modf( v * PackFactors.a, vuf ); - float bf = modf( vuf * ShiftRight8, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); -} -vec3 packDepthToRGB( const in float v ) { - if( v <= 0.0 ) - return vec3( 0., 0., 0. ); - if( v >= 1.0 ) - return vec3( 1., 1., 1. ); - float vuf; - float bf = modf( v * PackFactors.b, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec3( vuf * Inv255, gf * PackUpscale, bf ); -} -vec2 packDepthToRG( const in float v ) { - if( v <= 0.0 ) - return vec2( 0., 0. ); - if( v >= 1.0 ) - return vec2( 1., 1. ); - float vuf; - float gf = modf( v * 256., vuf ); - return vec2( vuf * Inv255, gf ); -} -float unpackRGBAToDepth( const in vec4 v ) { - return dot( v, UnpackFactors4 ); -} -float unpackRGBToDepth( const in vec3 v ) { - return dot( v, UnpackFactors3 ); -} -float unpackRGToDepth( const in vec2 v ) { - return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; -} -vec4 pack2HalfToRGBA( const in vec2 v ) { - vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); - return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); -} -vec2 unpackRGBATo2Half( const in vec4 v ) { - return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); -} -float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { - return ( viewZ + near ) / ( near - far ); -} -float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { - return depth * ( near - far ) - near; -} -float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { - return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); -} -float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { - return ( near * far ) / ( ( far - near ) * depth - far ); -}`,T6=`#ifdef PREMULTIPLIED_ALPHA - gl_FragColor.rgb *= gl_FragColor.a; -#endif`,A6=`vec4 mvPosition = vec4( transformed, 1.0 ); -#ifdef USE_BATCHING - mvPosition = batchingMatrix * mvPosition; -#endif -#ifdef USE_INSTANCING - mvPosition = instanceMatrix * mvPosition; -#endif -mvPosition = modelViewMatrix * mvPosition; -gl_Position = projectionMatrix * mvPosition;`,M6=`#ifdef DITHERING - gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,C6=`#ifdef DITHERING - vec3 dithering( vec3 color ) { - float grid_position = rand( gl_FragCoord.xy ); - vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); - dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); - return color + dither_shift_RGB; - } -#endif`,R6=`float roughnessFactor = roughness; -#ifdef USE_ROUGHNESSMAP - vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); - roughnessFactor *= texelRoughness.g; -#endif`,N6=`#ifdef USE_ROUGHNESSMAP - uniform sampler2D roughnessMap; -#endif`,k6=`#if NUM_SPOT_LIGHT_COORDS > 0 - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#if NUM_SPOT_LIGHT_MAPS > 0 - uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif - float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { - return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); - } - vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { - return unpackRGBATo2Half( texture2D( shadow, uv ) ); - } - float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ - float occlusion = 1.0; - vec2 distribution = texture2DDistribution( shadow, uv ); - float hard_shadow = step( compare , distribution.x ); - if (hard_shadow != 1.0 ) { - float distance = compare - distribution.x ; - float variance = max( 0.00000, distribution.y * distribution.y ); - float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); - } - return occlusion; - } - float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - float shadow = 1.0; - shadowCoord.xyz /= shadowCoord.w; - shadowCoord.z += shadowBias; - bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; - bool frustumTest = inFrustum && shadowCoord.z <= 1.0; - if ( frustumTest ) { - #if defined( SHADOWMAP_TYPE_PCF ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx0 = - texelSize.x * shadowRadius; - float dy0 = - texelSize.y * shadowRadius; - float dx1 = + texelSize.x * shadowRadius; - float dy1 = + texelSize.y * shadowRadius; - float dx2 = dx0 / 2.0; - float dy2 = dy0 / 2.0; - float dx3 = dx1 / 2.0; - float dy3 = dy1 / 2.0; - shadow = ( - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) - ) * ( 1.0 / 17.0 ); - #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx = texelSize.x; - float dy = texelSize.y; - vec2 uv = shadowCoord.xy; - vec2 f = fract( uv * shadowMapSize + 0.5 ); - uv -= f * texelSize; - shadow = ( - texture2DCompare( shadowMap, uv, shadowCoord.z ) + - texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + - texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + - mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), - f.x ) + - mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), - f.x ) + - mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), - f.y ) + - mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), - f.y ) + - mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), - f.x ), - mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), - f.x ), - f.y ) - ) * ( 1.0 / 9.0 ); - #elif defined( SHADOWMAP_TYPE_VSM ) - shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); - #else - shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } - vec2 cubeToUV( vec3 v, float texelSizeY ) { - vec3 absV = abs( v ); - float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); - absV *= scaleToCube; - v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); - vec2 planar = v.xy; - float almostATexel = 1.5 * texelSizeY; - float almostOne = 1.0 - almostATexel; - if ( absV.z >= almostOne ) { - if ( v.z > 0.0 ) - planar.x = 4.0 - v.x; - } else if ( absV.x >= almostOne ) { - float signX = sign( v.x ); - planar.x = v.z * signX + 2.0 * signX; - } else if ( absV.y >= almostOne ) { - float signY = sign( v.y ); - planar.x = v.x + 2.0 * signY + 2.0; - planar.y = v.z * signY - 2.0; - } - return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); - } - float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { - float shadow = 1.0; - vec3 lightToPosition = shadowCoord.xyz; - - float lightToPositionLength = length( lightToPosition ); - if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { - float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; - vec3 bd3D = normalize( lightToPosition ); - vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); - #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) - vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; - shadow = ( - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) - ) * ( 1.0 / 9.0 ); - #else - shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } -#endif`,I6=`#if NUM_SPOT_LIGHT_COORDS > 0 - uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif -#endif`,O6=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) - vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - vec4 shadowWorldPosition; -#endif -#if defined( USE_SHADOWMAP ) - #if NUM_DIR_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); - vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); - vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif -#endif -#if NUM_SPOT_LIGHT_COORDS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { - shadowWorldPosition = worldPosition; - #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; - #endif - vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end -#endif`,L6=`float getShadowMask() { - float shadow = 1.0; - #ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - directionalLight = directionalLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { - spotLight = spotLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - pointLight = pointLightShadows[ i ]; - shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; - } - #pragma unroll_loop_end - #endif - #endif - return shadow; -}`,P6=`#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,D6=`#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif`,U6=`#ifdef USE_SKINNING - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif`,F6=`#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - #ifdef USE_TANGENT - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - #endif -#endif`,B6=`float specularStrength; -#ifdef USE_SPECULARMAP - vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); - specularStrength = texelSpecular.r; -#else - specularStrength = 1.0; -#endif`,z6=`#ifdef USE_SPECULARMAP - uniform sampler2D specularMap; -#endif`,V6=`#if defined( TONE_MAPPING ) - gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,H6=`#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -uniform float toneMappingExposure; -vec3 LinearToneMapping( vec3 color ) { - return saturate( toneMappingExposure * color ); -} -vec3 ReinhardToneMapping( vec3 color ) { - color *= toneMappingExposure; - return saturate( color / ( vec3( 1.0 ) + color ) ); -} -vec3 CineonToneMapping( vec3 color ) { - color *= toneMappingExposure; - color = max( vec3( 0.0 ), color - 0.004 ); - return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); -} -vec3 RRTAndODTFit( vec3 v ) { - vec3 a = v * ( v + 0.0245786 ) - 0.000090537; - vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; - return a / b; -} -vec3 ACESFilmicToneMapping( vec3 color ) { - const mat3 ACESInputMat = mat3( - vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), - vec3( 0.04823, 0.01566, 0.83777 ) - ); - const mat3 ACESOutputMat = mat3( - vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), - vec3( -0.07367, -0.00605, 1.07602 ) - ); - color *= toneMappingExposure / 0.6; - color = ACESInputMat * color; - color = RRTAndODTFit( color ); - color = ACESOutputMat * color; - return saturate( color ); -} -const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( - vec3( 1.6605, - 0.1246, - 0.0182 ), - vec3( - 0.5876, 1.1329, - 0.1006 ), - vec3( - 0.0728, - 0.0083, 1.1187 ) -); -const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( - vec3( 0.6274, 0.0691, 0.0164 ), - vec3( 0.3293, 0.9195, 0.0880 ), - vec3( 0.0433, 0.0113, 0.8956 ) -); -vec3 agxDefaultContrastApprox( vec3 x ) { - vec3 x2 = x * x; - vec3 x4 = x2 * x2; - return + 15.5 * x4 * x2 - - 40.14 * x4 * x - + 31.96 * x4 - - 6.868 * x2 * x - + 0.4298 * x2 - + 0.1191 * x - - 0.00232; -} -vec3 AgXToneMapping( vec3 color ) { - const mat3 AgXInsetMatrix = mat3( - vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), - vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), - vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) - ); - const mat3 AgXOutsetMatrix = mat3( - vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), - vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), - vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) - ); - const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; - color *= toneMappingExposure; - color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; - color = AgXInsetMatrix * color; - color = max( color, 1e-10 ); color = log2( color ); - color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); - color = clamp( color, 0.0, 1.0 ); - color = agxDefaultContrastApprox( color ); - color = AgXOutsetMatrix * color; - color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); - color = LINEAR_REC2020_TO_LINEAR_SRGB * color; - color = clamp( color, 0.0, 1.0 ); - return color; -} -vec3 NeutralToneMapping( vec3 color ) { - const float StartCompression = 0.8 - 0.04; - const float Desaturation = 0.15; - color *= toneMappingExposure; - float x = min( color.r, min( color.g, color.b ) ); - float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; - color -= offset; - float peak = max( color.r, max( color.g, color.b ) ); - if ( peak < StartCompression ) return color; - float d = 1. - StartCompression; - float newPeak = 1. - d * d / ( peak + d - StartCompression ); - color *= newPeak / peak; - float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); - return mix( color, vec3( newPeak ), g ); -} -vec3 CustomToneMapping( vec3 color ) { return color; }`,G6=`#ifdef USE_TRANSMISSION - material.transmission = transmission; - material.transmissionAlpha = 1.0; - material.thickness = thickness; - material.attenuationDistance = attenuationDistance; - material.attenuationColor = attenuationColor; - #ifdef USE_TRANSMISSIONMAP - material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; - #endif - #ifdef USE_THICKNESSMAP - material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; - #endif - vec3 pos = vWorldPosition; - vec3 v = normalize( cameraPosition - pos ); - vec3 n = inverseTransformDirection( normal, viewMatrix ); - vec4 transmitted = getIBLVolumeRefraction( - n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, - pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, - material.attenuationColor, material.attenuationDistance ); - material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); - totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,W6=`#ifdef USE_TRANSMISSION - uniform float transmission; - uniform float thickness; - uniform float attenuationDistance; - uniform vec3 attenuationColor; - #ifdef USE_TRANSMISSIONMAP - uniform sampler2D transmissionMap; - #endif - #ifdef USE_THICKNESSMAP - uniform sampler2D thicknessMap; - #endif - uniform vec2 transmissionSamplerSize; - uniform sampler2D transmissionSamplerMap; - uniform mat4 modelMatrix; - uniform mat4 projectionMatrix; - varying vec3 vWorldPosition; - float w0( float a ) { - return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); - } - float w1( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); - } - float w2( float a ){ - return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); - } - float w3( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * a ); - } - float g0( float a ) { - return w0( a ) + w1( a ); - } - float g1( float a ) { - return w2( a ) + w3( a ); - } - float h0( float a ) { - return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); - } - float h1( float a ) { - return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); - } - vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { - uv = uv * texelSize.zw + 0.5; - vec2 iuv = floor( uv ); - vec2 fuv = fract( uv ); - float g0x = g0( fuv.x ); - float g1x = g1( fuv.x ); - float h0x = h0( fuv.x ); - float h1x = h1( fuv.x ); - float h0y = h0( fuv.y ); - float h1y = h1( fuv.y ); - vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + - g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); - } - vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { - vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); - vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); - vec2 fLodSizeInv = 1.0 / fLodSize; - vec2 cLodSizeInv = 1.0 / cLodSize; - vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); - vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); - return mix( fSample, cSample, fract( lod ) ); - } - vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { - vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); - vec3 modelScale; - modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); - modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); - modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); - return normalize( refractionVector ) * thickness * modelScale; - } - float applyIorToRoughness( const in float roughness, const in float ior ) { - return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); - } - vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { - float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); - return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); - } - vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { - if ( isinf( attenuationDistance ) ) { - return vec3( 1.0 ); - } else { - vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; - vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; - } - } - vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, - const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, - const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, - const in vec3 attenuationColor, const in float attenuationDistance ) { - vec4 transmittedLight; - vec3 transmittance; - #ifdef USE_DISPERSION - float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; - vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); - for ( int i = 0; i < 3; i ++ ) { - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - - vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); - transmittedLight[ i ] = transmissionSample[ i ]; - transmittedLight.a += transmissionSample.a; - transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; - } - transmittedLight.a /= 3.0; - - #else - - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); - transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); - - #endif - vec3 attenuatedColor = transmittance * transmittedLight.rgb; - vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); - float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; - return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); - } -#endif`,j6=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - varying vec2 vNormalMapUv; -#endif -#ifdef USE_EMISSIVEMAP - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_SPECULARMAP - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,$6=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - uniform mat3 mapTransform; - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - uniform mat3 alphaMapTransform; - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - uniform mat3 lightMapTransform; - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - uniform mat3 aoMapTransform; - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - uniform mat3 bumpMapTransform; - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - uniform mat3 normalMapTransform; - varying vec2 vNormalMapUv; -#endif -#ifdef USE_DISPLACEMENTMAP - uniform mat3 displacementMapTransform; - varying vec2 vDisplacementMapUv; -#endif -#ifdef USE_EMISSIVEMAP - uniform mat3 emissiveMapTransform; - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - uniform mat3 metalnessMapTransform; - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - uniform mat3 roughnessMapTransform; - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - uniform mat3 anisotropyMapTransform; - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - uniform mat3 clearcoatMapTransform; - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform mat3 clearcoatNormalMapTransform; - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform mat3 clearcoatRoughnessMapTransform; - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - uniform mat3 sheenColorMapTransform; - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - uniform mat3 sheenRoughnessMapTransform; - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - uniform mat3 iridescenceMapTransform; - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform mat3 iridescenceThicknessMapTransform; - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SPECULARMAP - uniform mat3 specularMapTransform; - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - uniform mat3 specularColorMapTransform; - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - uniform mat3 specularIntensityMapTransform; - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,q6=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - vUv = vec3( uv, 1 ).xy; -#endif -#ifdef USE_MAP - vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ALPHAMAP - vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_LIGHTMAP - vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_AOMAP - vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_BUMPMAP - vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_NORMALMAP - vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_DISPLACEMENTMAP - vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_EMISSIVEMAP - vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_METALNESSMAP - vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ROUGHNESSMAP - vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ANISOTROPYMAP - vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOATMAP - vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCEMAP - vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_COLORMAP - vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULARMAP - vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_COLORMAP - vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_TRANSMISSIONMAP - vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_THICKNESSMAP - vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; -#endif`,X6=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 - vec4 worldPosition = vec4( transformed, 1.0 ); - #ifdef USE_BATCHING - worldPosition = batchingMatrix * worldPosition; - #endif - #ifdef USE_INSTANCING - worldPosition = instanceMatrix * worldPosition; - #endif - worldPosition = modelMatrix * worldPosition; -#endif`;const K6=`varying vec2 vUv; -uniform mat3 uvTransform; -void main() { - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,Y6=`uniform sampler2D t2D; -uniform float backgroundIntensity; -varying vec2 vUv; -void main() { - vec4 texColor = texture2D( t2D, vUv ); - #ifdef DECODE_VIDEO_TEXTURE - texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,Z6=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,J6=`#ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; -#elif defined( ENVMAP_TYPE_CUBE_UV ) - uniform sampler2D envMap; -#endif -uniform float flipEnvMap; -uniform float backgroundBlurriness; -uniform float backgroundIntensity; -uniform mat3 backgroundRotation; -varying vec3 vWorldDirection; -#include -void main() { - #ifdef ENVMAP_TYPE_CUBE - vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); - #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); - #else - vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,Q6=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,eV=`uniform samplerCube tCube; -uniform float tFlip; -uniform float opacity; -varying vec3 vWorldDirection; -void main() { - vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); - gl_FragColor = texColor; - gl_FragColor.a *= opacity; - #include - #include -}`,tV=`#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - #include - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vHighPrecisionZW = gl_Position.zw; -}`,nV=`#if DEPTH_PACKING == 3200 - uniform float opacity; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - vec4 diffuseColor = vec4( 1.0 ); - #include - #if DEPTH_PACKING == 3200 - diffuseColor.a = opacity; - #endif - #include - #include - #include - #include - #include - float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; - #if DEPTH_PACKING == 3200 - gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); - #elif DEPTH_PACKING == 3201 - gl_FragColor = packDepthToRGBA( fragCoordZ ); - #elif DEPTH_PACKING == 3202 - gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); - #elif DEPTH_PACKING == 3203 - gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); - #endif -}`,rV=`#define DISTANCE -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vWorldPosition = worldPosition.xyz; -}`,iV=`#define DISTANCE -uniform vec3 referencePosition; -uniform float nearDistance; -uniform float farDistance; -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -#include -void main () { - vec4 diffuseColor = vec4( 1.0 ); - #include - #include - #include - #include - #include - float dist = length( vWorldPosition - referencePosition ); - dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); - dist = saturate( dist ); - gl_FragColor = packDepthToRGBA( dist ); -}`,sV=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include -}`,oV=`uniform sampler2D tEquirect; -varying vec3 vWorldDirection; -#include -void main() { - vec3 direction = normalize( vWorldDirection ); - vec2 sampleUV = equirectUv( direction ); - gl_FragColor = texture2D( tEquirect, sampleUV ); - #include - #include -}`,aV=`uniform float scale; -attribute float lineDistance; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vLineDistance = scale * lineDistance; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,cV=`uniform vec3 diffuse; -uniform float opacity; -uniform float dashSize; -uniform float totalSize; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - if ( mod( vLineDistance, totalSize ) > dashSize ) { - discard; - } - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,lV=`#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) - #include - #include - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,uV=`uniform vec3 diffuse; -uniform float opacity; -#ifndef FLAT_SHADED - varying vec3 vNormal; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; - #else - reflectedLight.indirectDiffuse += vec3( 1.0 ); - #endif - #include - reflectedLight.indirectDiffuse *= diffuseColor.rgb; - vec3 outgoingLight = reflectedLight.indirectDiffuse; - #include - #include - #include - #include - #include - #include - #include -}`,hV=`#define LAMBERT -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,fV=`#define LAMBERT -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,dV=`#define MATCAP -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; -}`,pV=`#define MATCAP -uniform vec3 diffuse; -uniform float opacity; -uniform sampler2D matcap; -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 viewDir = normalize( vViewPosition ); - vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); - vec3 y = cross( viewDir, x ); - vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; - #ifdef USE_MATCAP - vec4 matcapColor = texture2D( matcap, uv ); - #else - vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); - #endif - vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; - #include - #include - #include - #include - #include - #include -}`,mV=`#define NORMAL -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - vViewPosition = - mvPosition.xyz; -#endif -}`,gV=`#define NORMAL -uniform float opacity; -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); - #include - #include - #include - #include - gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); - #ifdef OPAQUE - gl_FragColor.a = 1.0; - #endif -}`,_V=`#define PHONG -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,vV=`#define PHONG -uniform vec3 diffuse; -uniform vec3 emissive; -uniform vec3 specular; -uniform float shininess; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,yV=`#define STANDARD -varying vec3 vViewPosition; -#ifdef USE_TRANSMISSION - varying vec3 vWorldPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -#ifdef USE_TRANSMISSION - vWorldPosition = worldPosition.xyz; -#endif -}`,xV=`#define STANDARD -#ifdef PHYSICAL - #define IOR - #define USE_SPECULAR -#endif -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float roughness; -uniform float metalness; -uniform float opacity; -#ifdef IOR - uniform float ior; -#endif -#ifdef USE_SPECULAR - uniform float specularIntensity; - uniform vec3 specularColor; - #ifdef USE_SPECULAR_COLORMAP - uniform sampler2D specularColorMap; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - uniform sampler2D specularIntensityMap; - #endif -#endif -#ifdef USE_CLEARCOAT - uniform float clearcoat; - uniform float clearcoatRoughness; -#endif -#ifdef USE_DISPERSION - uniform float dispersion; -#endif -#ifdef USE_IRIDESCENCE - uniform float iridescence; - uniform float iridescenceIOR; - uniform float iridescenceThicknessMinimum; - uniform float iridescenceThicknessMaximum; -#endif -#ifdef USE_SHEEN - uniform vec3 sheenColor; - uniform float sheenRoughness; - #ifdef USE_SHEEN_COLORMAP - uniform sampler2D sheenColorMap; - #endif - #ifdef USE_SHEEN_ROUGHNESSMAP - uniform sampler2D sheenRoughnessMap; - #endif -#endif -#ifdef USE_ANISOTROPY - uniform vec2 anisotropyVector; - #ifdef USE_ANISOTROPYMAP - uniform sampler2D anisotropyMap; - #endif -#endif -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; - vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; - #include - vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; - #ifdef USE_SHEEN - float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); - outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; - #endif - #ifdef USE_CLEARCOAT - float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); - vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); - outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; - #endif - #include - #include - #include - #include - #include - #include -}`,SV=`#define TOON -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -}`,EV=`#define TOON -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include -}`,wV=`uniform float size; -uniform float scale; -#include -#include -#include -#include -#include -#include -#ifdef USE_POINTS_UV - varying vec2 vUv; - uniform mat3 uvTransform; -#endif -void main() { - #ifdef USE_POINTS_UV - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - #endif - #include - #include - #include - #include - #include - #include - gl_PointSize = size; - #ifdef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); - #endif - #include - #include - #include - #include -}`,bV=`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,TV=`#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,AV=`uniform vec3 color; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); - #include - #include - #include -}`,MV=`uniform float rotation; -uniform vec2 center; -#include -#include -#include -#include -#include -void main() { - #include - vec4 mvPosition = modelViewMatrix[ 3 ]; - vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); - #ifndef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) scale *= - mvPosition.z; - #endif - vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; - vec2 rotatedPosition; - rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; - rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; - mvPosition.xy += rotatedPosition; - gl_Position = projectionMatrix * mvPosition; - #include - #include - #include -}`,CV=`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include -}`,Ft={alphahash_fragment:Yz,alphahash_pars_fragment:Zz,alphamap_fragment:Jz,alphamap_pars_fragment:Qz,alphatest_fragment:e8,alphatest_pars_fragment:t8,aomap_fragment:n8,aomap_pars_fragment:r8,batching_pars_vertex:i8,batching_vertex:s8,begin_vertex:o8,beginnormal_vertex:a8,bsdfs:c8,iridescence_fragment:l8,bumpmap_pars_fragment:u8,clipping_planes_fragment:h8,clipping_planes_pars_fragment:f8,clipping_planes_pars_vertex:d8,clipping_planes_vertex:p8,color_fragment:m8,color_pars_fragment:g8,color_pars_vertex:_8,color_vertex:v8,common:y8,cube_uv_reflection_fragment:x8,defaultnormal_vertex:S8,displacementmap_pars_vertex:E8,displacementmap_vertex:w8,emissivemap_fragment:b8,emissivemap_pars_fragment:T8,colorspace_fragment:A8,colorspace_pars_fragment:M8,envmap_fragment:C8,envmap_common_pars_fragment:R8,envmap_pars_fragment:N8,envmap_pars_vertex:k8,envmap_physical_pars_fragment:H8,envmap_vertex:I8,fog_vertex:O8,fog_pars_vertex:L8,fog_fragment:P8,fog_pars_fragment:D8,gradientmap_pars_fragment:U8,lightmap_pars_fragment:F8,lights_lambert_fragment:B8,lights_lambert_pars_fragment:z8,lights_pars_begin:V8,lights_toon_fragment:G8,lights_toon_pars_fragment:W8,lights_phong_fragment:j8,lights_phong_pars_fragment:$8,lights_physical_fragment:q8,lights_physical_pars_fragment:X8,lights_fragment_begin:K8,lights_fragment_maps:Y8,lights_fragment_end:Z8,logdepthbuf_fragment:J8,logdepthbuf_pars_fragment:Q8,logdepthbuf_pars_vertex:e6,logdepthbuf_vertex:t6,map_fragment:n6,map_pars_fragment:r6,map_particle_fragment:i6,map_particle_pars_fragment:s6,metalnessmap_fragment:o6,metalnessmap_pars_fragment:a6,morphinstance_vertex:c6,morphcolor_vertex:l6,morphnormal_vertex:u6,morphtarget_pars_vertex:h6,morphtarget_vertex:f6,normal_fragment_begin:d6,normal_fragment_maps:p6,normal_pars_fragment:m6,normal_pars_vertex:g6,normal_vertex:_6,normalmap_pars_fragment:v6,clearcoat_normal_fragment_begin:y6,clearcoat_normal_fragment_maps:x6,clearcoat_pars_fragment:S6,iridescence_pars_fragment:E6,opaque_fragment:w6,packing:b6,premultiplied_alpha_fragment:T6,project_vertex:A6,dithering_fragment:M6,dithering_pars_fragment:C6,roughnessmap_fragment:R6,roughnessmap_pars_fragment:N6,shadowmap_pars_fragment:k6,shadowmap_pars_vertex:I6,shadowmap_vertex:O6,shadowmask_pars_fragment:L6,skinbase_vertex:P6,skinning_pars_vertex:D6,skinning_vertex:U6,skinnormal_vertex:F6,specularmap_fragment:B6,specularmap_pars_fragment:z6,tonemapping_fragment:V6,tonemapping_pars_fragment:H6,transmission_fragment:G6,transmission_pars_fragment:W6,uv_pars_fragment:j6,uv_pars_vertex:$6,uv_vertex:q6,worldpos_vertex:X6,background_vert:K6,background_frag:Y6,backgroundCube_vert:Z6,backgroundCube_frag:J6,cube_vert:Q6,cube_frag:eV,depth_vert:tV,depth_frag:nV,distanceRGBA_vert:rV,distanceRGBA_frag:iV,equirect_vert:sV,equirect_frag:oV,linedashed_vert:aV,linedashed_frag:cV,meshbasic_vert:lV,meshbasic_frag:uV,meshlambert_vert:hV,meshlambert_frag:fV,meshmatcap_vert:dV,meshmatcap_frag:pV,meshnormal_vert:mV,meshnormal_frag:gV,meshphong_vert:_V,meshphong_frag:vV,meshphysical_vert:yV,meshphysical_frag:xV,meshtoon_vert:SV,meshtoon_frag:EV,points_vert:wV,points_frag:bV,shadow_vert:TV,shadow_frag:AV,sprite_vert:MV,sprite_frag:CV},Xe={common:{diffuse:{value:new ln(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Dt},alphaMap:{value:null},alphaMapTransform:{value:new Dt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Dt}},envmap:{envMap:{value:null},envMapRotation:{value:new Dt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Dt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Dt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Dt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Dt},normalScale:{value:new St(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Dt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Dt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Dt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Dt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ln(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new ln(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Dt},alphaTest:{value:0},uvTransform:{value:new Dt}},sprite:{diffuse:{value:new ln(16777215)},opacity:{value:1},center:{value:new St(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Dt},alphaMap:{value:null},alphaMapTransform:{value:new Dt},alphaTest:{value:0}}},ua={basic:{uniforms:Ii([Xe.common,Xe.specularmap,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.fog]),vertexShader:Ft.meshbasic_vert,fragmentShader:Ft.meshbasic_frag},lambert:{uniforms:Ii([Xe.common,Xe.specularmap,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.fog,Xe.lights,{emissive:{value:new ln(0)}}]),vertexShader:Ft.meshlambert_vert,fragmentShader:Ft.meshlambert_frag},phong:{uniforms:Ii([Xe.common,Xe.specularmap,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.fog,Xe.lights,{emissive:{value:new ln(0)},specular:{value:new ln(1118481)},shininess:{value:30}}]),vertexShader:Ft.meshphong_vert,fragmentShader:Ft.meshphong_frag},standard:{uniforms:Ii([Xe.common,Xe.envmap,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.roughnessmap,Xe.metalnessmap,Xe.fog,Xe.lights,{emissive:{value:new ln(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ft.meshphysical_vert,fragmentShader:Ft.meshphysical_frag},toon:{uniforms:Ii([Xe.common,Xe.aomap,Xe.lightmap,Xe.emissivemap,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.gradientmap,Xe.fog,Xe.lights,{emissive:{value:new ln(0)}}]),vertexShader:Ft.meshtoon_vert,fragmentShader:Ft.meshtoon_frag},matcap:{uniforms:Ii([Xe.common,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,Xe.fog,{matcap:{value:null}}]),vertexShader:Ft.meshmatcap_vert,fragmentShader:Ft.meshmatcap_frag},points:{uniforms:Ii([Xe.points,Xe.fog]),vertexShader:Ft.points_vert,fragmentShader:Ft.points_frag},dashed:{uniforms:Ii([Xe.common,Xe.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ft.linedashed_vert,fragmentShader:Ft.linedashed_frag},depth:{uniforms:Ii([Xe.common,Xe.displacementmap]),vertexShader:Ft.depth_vert,fragmentShader:Ft.depth_frag},normal:{uniforms:Ii([Xe.common,Xe.bumpmap,Xe.normalmap,Xe.displacementmap,{opacity:{value:1}}]),vertexShader:Ft.meshnormal_vert,fragmentShader:Ft.meshnormal_frag},sprite:{uniforms:Ii([Xe.sprite,Xe.fog]),vertexShader:Ft.sprite_vert,fragmentShader:Ft.sprite_frag},background:{uniforms:{uvTransform:{value:new Dt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ft.background_vert,fragmentShader:Ft.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Dt}},vertexShader:Ft.backgroundCube_vert,fragmentShader:Ft.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ft.cube_vert,fragmentShader:Ft.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ft.equirect_vert,fragmentShader:Ft.equirect_frag},distanceRGBA:{uniforms:Ii([Xe.common,Xe.displacementmap,{referencePosition:{value:new xe},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ft.distanceRGBA_vert,fragmentShader:Ft.distanceRGBA_frag},shadow:{uniforms:Ii([Xe.lights,Xe.fog,{color:{value:new ln(0)},opacity:{value:1}}]),vertexShader:Ft.shadow_vert,fragmentShader:Ft.shadow_frag}};ua.physical={uniforms:Ii([ua.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Dt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Dt},clearcoatNormalScale:{value:new St(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Dt},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Dt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Dt},sheen:{value:0},sheenColor:{value:new ln(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Dt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Dt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Dt},transmissionSamplerSize:{value:new St},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Dt},attenuationDistance:{value:0},attenuationColor:{value:new ln(0)},specularColor:{value:new ln(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Dt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Dt},anisotropyVector:{value:new St},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Dt}}]),vertexShader:Ft.meshphysical_vert,fragmentShader:Ft.meshphysical_frag};const h0={r:0,b:0,g:0},du=new kc,RV=new ar;function NV(t,e,n,r,i,s,o){const a=new ln(0);let c=s===!0?0:1,l,u,h=null,p=0,m=null;function g(S){let E=S.isScene===!0?S.background:null;return E&&E.isTexture&&(E=(S.backgroundBlurriness>0?n:e).get(E)),E}function v(S){let E=!1;const b=g(S);b===null?_(a,c):b&&b.isColor&&(_(b,1),E=!0);const N=t.xr.getEnvironmentBlendMode();N==="additive"?r.buffers.color.setClear(0,0,0,1,o):N==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(t.autoClear||E)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))}function y(S,E){const b=g(E);b&&(b.isCubeTexture||b.mapping===Iv)?(u===void 0&&(u=new Ao(new Qp(1,1,1),new Gi({name:"BackgroundCubeMaterial",uniforms:Ff(ua.backgroundCube.uniforms),vertexShader:ua.backgroundCube.vertexShader,fragmentShader:ua.backgroundCube.fragmentShader,side:ri,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(N,R,M){this.matrixWorld.copyPosition(M.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(u)),du.copy(E.backgroundRotation),du.x*=-1,du.y*=-1,du.z*=-1,b.isCubeTexture&&b.isRenderTargetTexture===!1&&(du.y*=-1,du.z*=-1),u.material.uniforms.envMap.value=b,u.material.uniforms.flipEnvMap.value=b.isCubeTexture&&b.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=E.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(RV.makeRotationFromEuler(du)),u.material.toneMapped=hn.getTransfer(b.colorSpace)!==Tn,(h!==b||p!==b.version||m!==t.toneMapping)&&(u.material.needsUpdate=!0,h=b,p=b.version,m=t.toneMapping),u.layers.enableAll(),S.unshift(u,u.geometry,u.material,0,0,null)):b&&b.isTexture&&(l===void 0&&(l=new Ao(new em(2,2),new Gi({name:"BackgroundMaterial",uniforms:Ff(ua.background.uniforms),vertexShader:ua.background.vertexShader,fragmentShader:ua.background.fragmentShader,side:Nc,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=b,l.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,l.material.toneMapped=hn.getTransfer(b.colorSpace)!==Tn,b.matrixAutoUpdate===!0&&b.updateMatrix(),l.material.uniforms.uvTransform.value.copy(b.matrix),(h!==b||p!==b.version||m!==t.toneMapping)&&(l.material.needsUpdate=!0,h=b,p=b.version,m=t.toneMapping),l.layers.enableAll(),S.unshift(l,l.geometry,l.material,0,0,null))}function _(S,E){S.getRGB(h0,CO(t)),r.buffers.color.setClear(h0.r,h0.g,h0.b,E,o)}return{getClearColor:function(){return a},setClearColor:function(S,E=1){a.set(S),c=E,_(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(S){c=S,_(a,c)},render:v,addToRenderList:y}}function kV(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),r={},i=p(null);let s=i,o=!1;function a(I,U,L,P,T){let H=!1;const V=h(P,L,U);s!==V&&(s=V,l(s.object)),H=m(I,P,L,T),H&&g(I,P,L,T),T!==null&&e.update(T,t.ELEMENT_ARRAY_BUFFER),(H||o)&&(o=!1,b(I,U,L,P),T!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.get(T).buffer))}function c(){return t.createVertexArray()}function l(I){return t.bindVertexArray(I)}function u(I){return t.deleteVertexArray(I)}function h(I,U,L){const P=L.wireframe===!0;let T=r[I.id];T===void 0&&(T={},r[I.id]=T);let H=T[U.id];H===void 0&&(H={},T[U.id]=H);let V=H[P];return V===void 0&&(V=p(c()),H[P]=V),V}function p(I){const U=[],L=[],P=[];for(let T=0;T=0){const K=T[z];let j=H[z];if(j===void 0&&(z==="instanceMatrix"&&I.instanceMatrix&&(j=I.instanceMatrix),z==="instanceColor"&&I.instanceColor&&(j=I.instanceColor)),K===void 0||K.attribute!==j||j&&K.data!==j.data)return!0;V++}return s.attributesNum!==V||s.index!==P}function g(I,U,L,P){const T={},H=U.attributes;let V=0;const B=L.getAttributes();for(const z in B)if(B[z].location>=0){let K=H[z];K===void 0&&(z==="instanceMatrix"&&I.instanceMatrix&&(K=I.instanceMatrix),z==="instanceColor"&&I.instanceColor&&(K=I.instanceColor));const j={};j.attribute=K,K&&K.data&&(j.data=K.data),T[z]=j,V++}s.attributes=T,s.attributesNum=V,s.index=P}function v(){const I=s.newAttributes;for(let U=0,L=I.length;U=0){let W=T[B];if(W===void 0&&(B==="instanceMatrix"&&I.instanceMatrix&&(W=I.instanceMatrix),B==="instanceColor"&&I.instanceColor&&(W=I.instanceColor)),W!==void 0){const K=W.normalized,j=W.itemSize,Y=e.get(W);if(Y===void 0)continue;const ge=Y.buffer,Q=Y.type,re=Y.bytesPerElement,we=Q===t.INT||Q===t.UNSIGNED_INT||W.gpuType===mb;if(W.isInterleavedBufferAttribute){const Ae=W.data,Ee=Ae.stride,Le=W.offset;if(Ae.isInstancedInterleavedBuffer){for(let He=0;He0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";M="mediump"}return M==="mediump"&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=n.precision!==void 0?n.precision:"highp";const u=c(l);u!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",u,"instead."),l=u);const h=n.logarithmicDepthBuffer===!0,p=n.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),m=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),g=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=t.getParameter(t.MAX_TEXTURE_SIZE),y=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),_=t.getParameter(t.MAX_VERTEX_ATTRIBS),S=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),E=t.getParameter(t.MAX_VARYING_VECTORS),b=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),N=g>0,R=t.getParameter(t.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:h,reverseDepthBuffer:p,maxTextures:m,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:y,maxAttributes:_,maxVertexUniforms:S,maxVaryings:E,maxFragmentUniforms:b,vertexTextures:N,maxSamples:R}}function LV(t){const e=this;let n=null,r=0,i=!1,s=!1;const o=new Eo,a=new Dt,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(h,p){const m=h.length!==0||p||r!==0||i;return i=p,r=h.length,m},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,p){n=u(h,p,0)},this.setState=function(h,p,m){const g=h.clippingPlanes,v=h.clipIntersection,y=h.clipShadows,_=t.get(h);if(!i||g===null||g.length===0||s&&!y)s?u(null):l();else{const S=s?0:r,E=S*4;let b=_.clippingState||null;c.value=b,b=u(g,p,E,m);for(let N=0;N!==E;++N)b[N]=n[N];_.clippingState=b,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=S}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function u(h,p,m,g){const v=h!==null?h.length:0;let y=null;if(v!==0){if(y=c.value,g!==!0||y===null){const _=m+v*4,S=p.matrixWorldInverse;a.getNormalMatrix(S),(y===null||y.length<_)&&(y=new Float32Array(_));for(let E=0,b=m;E!==v;++E,b+=4)o.copy(h[E]).applyMatrix4(S,a),o.normal.toArray(y,b),y[b+3]=o.constant}c.value=y,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,y}}function PV(t){let e=new WeakMap;function n(o,a){return a===QS?o.mapping=Df:a===eE&&(o.mapping=Uf),o}function r(o){if(o&&o.isTexture){const a=o.mapping;if(a===QS||a===eE)if(e.has(o)){const c=e.get(o).texture;return n(c,o.mapping)}else{const c=o.image;if(c&&c.height>0){const l=new $z(c.height);return l.fromEquirectangularTexture(t,o),e.set(o,l),o.addEventListener("dispose",i),n(l.texture,o.mapping)}else return null}}return o}function i(o){const a=o.target;a.removeEventListener("dispose",i);const c=e.get(a);c!==void 0&&(e.delete(a),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}class Uv extends Dv{constructor(e=-1,n=1,r=1,i=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=n,this.top=r,this.bottom=i,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,n,r,i,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),n=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let s=r-e,o=r+e,a=i+n,c=i-n;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=l*this.view.offsetX,o=s+l*this.view.width,a-=u*this.view.offsetY,c=a-u*this.view.height}this.projectionMatrix.makeOrthographic(s,o,a,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.zoom=this.zoom,n.object.left=this.left,n.object.right=this.right,n.object.top=this.top,n.object.bottom=this.bottom,n.object.near=this.near,n.object.far=this.far,this.view!==null&&(n.object.view=Object.assign({},this.view)),n}}const ff=4,SR=[.125,.215,.35,.446,.526,.582],Nu=20,I1=new Uv,ER=new ln;let O1=null,L1=0,P1=0,D1=!1;const wu=(1+Math.sqrt(5))/2,Kh=1/wu,wR=[new xe(-wu,Kh,0),new xe(wu,Kh,0),new xe(-Kh,0,wu),new xe(Kh,0,wu),new xe(0,wu,-Kh),new xe(0,wu,Kh),new xe(-1,1,-1),new xe(1,1,-1),new xe(-1,1,1),new xe(1,1,1)];class bR{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,n=0,r=.1,i=100){O1=this._renderer.getRenderTarget(),L1=this._renderer.getActiveCubeFace(),P1=this._renderer.getActiveMipmapLevel(),D1=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,r,i,s),n>0&&this._blur(s,0,0,n),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,n=null){return this._fromTexture(e,n)}fromCubemap(e,n=null){return this._fromTexture(e,n)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=MR(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=AR(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?E:0,E,E),u.setRenderTarget(i),v&&u.render(g,a),u.render(e,a)}g.geometry.dispose(),g.material.dispose(),u.toneMapping=p,u.autoClear=h,e.background=y}_textureToCubeUV(e,n){const r=this._renderer,i=e.mapping===Df||e.mapping===Uf;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=MR()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=AR());const s=i?this._cubemapMaterial:this._equirectMaterial,o=new Ao(this._lodPlanes[0],s),a=s.uniforms;a.envMap.value=e;const c=this._cubeSize;f0(n,0,0,3*c,2*c),r.setRenderTarget(n),r.render(o,I1)}_applyPMREM(e){const n=this._renderer,r=n.autoClear;n.autoClear=!1;const i=this._lodPlanes.length;for(let s=1;sNu&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${y} samples when the maximum is set to ${Nu}`);const _=[];let S=0;for(let M=0;ME-ff?i-E+ff:0),R=4*(this._cubeSize-b);f0(n,N,R,3*b,2*b),c.setRenderTarget(n),c.render(h,I1)}}function DV(t){const e=[],n=[],r=[];let i=t;const s=t-ff+1+SR.length;for(let o=0;ot-ff?c=SR[o-t+ff-1]:o===0&&(c=0),r.push(c);const l=1/(a-2),u=-l,h=1+l,p=[u,u,h,u,h,h,u,u,h,h,u,h],m=6,g=6,v=3,y=2,_=1,S=new Float32Array(v*g*m),E=new Float32Array(y*g*m),b=new Float32Array(_*g*m);for(let R=0;R2?0:-1,C=[M,O,0,M+2/3,O,0,M+2/3,O+1,0,M,O,0,M+2/3,O+1,0,M,O+1,0];S.set(C,v*g*R),E.set(p,y*g*R);const I=[R,R,R,R,R,R];b.set(I,_*g*R)}const N=new Bo;N.setAttribute("position",new Jn(S,v)),N.setAttribute("uv",new Jn(E,y)),N.setAttribute("faceIndex",new Jn(b,_)),e.push(N),i>ff&&i--}return{lodPlanes:e,sizeLods:n,sigmas:r}}function TR(t,e,n){const r=new Us(t,e,n);return r.texture.mapping=Iv,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function f0(t,e,n,r,i){t.viewport.set(e,n,r,i),t.scissor.set(e,n,r,i)}function UV(t,e,n){const r=new Float32Array(Nu),i=new xe(0,1,0);return new Gi({name:"SphericalGaussianBlur",defines:{n:Nu,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:wb(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - uniform int samples; - uniform float weights[ n ]; - uniform bool latitudinal; - uniform float dTheta; - uniform float mipInt; - uniform vec3 poleAxis; - - #define ENVMAP_TYPE_CUBE_UV - #include - - vec3 getSample( float theta, vec3 axis ) { - - float cosTheta = cos( theta ); - // Rodrigues' axis-angle rotation - vec3 sampleDirection = vOutputDirection * cosTheta - + cross( axis, vOutputDirection ) * sin( theta ) - + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); - - return bilinearCubeUV( envMap, sampleDirection, mipInt ); - - } - - void main() { - - vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); - - if ( all( equal( axis, vec3( 0.0 ) ) ) ) { - - axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); - - } - - axis = normalize( axis ); - - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); - - for ( int i = 1; i < n; i++ ) { - - if ( i >= samples ) { - - break; - - } - - float theta = dTheta * float( i ); - gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); - gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); - - } - - } - `,blending:Ro,depthTest:!1,depthWrite:!1})}function AR(){return new Gi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:wb(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - - #include - - void main() { - - vec3 outputDirection = normalize( vOutputDirection ); - vec2 uv = equirectUv( outputDirection ); - - gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); - - } - `,blending:Ro,depthTest:!1,depthWrite:!1})}function MR(){return new Gi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:wb(),fragmentShader:` - - precision mediump float; - precision mediump int; - - uniform float flipEnvMap; - - varying vec3 vOutputDirection; - - uniform samplerCube envMap; - - void main() { - - gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); - - } - `,blending:Ro,depthTest:!1,depthWrite:!1})}function wb(){return` - - precision mediump float; - precision mediump int; - - attribute float faceIndex; - - varying vec3 vOutputDirection; - - // RH coordinate system; PMREM face-indexing convention - vec3 getDirection( vec2 uv, float face ) { - - uv = 2.0 * uv - 1.0; - - vec3 direction = vec3( uv, 1.0 ); - - if ( face == 0.0 ) { - - direction = direction.zyx; // ( 1, v, u ) pos x - - } else if ( face == 1.0 ) { - - direction = direction.xzy; - direction.xz *= -1.0; // ( -u, 1, -v ) pos y - - } else if ( face == 2.0 ) { - - direction.x *= -1.0; // ( -u, v, 1 ) pos z - - } else if ( face == 3.0 ) { - - direction = direction.zyx; - direction.xz *= -1.0; // ( -1, v, -u ) neg x - - } else if ( face == 4.0 ) { - - direction = direction.xzy; - direction.xy *= -1.0; // ( -u, -1, v ) neg y - - } else if ( face == 5.0 ) { - - direction.z *= -1.0; // ( u, v, -1 ) neg z - - } - - return direction; - - } - - void main() { - - vOutputDirection = getDirection( uv, faceIndex ); - gl_Position = vec4( position, 1.0 ); - - } - `}function FV(t){let e=new WeakMap,n=null;function r(a){if(a&&a.isTexture){const c=a.mapping,l=c===QS||c===eE,u=c===Df||c===Uf;if(l||u){let h=e.get(a);const p=h!==void 0?h.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==p)return n===null&&(n=new bR(t)),h=l?n.fromEquirectangular(a,h):n.fromCubemap(a,h),h.texture.pmremVersion=a.pmremVersion,e.set(a,h),h.texture;if(h!==void 0)return h.texture;{const m=a.image;return l&&m&&m.height>0||u&&m&&i(m)?(n===null&&(n=new bR(t)),h=l?n.fromEquirectangular(a):n.fromCubemap(a),h.texture.pmremVersion=a.pmremVersion,e.set(a,h),a.addEventListener("dispose",s),h.texture):null}}}return a}function i(a){let c=0;const l=6;for(let u=0;ue.maxTextureSize&&(R=Math.ceil(N/e.maxTextureSize),N=e.maxTextureSize);const M=new Float32Array(N*R*4*h),O=new bO(M,N,R,h);O.type=_a,O.needsUpdate=!0;const C=b*4;for(let U=0;U0)return t;const i=e*n;let s=RR[i];if(s===void 0&&(s=new Float32Array(i),RR[i]=s),e!==0){r.toArray(s,0);for(let o=1,a=0;o!==e;++o)a+=n,t[o].toArray(s,a)}return s}function Vr(t,e){if(t.length!==e.length)return!1;for(let n=0,r=t.length;n":" "} ${a}: ${n[o]}`)}return r.join(` -`)}const DR=new Dt;function FH(t){hn._getMatrix(DR,hn.workingColorSpace,t);const e=`mat3( ${DR.elements.map(n=>n.toFixed(4))} )`;switch(hn.getTransfer(t)){case Lv:return[e,"LinearTransferOETF"];case Tn:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",t),[e,"LinearTransferOETF"]}}function UR(t,e,n){const r=t.getShaderParameter(e,t.COMPILE_STATUS),i=t.getShaderInfoLog(e).trim();if(r&&i==="")return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const o=parseInt(s[1]);return n.toUpperCase()+` - -`+i+` - -`+UH(t.getShaderSource(e),o)}else return i}function BH(t,e){const n=FH(e);return[`vec4 ${t}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(` -`)}function zH(t,e){let n;switch(e){case G5:n="Linear";break;case W5:n="Reinhard";break;case j5:n="Cineon";break;case cO:n="ACESFilmic";break;case q5:n="AgX";break;case X5:n="Neutral";break;case $5:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const d0=new xe;function VH(){hn.getLuminanceCoefficients(d0);const t=d0.x.toFixed(4),e=d0.y.toFixed(4),n=d0.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${t}, ${e}, ${n} );`," return dot( weights, rgb );","}"].join(` -`)}function HH(t){return[t.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",t.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(rp).join(` -`)}function GH(t){const e=[];for(const n in t){const r=t[n];r!==!1&&e.push("#define "+n+" "+r)}return e.join(` -`)}function WH(t,e){const n={},r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function RE(t){return t.replace(jH,qH)}const $H=new Map;function qH(t,e){let n=Ft[e];if(n===void 0){const r=$H.get(e);if(r!==void 0)n=Ft[r],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,r);else throw new Error("Can not resolve #include <"+e+">")}return RE(n)}const XH=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function zR(t){return t.replace(XH,KH)}function KH(t,e,n,r){let i="";for(let s=parseInt(e);s0&&(y+=` -`),_=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g].filter(rp).join(` -`),_.length>0&&(_+=` -`)):(y=[VR(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&n.flatShading===!1?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` -`].filter(rp).join(` -`),_=[VR(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+l:"",n.envMap?"#define "+u:"",n.envMap?"#define "+h:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==ya?"#define TONE_MAPPING":"",n.toneMapping!==ya?Ft.tonemapping_pars_fragment:"",n.toneMapping!==ya?zH("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Ft.colorspace_pars_fragment,BH("linearToOutputTexel",n.outputColorSpace),VH(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",` -`].filter(rp).join(` -`)),o=RE(o),o=FR(o,n),o=BR(o,n),a=RE(a),a=FR(a,n),a=BR(a,n),o=zR(o),a=zR(a),n.isRawShaderMaterial!==!0&&(S=`#version 300 es -`,y=[m,"#define attribute in","#define varying out","#define texture2D texture"].join(` -`)+` -`+y,_=["#define varying in",n.glslVersion===QC?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===QC?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` -`)+` -`+_);const E=S+y+o,b=S+_+a,N=PR(i,i.VERTEX_SHADER,E),R=PR(i,i.FRAGMENT_SHADER,b);i.attachShader(v,N),i.attachShader(v,R),n.index0AttributeName!==void 0?i.bindAttribLocation(v,0,n.index0AttributeName):n.morphTargets===!0&&i.bindAttribLocation(v,0,"position"),i.linkProgram(v);function M(U){if(t.debug.checkShaderErrors){const L=i.getProgramInfoLog(v).trim(),P=i.getShaderInfoLog(N).trim(),T=i.getShaderInfoLog(R).trim();let H=!0,V=!0;if(i.getProgramParameter(v,i.LINK_STATUS)===!1)if(H=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(i,v,N,R);else{const B=UR(i,N,"vertex"),z=UR(i,R,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(v,i.VALIDATE_STATUS)+` - -Material Name: `+U.name+` -Material Type: `+U.type+` - -Program Info Log: `+L+` -`+B+` -`+z)}else L!==""?console.warn("THREE.WebGLProgram: Program Info Log:",L):(P===""||T==="")&&(V=!1);V&&(U.diagnostics={runnable:H,programLog:L,vertexShader:{log:P,prefix:y},fragmentShader:{log:T,prefix:_}})}i.deleteShader(N),i.deleteShader(R),O=new i_(i,v),C=WH(i,v)}let O;this.getUniforms=function(){return O===void 0&&M(this),O};let C;this.getAttributes=function(){return C===void 0&&M(this),C};let I=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return I===!1&&(I=i.getProgramParameter(v,PH)),I},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(v),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=DH++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=N,this.fragmentShader=R,this}let nG=0;class rG{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(n),s=this._getShaderStage(r),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(e){const n=this.materialCache.get(e);for(const r of n)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const n=this.materialCache;let r=n.get(e);return r===void 0&&(r=new Set,n.set(e,r)),r}_getShaderStage(e){const n=this.shaderCache;let r=n.get(e);return r===void 0&&(r=new iG(e),n.set(e,r)),r}}class iG{constructor(e){this.id=nG++,this.code=e,this.usedTimes=0}}function sG(t,e,n,r,i,s,o){const a=new bf,c=new rG,l=new Set,u=[],h=i.logarithmicDepthBuffer,p=i.vertexTextures;let m=i.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(C){return l.add(C),C===0?"uv":`uv${C}`}function y(C,I,U,L,P){const T=L.fog,H=P.geometry,V=C.isMeshStandardMaterial?L.environment:null,B=(C.isMeshStandardMaterial?n:e).get(C.envMap||V),z=B&&B.mapping===Iv?B.image.height:null,W=g[C.type];C.precision!==null&&(m=i.getMaxPrecision(C.precision),m!==C.precision&&console.warn("THREE.WebGLProgram.getParameters:",C.precision,"not supported, using",m,"instead."));const K=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,j=K!==void 0?K.length:0;let Y=0;H.morphAttributes.position!==void 0&&(Y=1),H.morphAttributes.normal!==void 0&&(Y=2),H.morphAttributes.color!==void 0&&(Y=3);let ge,Q,re,we;if(W){const fn=ua[W];ge=fn.vertexShader,Q=fn.fragmentShader}else ge=C.vertexShader,Q=C.fragmentShader,c.update(C),re=c.getVertexShaderID(C),we=c.getFragmentShaderID(C);const Ae=t.getRenderTarget(),Ee=t.state.buffers.depth.getReversed(),Le=P.isInstancedMesh===!0,He=P.isBatchedMesh===!0,qe=!!C.map,it=!!C.matcap,De=!!B,A=!!C.aoMap,ie=!!C.lightMap,te=!!C.bumpMap,X=!!C.normalMap,$=!!C.displacementMap,ne=!!C.emissiveMap,ae=!!C.metalnessMap,G=!!C.roughnessMap,D=C.anisotropy>0,ee=C.clearcoat>0,he=C.dispersion>0,ce=C.iridescence>0,_e=C.sheen>0,ze=C.transmission>0,Oe=D&&!!C.anisotropyMap,Ge=ee&&!!C.clearcoatMap,Lt=ee&&!!C.clearcoatNormalMap,Pe=ee&&!!C.clearcoatRoughnessMap,nt=ce&&!!C.iridescenceMap,et=ce&&!!C.iridescenceThicknessMap,yt=_e&&!!C.sheenColorMap,rt=_e&&!!C.sheenRoughnessMap,Ct=!!C.specularMap,Rt=!!C.specularColorMap,Sn=!!C.specularIntensityMap,le=ze&&!!C.transmissionMap,je=ze&&!!C.thicknessMap,Ce=!!C.gradientMap,ke=!!C.alphaMap,$e=C.alphaTest>0,Je=!!C.alphaHash,Nt=!!C.extensions;let Wn=ya;C.toneMapped&&(Ae===null||Ae.isXRRenderTarget===!0)&&(Wn=t.toneMapping);const Nr={shaderID:W,shaderType:C.type,shaderName:C.name,vertexShader:ge,fragmentShader:Q,defines:C.defines,customVertexShaderID:re,customFragmentShaderID:we,isRawShaderMaterial:C.isRawShaderMaterial===!0,glslVersion:C.glslVersion,precision:m,batching:He,batchingColor:He&&P._colorsTexture!==null,instancing:Le,instancingColor:Le&&P.instanceColor!==null,instancingMorph:Le&&P.morphTexture!==null,supportsVertexTextures:p,outputColorSpace:Ae===null?t.outputColorSpace:Ae.isXRRenderTarget===!0?Ae.texture.colorSpace:jl,alphaToCoverage:!!C.alphaToCoverage,map:qe,matcap:it,envMap:De,envMapMode:De&&B.mapping,envMapCubeUVHeight:z,aoMap:A,lightMap:ie,bumpMap:te,normalMap:X,displacementMap:p&&$,emissiveMap:ne,normalMapObjectSpace:X&&C.normalMapType===Z5,normalMapTangentSpace:X&&C.normalMapType===xO,metalnessMap:ae,roughnessMap:G,anisotropy:D,anisotropyMap:Oe,clearcoat:ee,clearcoatMap:Ge,clearcoatNormalMap:Lt,clearcoatRoughnessMap:Pe,dispersion:he,iridescence:ce,iridescenceMap:nt,iridescenceThicknessMap:et,sheen:_e,sheenColorMap:yt,sheenRoughnessMap:rt,specularMap:Ct,specularColorMap:Rt,specularIntensityMap:Sn,transmission:ze,transmissionMap:le,thicknessMap:je,gradientMap:Ce,opaque:C.transparent===!1&&C.blending===Sf&&C.alphaToCoverage===!1,alphaMap:ke,alphaTest:$e,alphaHash:Je,combine:C.combine,mapUv:qe&&v(C.map.channel),aoMapUv:A&&v(C.aoMap.channel),lightMapUv:ie&&v(C.lightMap.channel),bumpMapUv:te&&v(C.bumpMap.channel),normalMapUv:X&&v(C.normalMap.channel),displacementMapUv:$&&v(C.displacementMap.channel),emissiveMapUv:ne&&v(C.emissiveMap.channel),metalnessMapUv:ae&&v(C.metalnessMap.channel),roughnessMapUv:G&&v(C.roughnessMap.channel),anisotropyMapUv:Oe&&v(C.anisotropyMap.channel),clearcoatMapUv:Ge&&v(C.clearcoatMap.channel),clearcoatNormalMapUv:Lt&&v(C.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Pe&&v(C.clearcoatRoughnessMap.channel),iridescenceMapUv:nt&&v(C.iridescenceMap.channel),iridescenceThicknessMapUv:et&&v(C.iridescenceThicknessMap.channel),sheenColorMapUv:yt&&v(C.sheenColorMap.channel),sheenRoughnessMapUv:rt&&v(C.sheenRoughnessMap.channel),specularMapUv:Ct&&v(C.specularMap.channel),specularColorMapUv:Rt&&v(C.specularColorMap.channel),specularIntensityMapUv:Sn&&v(C.specularIntensityMap.channel),transmissionMapUv:le&&v(C.transmissionMap.channel),thicknessMapUv:je&&v(C.thicknessMap.channel),alphaMapUv:ke&&v(C.alphaMap.channel),vertexTangents:!!H.attributes.tangent&&(X||D),vertexColors:C.vertexColors,vertexAlphas:C.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,pointsUvs:P.isPoints===!0&&!!H.attributes.uv&&(qe||ke),fog:!!T,useFog:C.fog===!0,fogExp2:!!T&&T.isFogExp2,flatShading:C.flatShading===!0,sizeAttenuation:C.sizeAttenuation===!0,logarithmicDepthBuffer:h,reverseDepthBuffer:Ee,skinning:P.isSkinnedMesh===!0,morphTargets:H.morphAttributes.position!==void 0,morphNormals:H.morphAttributes.normal!==void 0,morphColors:H.morphAttributes.color!==void 0,morphTargetsCount:j,morphTextureStride:Y,numDirLights:I.directional.length,numPointLights:I.point.length,numSpotLights:I.spot.length,numSpotLightMaps:I.spotLightMap.length,numRectAreaLights:I.rectArea.length,numHemiLights:I.hemi.length,numDirLightShadows:I.directionalShadowMap.length,numPointLightShadows:I.pointShadowMap.length,numSpotLightShadows:I.spotShadowMap.length,numSpotLightShadowsWithMaps:I.numSpotLightShadowsWithMaps,numLightProbes:I.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:C.dithering,shadowMapEnabled:t.shadowMap.enabled&&U.length>0,shadowMapType:t.shadowMap.type,toneMapping:Wn,decodeVideoTexture:qe&&C.map.isVideoTexture===!0&&hn.getTransfer(C.map.colorSpace)===Tn,decodeVideoTextureEmissive:ne&&C.emissiveMap.isVideoTexture===!0&&hn.getTransfer(C.emissiveMap.colorSpace)===Tn,premultipliedAlpha:C.premultipliedAlpha,doubleSided:C.side===Ns,flipSided:C.side===ri,useDepthPacking:C.depthPacking>=0,depthPacking:C.depthPacking||0,index0AttributeName:C.index0AttributeName,extensionClipCullDistance:Nt&&C.extensions.clipCullDistance===!0&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Nt&&C.extensions.multiDraw===!0||He)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:C.customProgramCacheKey()};return Nr.vertexUv1s=l.has(1),Nr.vertexUv2s=l.has(2),Nr.vertexUv3s=l.has(3),l.clear(),Nr}function _(C){const I=[];if(C.shaderID?I.push(C.shaderID):(I.push(C.customVertexShaderID),I.push(C.customFragmentShaderID)),C.defines!==void 0)for(const U in C.defines)I.push(U),I.push(C.defines[U]);return C.isRawShaderMaterial===!1&&(S(I,C),E(I,C),I.push(t.outputColorSpace)),I.push(C.customProgramCacheKey),I.join()}function S(C,I){C.push(I.precision),C.push(I.outputColorSpace),C.push(I.envMapMode),C.push(I.envMapCubeUVHeight),C.push(I.mapUv),C.push(I.alphaMapUv),C.push(I.lightMapUv),C.push(I.aoMapUv),C.push(I.bumpMapUv),C.push(I.normalMapUv),C.push(I.displacementMapUv),C.push(I.emissiveMapUv),C.push(I.metalnessMapUv),C.push(I.roughnessMapUv),C.push(I.anisotropyMapUv),C.push(I.clearcoatMapUv),C.push(I.clearcoatNormalMapUv),C.push(I.clearcoatRoughnessMapUv),C.push(I.iridescenceMapUv),C.push(I.iridescenceThicknessMapUv),C.push(I.sheenColorMapUv),C.push(I.sheenRoughnessMapUv),C.push(I.specularMapUv),C.push(I.specularColorMapUv),C.push(I.specularIntensityMapUv),C.push(I.transmissionMapUv),C.push(I.thicknessMapUv),C.push(I.combine),C.push(I.fogExp2),C.push(I.sizeAttenuation),C.push(I.morphTargetsCount),C.push(I.morphAttributeCount),C.push(I.numDirLights),C.push(I.numPointLights),C.push(I.numSpotLights),C.push(I.numSpotLightMaps),C.push(I.numHemiLights),C.push(I.numRectAreaLights),C.push(I.numDirLightShadows),C.push(I.numPointLightShadows),C.push(I.numSpotLightShadows),C.push(I.numSpotLightShadowsWithMaps),C.push(I.numLightProbes),C.push(I.shadowMapType),C.push(I.toneMapping),C.push(I.numClippingPlanes),C.push(I.numClipIntersection),C.push(I.depthPacking)}function E(C,I){a.disableAll(),I.supportsVertexTextures&&a.enable(0),I.instancing&&a.enable(1),I.instancingColor&&a.enable(2),I.instancingMorph&&a.enable(3),I.matcap&&a.enable(4),I.envMap&&a.enable(5),I.normalMapObjectSpace&&a.enable(6),I.normalMapTangentSpace&&a.enable(7),I.clearcoat&&a.enable(8),I.iridescence&&a.enable(9),I.alphaTest&&a.enable(10),I.vertexColors&&a.enable(11),I.vertexAlphas&&a.enable(12),I.vertexUv1s&&a.enable(13),I.vertexUv2s&&a.enable(14),I.vertexUv3s&&a.enable(15),I.vertexTangents&&a.enable(16),I.anisotropy&&a.enable(17),I.alphaHash&&a.enable(18),I.batching&&a.enable(19),I.dispersion&&a.enable(20),I.batchingColor&&a.enable(21),C.push(a.mask),a.disableAll(),I.fog&&a.enable(0),I.useFog&&a.enable(1),I.flatShading&&a.enable(2),I.logarithmicDepthBuffer&&a.enable(3),I.reverseDepthBuffer&&a.enable(4),I.skinning&&a.enable(5),I.morphTargets&&a.enable(6),I.morphNormals&&a.enable(7),I.morphColors&&a.enable(8),I.premultipliedAlpha&&a.enable(9),I.shadowMapEnabled&&a.enable(10),I.doubleSided&&a.enable(11),I.flipSided&&a.enable(12),I.useDepthPacking&&a.enable(13),I.dithering&&a.enable(14),I.transmission&&a.enable(15),I.sheen&&a.enable(16),I.opaque&&a.enable(17),I.pointsUvs&&a.enable(18),I.decodeVideoTexture&&a.enable(19),I.decodeVideoTextureEmissive&&a.enable(20),I.alphaToCoverage&&a.enable(21),C.push(a.mask)}function b(C){const I=g[C.type];let U;if(I){const L=ua[I];U=Hz.clone(L.uniforms)}else U=C.uniforms;return U}function N(C,I){let U;for(let L=0,P=u.length;L0?r.push(_):m.transparent===!0?i.push(_):n.push(_)}function c(h,p,m,g,v,y){const _=o(h,p,m,g,v,y);m.transmission>0?r.unshift(_):m.transparent===!0?i.unshift(_):n.unshift(_)}function l(h,p){n.length>1&&n.sort(h||aG),r.length>1&&r.sort(p||HR),i.length>1&&i.sort(p||HR)}function u(){for(let h=e,p=t.length;h=s.length?(o=new GR,s.push(o)):o=s[i],o}function n(){t=new WeakMap}return{get:e,dispose:n}}function lG(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new xe,color:new ln};break;case"SpotLight":n={position:new xe,direction:new xe,color:new ln,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new xe,color:new ln,distance:0,decay:0};break;case"HemisphereLight":n={direction:new xe,skyColor:new ln,groundColor:new ln};break;case"RectAreaLight":n={color:new ln,position:new xe,halfWidth:new xe,halfHeight:new xe};break}return t[e.id]=n,n}}}function uG(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new St};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new St};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new St,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let hG=0;function fG(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function dG(t){const e=new lG,n=uG(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)r.probe.push(new xe);const i=new xe,s=new ar,o=new ar;function a(l){let u=0,h=0,p=0;for(let C=0;C<9;C++)r.probe[C].set(0,0,0);let m=0,g=0,v=0,y=0,_=0,S=0,E=0,b=0,N=0,R=0,M=0;l.sort(fG);for(let C=0,I=l.length;C0&&(t.has("OES_texture_float_linear")===!0?(r.rectAreaLTC1=Xe.LTC_FLOAT_1,r.rectAreaLTC2=Xe.LTC_FLOAT_2):(r.rectAreaLTC1=Xe.LTC_HALF_1,r.rectAreaLTC2=Xe.LTC_HALF_2)),r.ambient[0]=u,r.ambient[1]=h,r.ambient[2]=p;const O=r.hash;(O.directionalLength!==m||O.pointLength!==g||O.spotLength!==v||O.rectAreaLength!==y||O.hemiLength!==_||O.numDirectionalShadows!==S||O.numPointShadows!==E||O.numSpotShadows!==b||O.numSpotMaps!==N||O.numLightProbes!==M)&&(r.directional.length=m,r.spot.length=v,r.rectArea.length=y,r.point.length=g,r.hemi.length=_,r.directionalShadow.length=S,r.directionalShadowMap.length=S,r.pointShadow.length=E,r.pointShadowMap.length=E,r.spotShadow.length=b,r.spotShadowMap.length=b,r.directionalShadowMatrix.length=S,r.pointShadowMatrix.length=E,r.spotLightMatrix.length=b+N-R,r.spotLightMap.length=N,r.numSpotLightShadowsWithMaps=R,r.numLightProbes=M,O.directionalLength=m,O.pointLength=g,O.spotLength=v,O.rectAreaLength=y,O.hemiLength=_,O.numDirectionalShadows=S,O.numPointShadows=E,O.numSpotShadows=b,O.numSpotMaps=N,O.numLightProbes=M,r.version=hG++)}function c(l,u){let h=0,p=0,m=0,g=0,v=0;const y=u.matrixWorldInverse;for(let _=0,S=l.length;_=o.length?(a=new WR(t),o.push(a)):a=o[s],a}function r(){e=new WeakMap}return{get:n,dispose:r}}class mG extends Vc{static get type(){return"MeshDepthMaterial"}constructor(e){super(),this.isMeshDepthMaterial=!0,this.depthPacking=ah,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class gG extends Vc{static get type(){return"MeshDistanceMaterial"}constructor(e){super(),this.isMeshDistanceMaterial=!0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const _G=`void main() { - gl_Position = vec4( position, 1.0 ); -}`,vG=`uniform sampler2D shadow_pass; -uniform vec2 resolution; -uniform float radius; -#include -void main() { - const float samples = float( VSM_SAMPLES ); - float mean = 0.0; - float squared_mean = 0.0; - float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); - float uvStart = samples <= 1.0 ? 0.0 : - 1.0; - for ( float i = 0.0; i < samples; i ++ ) { - float uvOffset = uvStart + i * uvStride; - #ifdef HORIZONTAL_PASS - vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); - mean += distribution.x; - squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; - #else - float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); - mean += depth; - squared_mean += depth * depth; - #endif - } - mean = mean / samples; - squared_mean = squared_mean / samples; - float std_dev = sqrt( squared_mean - mean * mean ); - gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); -}`;function yG(t,e,n){let r=new NO;const i=new St,s=new St,o=new gr,a=new mG({depthPacking:Y5}),c=new gG,l={},u=n.maxTextureSize,h={[Nc]:ri,[ri]:Nc,[Ns]:Ns},p=new Gi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new St},radius:{value:4}},vertexShader:_G,fragmentShader:vG}),m=p.clone();m.defines.HORIZONTAL_PASS=1;const g=new Bo;g.setAttribute("position",new Jn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Ao(g,p),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=pb;let _=this.type;this.render=function(R,M,O){if(y.enabled===!1||y.autoUpdate===!1&&y.needsUpdate===!1||R.length===0)return;const C=t.getRenderTarget(),I=t.getActiveCubeFace(),U=t.getActiveMipmapLevel(),L=t.state;L.setBlending(Ro),L.buffers.color.setClear(1,1,1,1),L.buffers.depth.setTest(!0),L.setScissorTest(!1);const P=_!==ca&&this.type===ca,T=_===ca&&this.type!==ca;for(let H=0,V=R.length;Hu||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/W.x),i.x=s.x*W.x,z.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/W.y),i.y=s.y*W.y,z.mapSize.y=s.y)),z.map===null||P===!0||T===!0){const j=this.type!==ca?{minFilter:vr,magFilter:vr}:{};z.map!==null&&z.map.dispose(),z.map=new Us(i.x,i.y,j),z.map.texture.name=B.name+".shadowMap",z.camera.updateProjectionMatrix()}t.setRenderTarget(z.map),t.clear();const K=z.getViewportCount();for(let j=0;j0||M.map&&M.alphaTest>0){const L=I.uuid,P=M.uuid;let T=l[L];T===void 0&&(T={},l[L]=T);let H=T[P];H===void 0&&(H=I.clone(),T[P]=H,M.addEventListener("dispose",N)),I=H}if(I.visible=M.visible,I.wireframe=M.wireframe,C===ca?I.side=M.shadowSide!==null?M.shadowSide:M.side:I.side=M.shadowSide!==null?M.shadowSide:h[M.side],I.alphaMap=M.alphaMap,I.alphaTest=M.alphaTest,I.map=M.map,I.clipShadows=M.clipShadows,I.clippingPlanes=M.clippingPlanes,I.clipIntersection=M.clipIntersection,I.displacementMap=M.displacementMap,I.displacementScale=M.displacementScale,I.displacementBias=M.displacementBias,I.wireframeLinewidth=M.wireframeLinewidth,I.linewidth=M.linewidth,O.isPointLight===!0&&I.isMeshDistanceMaterial===!0){const L=t.properties.get(I);L.light=O}return I}function b(R,M,O,C,I){if(R.visible===!1)return;if(R.layers.test(M.layers)&&(R.isMesh||R.isLine||R.isPoints)&&(R.castShadow||R.receiveShadow&&I===ca)&&(!R.frustumCulled||r.intersectsObject(R))){R.modelViewMatrix.multiplyMatrices(O.matrixWorldInverse,R.matrixWorld);const P=e.update(R),T=R.material;if(Array.isArray(T)){const H=P.groups;for(let V=0,B=H.length;V=1):z.indexOf("OpenGL ES")!==-1&&(B=parseFloat(/^OpenGL ES (\d)/.exec(z)[1]),V=B>=2);let W=null,K={};const j=t.getParameter(t.SCISSOR_BOX),Y=t.getParameter(t.VIEWPORT),ge=new gr().fromArray(j),Q=new gr().fromArray(Y);function re(le,je,Ce,ke){const $e=new Uint8Array(4),Je=t.createTexture();t.bindTexture(le,Je),t.texParameteri(le,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(le,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let Nt=0;Nt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new St,u=new WeakMap;let h;const p=new WeakMap;let m=!1;try{m=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(G,D){return m?new OffscreenCanvas(G,D):Tp("canvas")}function v(G,D,ee){let he=1;const ce=ae(G);if((ce.width>ee||ce.height>ee)&&(he=ee/Math.max(ce.width,ce.height)),he<1)if(typeof HTMLImageElement<"u"&&G instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&G instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&G instanceof ImageBitmap||typeof VideoFrame<"u"&&G instanceof VideoFrame){const _e=Math.floor(he*ce.width),ze=Math.floor(he*ce.height);h===void 0&&(h=g(_e,ze));const Oe=D?g(_e,ze):h;return Oe.width=_e,Oe.height=ze,Oe.getContext("2d").drawImage(G,0,0,_e,ze),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+ce.width+"x"+ce.height+") to ("+_e+"x"+ze+")."),Oe}else return"data"in G&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+ce.width+"x"+ce.height+")."),G;return G}function y(G){return G.generateMipmaps}function _(G){t.generateMipmap(G)}function S(G){return G.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:G.isWebGL3DRenderTarget?t.TEXTURE_3D:G.isWebGLArrayRenderTarget||G.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function E(G,D,ee,he,ce=!1){if(G!==null){if(t[G]!==void 0)return t[G];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+G+"'")}let _e=D;if(D===t.RED&&(ee===t.FLOAT&&(_e=t.R32F),ee===t.HALF_FLOAT&&(_e=t.R16F),ee===t.UNSIGNED_BYTE&&(_e=t.R8)),D===t.RED_INTEGER&&(ee===t.UNSIGNED_BYTE&&(_e=t.R8UI),ee===t.UNSIGNED_SHORT&&(_e=t.R16UI),ee===t.UNSIGNED_INT&&(_e=t.R32UI),ee===t.BYTE&&(_e=t.R8I),ee===t.SHORT&&(_e=t.R16I),ee===t.INT&&(_e=t.R32I)),D===t.RG&&(ee===t.FLOAT&&(_e=t.RG32F),ee===t.HALF_FLOAT&&(_e=t.RG16F),ee===t.UNSIGNED_BYTE&&(_e=t.RG8)),D===t.RG_INTEGER&&(ee===t.UNSIGNED_BYTE&&(_e=t.RG8UI),ee===t.UNSIGNED_SHORT&&(_e=t.RG16UI),ee===t.UNSIGNED_INT&&(_e=t.RG32UI),ee===t.BYTE&&(_e=t.RG8I),ee===t.SHORT&&(_e=t.RG16I),ee===t.INT&&(_e=t.RG32I)),D===t.RGB_INTEGER&&(ee===t.UNSIGNED_BYTE&&(_e=t.RGB8UI),ee===t.UNSIGNED_SHORT&&(_e=t.RGB16UI),ee===t.UNSIGNED_INT&&(_e=t.RGB32UI),ee===t.BYTE&&(_e=t.RGB8I),ee===t.SHORT&&(_e=t.RGB16I),ee===t.INT&&(_e=t.RGB32I)),D===t.RGBA_INTEGER&&(ee===t.UNSIGNED_BYTE&&(_e=t.RGBA8UI),ee===t.UNSIGNED_SHORT&&(_e=t.RGBA16UI),ee===t.UNSIGNED_INT&&(_e=t.RGBA32UI),ee===t.BYTE&&(_e=t.RGBA8I),ee===t.SHORT&&(_e=t.RGBA16I),ee===t.INT&&(_e=t.RGBA32I)),D===t.RGB&&ee===t.UNSIGNED_INT_5_9_9_9_REV&&(_e=t.RGB9_E5),D===t.RGBA){const ze=ce?Lv:hn.getTransfer(he);ee===t.FLOAT&&(_e=t.RGBA32F),ee===t.HALF_FLOAT&&(_e=t.RGBA16F),ee===t.UNSIGNED_BYTE&&(_e=ze===Tn?t.SRGB8_ALPHA8:t.RGBA8),ee===t.UNSIGNED_SHORT_4_4_4_4&&(_e=t.RGBA4),ee===t.UNSIGNED_SHORT_5_5_5_1&&(_e=t.RGB5_A1)}return(_e===t.R16F||_e===t.R32F||_e===t.RG16F||_e===t.RG32F||_e===t.RGBA16F||_e===t.RGBA32F)&&e.get("EXT_color_buffer_float"),_e}function b(G,D){let ee;return G?D===null||D===Il||D===ju?ee=t.DEPTH24_STENCIL8:D===_a?ee=t.DEPTH32F_STENCIL8:D===wp&&(ee=t.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):D===null||D===Il||D===ju?ee=t.DEPTH_COMPONENT24:D===_a?ee=t.DEPTH_COMPONENT32F:D===wp&&(ee=t.DEPTH_COMPONENT16),ee}function N(G,D){return y(G)===!0||G.isFramebufferTexture&&G.minFilter!==vr&&G.minFilter!==is?Math.log2(Math.max(D.width,D.height))+1:G.mipmaps!==void 0&&G.mipmaps.length>0?G.mipmaps.length:G.isCompressedTexture&&Array.isArray(G.image)?D.mipmaps.length:1}function R(G){const D=G.target;D.removeEventListener("dispose",R),O(D),D.isVideoTexture&&u.delete(D)}function M(G){const D=G.target;D.removeEventListener("dispose",M),I(D)}function O(G){const D=r.get(G);if(D.__webglInit===void 0)return;const ee=G.source,he=p.get(ee);if(he){const ce=he[D.__cacheKey];ce.usedTimes--,ce.usedTimes===0&&C(G),Object.keys(he).length===0&&p.delete(ee)}r.remove(G)}function C(G){const D=r.get(G);t.deleteTexture(D.__webglTexture);const ee=G.source,he=p.get(ee);delete he[D.__cacheKey],o.memory.textures--}function I(G){const D=r.get(G);if(G.depthTexture&&(G.depthTexture.dispose(),r.remove(G.depthTexture)),G.isWebGLCubeRenderTarget)for(let he=0;he<6;he++){if(Array.isArray(D.__webglFramebuffer[he]))for(let ce=0;ce=i.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+G+" texture units while this GPU supports only "+i.maxTextures),U+=1,G}function T(G){const D=[];return D.push(G.wrapS),D.push(G.wrapT),D.push(G.wrapR||0),D.push(G.magFilter),D.push(G.minFilter),D.push(G.anisotropy),D.push(G.internalFormat),D.push(G.format),D.push(G.type),D.push(G.generateMipmaps),D.push(G.premultiplyAlpha),D.push(G.flipY),D.push(G.unpackAlignment),D.push(G.colorSpace),D.join()}function H(G,D){const ee=r.get(G);if(G.isVideoTexture&&$(G),G.isRenderTargetTexture===!1&&G.version>0&&ee.__version!==G.version){const he=G.image;if(he===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(he.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Q(ee,G,D);return}}n.bindTexture(t.TEXTURE_2D,ee.__webglTexture,t.TEXTURE0+D)}function V(G,D){const ee=r.get(G);if(G.version>0&&ee.__version!==G.version){Q(ee,G,D);return}n.bindTexture(t.TEXTURE_2D_ARRAY,ee.__webglTexture,t.TEXTURE0+D)}function B(G,D){const ee=r.get(G);if(G.version>0&&ee.__version!==G.version){Q(ee,G,D);return}n.bindTexture(t.TEXTURE_3D,ee.__webglTexture,t.TEXTURE0+D)}function z(G,D){const ee=r.get(G);if(G.version>0&&ee.__version!==G.version){re(ee,G,D);return}n.bindTexture(t.TEXTURE_CUBE_MAP,ee.__webglTexture,t.TEXTURE0+D)}const W={[tE]:t.REPEAT,[Ou]:t.CLAMP_TO_EDGE,[nE]:t.MIRRORED_REPEAT},K={[vr]:t.NEAREST,[K5]:t.NEAREST_MIPMAP_NEAREST,[qg]:t.NEAREST_MIPMAP_LINEAR,[is]:t.LINEAR,[h1]:t.LINEAR_MIPMAP_NEAREST,[Lu]:t.LINEAR_MIPMAP_LINEAR},j={[J5]:t.NEVER,[iz]:t.ALWAYS,[Q5]:t.LESS,[SO]:t.LEQUAL,[ez]:t.EQUAL,[rz]:t.GEQUAL,[tz]:t.GREATER,[nz]:t.NOTEQUAL};function Y(G,D){if(D.type===_a&&e.has("OES_texture_float_linear")===!1&&(D.magFilter===is||D.magFilter===h1||D.magFilter===qg||D.magFilter===Lu||D.minFilter===is||D.minFilter===h1||D.minFilter===qg||D.minFilter===Lu)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(G,t.TEXTURE_WRAP_S,W[D.wrapS]),t.texParameteri(G,t.TEXTURE_WRAP_T,W[D.wrapT]),(G===t.TEXTURE_3D||G===t.TEXTURE_2D_ARRAY)&&t.texParameteri(G,t.TEXTURE_WRAP_R,W[D.wrapR]),t.texParameteri(G,t.TEXTURE_MAG_FILTER,K[D.magFilter]),t.texParameteri(G,t.TEXTURE_MIN_FILTER,K[D.minFilter]),D.compareFunction&&(t.texParameteri(G,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(G,t.TEXTURE_COMPARE_FUNC,j[D.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(D.magFilter===vr||D.minFilter!==qg&&D.minFilter!==Lu||D.type===_a&&e.has("OES_texture_float_linear")===!1)return;if(D.anisotropy>1||r.get(D).__currentAnisotropy){const ee=e.get("EXT_texture_filter_anisotropic");t.texParameterf(G,ee.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(D.anisotropy,i.getMaxAnisotropy())),r.get(D).__currentAnisotropy=D.anisotropy}}}function ge(G,D){let ee=!1;G.__webglInit===void 0&&(G.__webglInit=!0,D.addEventListener("dispose",R));const he=D.source;let ce=p.get(he);ce===void 0&&(ce={},p.set(he,ce));const _e=T(D);if(_e!==G.__cacheKey){ce[_e]===void 0&&(ce[_e]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,ee=!0),ce[_e].usedTimes++;const ze=ce[G.__cacheKey];ze!==void 0&&(ce[G.__cacheKey].usedTimes--,ze.usedTimes===0&&C(D)),G.__cacheKey=_e,G.__webglTexture=ce[_e].texture}return ee}function Q(G,D,ee){let he=t.TEXTURE_2D;(D.isDataArrayTexture||D.isCompressedArrayTexture)&&(he=t.TEXTURE_2D_ARRAY),D.isData3DTexture&&(he=t.TEXTURE_3D);const ce=ge(G,D),_e=D.source;n.bindTexture(he,G.__webglTexture,t.TEXTURE0+ee);const ze=r.get(_e);if(_e.version!==ze.__version||ce===!0){n.activeTexture(t.TEXTURE0+ee);const Oe=hn.getPrimaries(hn.workingColorSpace),Ge=D.colorSpace===pa?null:hn.getPrimaries(D.colorSpace),Lt=D.colorSpace===pa||Oe===Ge?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,D.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,D.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,Lt);let Pe=v(D.image,!1,i.maxTextureSize);Pe=ne(D,Pe);const nt=s.convert(D.format,D.colorSpace),et=s.convert(D.type);let yt=E(D.internalFormat,nt,et,D.colorSpace,D.isVideoTexture);Y(he,D);let rt;const Ct=D.mipmaps,Rt=D.isVideoTexture!==!0,Sn=ze.__version===void 0||ce===!0,le=_e.dataReady,je=N(D,Pe);if(D.isDepthTexture)yt=b(D.format===$u,D.type),Sn&&(Rt?n.texStorage2D(t.TEXTURE_2D,1,yt,Pe.width,Pe.height):n.texImage2D(t.TEXTURE_2D,0,yt,Pe.width,Pe.height,0,nt,et,null));else if(D.isDataTexture)if(Ct.length>0){Rt&&Sn&&n.texStorage2D(t.TEXTURE_2D,je,yt,Ct[0].width,Ct[0].height);for(let Ce=0,ke=Ct.length;Ce0){const $e=jR(rt.width,rt.height,D.format,D.type);for(const Je of D.layerUpdates){const Nt=rt.data.subarray(Je*$e/rt.data.BYTES_PER_ELEMENT,(Je+1)*$e/rt.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,Ce,0,0,Je,rt.width,rt.height,1,nt,Nt)}D.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,Ce,0,0,0,rt.width,rt.height,Pe.depth,nt,rt.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,Ce,yt,rt.width,rt.height,Pe.depth,0,rt.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Rt?le&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,Ce,0,0,0,rt.width,rt.height,Pe.depth,nt,et,rt.data):n.texImage3D(t.TEXTURE_2D_ARRAY,Ce,yt,rt.width,rt.height,Pe.depth,0,nt,et,rt.data)}else{Rt&&Sn&&n.texStorage2D(t.TEXTURE_2D,je,yt,Ct[0].width,Ct[0].height);for(let Ce=0,ke=Ct.length;Ce0){const Ce=jR(Pe.width,Pe.height,D.format,D.type);for(const ke of D.layerUpdates){const $e=Pe.data.subarray(ke*Ce/Pe.data.BYTES_PER_ELEMENT,(ke+1)*Ce/Pe.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,ke,Pe.width,Pe.height,1,nt,et,$e)}D.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,Pe.width,Pe.height,Pe.depth,nt,et,Pe.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,yt,Pe.width,Pe.height,Pe.depth,0,nt,et,Pe.data);else if(D.isData3DTexture)Rt?(Sn&&n.texStorage3D(t.TEXTURE_3D,je,yt,Pe.width,Pe.height,Pe.depth),le&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,Pe.width,Pe.height,Pe.depth,nt,et,Pe.data)):n.texImage3D(t.TEXTURE_3D,0,yt,Pe.width,Pe.height,Pe.depth,0,nt,et,Pe.data);else if(D.isFramebufferTexture){if(Sn)if(Rt)n.texStorage2D(t.TEXTURE_2D,je,yt,Pe.width,Pe.height);else{let Ce=Pe.width,ke=Pe.height;for(let $e=0;$e>=1,ke>>=1}}else if(Ct.length>0){if(Rt&&Sn){const Ce=ae(Ct[0]);n.texStorage2D(t.TEXTURE_2D,je,yt,Ce.width,Ce.height)}for(let Ce=0,ke=Ct.length;Ce0&&je++;const ke=ae(nt[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,je,Ct,ke.width,ke.height)}for(let ke=0;ke<6;ke++)if(Pe){Rt?le&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,nt[ke].width,nt[ke].height,yt,rt,nt[ke].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,Ct,nt[ke].width,nt[ke].height,0,yt,rt,nt[ke].data);for(let $e=0;$e>_e),et=Math.max(1,D.height>>_e);ce===t.TEXTURE_3D||ce===t.TEXTURE_2D_ARRAY?n.texImage3D(ce,_e,Ge,nt,et,D.depth,0,ze,Oe,null):n.texImage2D(ce,_e,Ge,nt,et,0,ze,Oe,null)}n.bindFramebuffer(t.FRAMEBUFFER,G),X(D)?a.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,he,ce,Pe.__webglTexture,0,te(D)):(ce===t.TEXTURE_2D||ce>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&ce<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,he,ce,Pe.__webglTexture,_e),n.bindFramebuffer(t.FRAMEBUFFER,null)}function Ae(G,D,ee){if(t.bindRenderbuffer(t.RENDERBUFFER,G),D.depthBuffer){const he=D.depthTexture,ce=he&&he.isDepthTexture?he.type:null,_e=b(D.stencilBuffer,ce),ze=D.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Oe=te(D);X(D)?a.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Oe,_e,D.width,D.height):ee?t.renderbufferStorageMultisample(t.RENDERBUFFER,Oe,_e,D.width,D.height):t.renderbufferStorage(t.RENDERBUFFER,_e,D.width,D.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,ze,t.RENDERBUFFER,G)}else{const he=D.textures;for(let ce=0;ce{delete D.__boundDepthTexture,delete D.__depthDisposeCallback,he.removeEventListener("dispose",ce)};he.addEventListener("dispose",ce),D.__depthDisposeCallback=ce}D.__boundDepthTexture=he}if(G.depthTexture&&!D.__autoAllocateDepthBuffer){if(ee)throw new Error("target.depthTexture not supported in Cube render targets");Ee(D.__webglFramebuffer,G)}else if(ee){D.__webglDepthbuffer=[];for(let he=0;he<6;he++)if(n.bindFramebuffer(t.FRAMEBUFFER,D.__webglFramebuffer[he]),D.__webglDepthbuffer[he]===void 0)D.__webglDepthbuffer[he]=t.createRenderbuffer(),Ae(D.__webglDepthbuffer[he],G,!1);else{const ce=G.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,_e=D.__webglDepthbuffer[he];t.bindRenderbuffer(t.RENDERBUFFER,_e),t.framebufferRenderbuffer(t.FRAMEBUFFER,ce,t.RENDERBUFFER,_e)}}else if(n.bindFramebuffer(t.FRAMEBUFFER,D.__webglFramebuffer),D.__webglDepthbuffer===void 0)D.__webglDepthbuffer=t.createRenderbuffer(),Ae(D.__webglDepthbuffer,G,!1);else{const he=G.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ce=D.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,ce),t.framebufferRenderbuffer(t.FRAMEBUFFER,he,t.RENDERBUFFER,ce)}n.bindFramebuffer(t.FRAMEBUFFER,null)}function He(G,D,ee){const he=r.get(G);D!==void 0&&we(he.__webglFramebuffer,G,G.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),ee!==void 0&&Le(G)}function qe(G){const D=G.texture,ee=r.get(G),he=r.get(D);G.addEventListener("dispose",M);const ce=G.textures,_e=G.isWebGLCubeRenderTarget===!0,ze=ce.length>1;if(ze||(he.__webglTexture===void 0&&(he.__webglTexture=t.createTexture()),he.__version=D.version,o.memory.textures++),_e){ee.__webglFramebuffer=[];for(let Oe=0;Oe<6;Oe++)if(D.mipmaps&&D.mipmaps.length>0){ee.__webglFramebuffer[Oe]=[];for(let Ge=0;Ge0){ee.__webglFramebuffer=[];for(let Oe=0;Oe0&&X(G)===!1){ee.__webglMultisampledFramebuffer=t.createFramebuffer(),ee.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,ee.__webglMultisampledFramebuffer);for(let Oe=0;Oe0)for(let Ge=0;Ge0)for(let Ge=0;Ge0){if(X(G)===!1){const D=G.textures,ee=G.width,he=G.height;let ce=t.COLOR_BUFFER_BIT;const _e=G.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ze=r.get(G),Oe=D.length>1;if(Oe)for(let Ge=0;Ge0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&D.__useRenderToTexture!==!1}function $(G){const D=o.render.frame;u.get(G)!==D&&(u.set(G,D),G.update())}function ne(G,D){const ee=G.colorSpace,he=G.format,ce=G.type;return G.isCompressedTexture===!0||G.isVideoTexture===!0||ee!==jl&&ee!==pa&&(hn.getTransfer(ee)===Tn?(he!==to||ce!==bi)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",ee)),D}function ae(G){return typeof HTMLImageElement<"u"&&G instanceof HTMLImageElement?(l.width=G.naturalWidth||G.width,l.height=G.naturalHeight||G.height):typeof VideoFrame<"u"&&G instanceof VideoFrame?(l.width=G.displayWidth,l.height=G.displayHeight):(l.width=G.width,l.height=G.height),l}this.allocateTextureUnit=P,this.resetTextureUnits=L,this.setTexture2D=H,this.setTexture2DArray=V,this.setTexture3D=B,this.setTextureCube=z,this.rebindTextures=He,this.setupRenderTarget=qe,this.updateRenderTargetMipmap=it,this.updateMultisampleRenderTarget=ie,this.setupDepthRenderbuffer=Le,this.setupFrameBufferTexture=we,this.useMultisampledRTT=X}function bG(t,e){function n(r,i=pa){let s;const o=hn.getTransfer(i);if(r===bi)return t.UNSIGNED_BYTE;if(r===gb)return t.UNSIGNED_SHORT_4_4_4_4;if(r===_b)return t.UNSIGNED_SHORT_5_5_5_1;if(r===fO)return t.UNSIGNED_INT_5_9_9_9_REV;if(r===uO)return t.BYTE;if(r===hO)return t.SHORT;if(r===wp)return t.UNSIGNED_SHORT;if(r===mb)return t.INT;if(r===Il)return t.UNSIGNED_INT;if(r===_a)return t.FLOAT;if(r===ld)return t.HALF_FLOAT;if(r===dO)return t.ALPHA;if(r===pO)return t.RGB;if(r===to)return t.RGBA;if(r===mO)return t.LUMINANCE;if(r===gO)return t.LUMINANCE_ALPHA;if(r===Ef)return t.DEPTH_COMPONENT;if(r===$u)return t.DEPTH_STENCIL;if(r===_O)return t.RED;if(r===vb)return t.RED_INTEGER;if(r===vO)return t.RG;if(r===yb)return t.RG_INTEGER;if(r===Ov)return t.RGBA_INTEGER;if(r===Q0||r===e_||r===t_||r===n_)if(o===Tn)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(r===Q0)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(r===e_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(r===t_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(r===n_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(r===Q0)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(r===e_)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(r===t_)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(r===n_)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(r===rE||r===iE||r===sE||r===oE)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(r===rE)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(r===iE)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(r===sE)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(r===oE)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(r===aE||r===cE||r===lE)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(r===aE||r===cE)return o===Tn?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(r===lE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(r===uE||r===hE||r===fE||r===dE||r===pE||r===mE||r===gE||r===_E||r===vE||r===yE||r===xE||r===SE||r===EE||r===wE)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(r===uE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(r===hE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(r===fE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(r===dE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(r===pE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(r===mE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(r===gE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(r===_E)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(r===vE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(r===yE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(r===xE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(r===SE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(r===EE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(r===wE)return o===Tn?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(r===r_||r===bE||r===TE)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(r===r_)return o===Tn?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(r===bE)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(r===TE)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(r===yO||r===AE||r===ME||r===CE)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(r===r_)return s.COMPRESSED_RED_RGTC1_EXT;if(r===AE)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(r===ME)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(r===CE)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return r===ju?t.UNSIGNED_INT_24_8:t[r]!==void 0?t[r]:null}return{convert:n}}class TG extends Ms{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class ip extends cs{constructor(){super(),this.isGroup=!0,this.type="Group"}}const AG={type:"move"};class F1{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new ip,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new ip,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new xe,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new xe),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new ip,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new xe,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new xe),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const n=this._hand;if(n)for(const r of e.hand.values())this._getHandJoint(n,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,n,r){let i=null,s=null,o=null;const a=this._targetRay,c=this._grip,l=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(l&&e.hand){o=!0;for(const v of e.hand.values()){const y=n.getJointPose(v,r),_=this._getHandJoint(l,v);y!==null&&(_.matrix.fromArray(y.transform.matrix),_.matrix.decompose(_.position,_.rotation,_.scale),_.matrixWorldNeedsUpdate=!0,_.jointRadius=y.radius),_.visible=y!==null}const u=l.joints["index-finger-tip"],h=l.joints["thumb-tip"],p=u.position.distanceTo(h.position),m=.02,g=.005;l.inputState.pinching&&p>m+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&p<=m-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=n.getPose(e.gripSpace,r),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));a!==null&&(i=n.getPose(e.targetRaySpace,r),i===null&&s!==null&&(i=s),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(AG)))}return a!==null&&(a.visible=i!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const r=new ip;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[n.jointName]=r,e.add(r)}return e.joints[n.jointName]}}const MG=` -void main() { - - gl_Position = vec4( position, 1.0 ); - -}`,CG=` -uniform sampler2DArray depthColor; -uniform float depthWidth; -uniform float depthHeight; - -void main() { - - vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); - - if ( coord.x >= 1.0 ) { - - gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; - - } else { - - gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; - - } - -}`;class RG{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,n,r){if(this.texture===null){const i=new or,s=e.properties.get(i);s.__webglTexture=n.texture,(n.depthNear!=r.depthNear||n.depthFar!=r.depthFar)&&(this.depthNear=n.depthNear,this.depthFar=n.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const n=e.cameras[0].viewport,r=new Gi({vertexShader:MG,fragmentShader:CG,uniforms:{depthColor:{value:this.texture},depthWidth:{value:n.z},depthHeight:{value:n.w}}});this.mesh=new Ao(new em(20,20),r)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class NG extends zc{constructor(e,n){super();const r=this;let i=null,s=1,o=null,a="local-floor",c=1,l=null,u=null,h=null,p=null,m=null,g=null;const v=new RG,y=n.getContextAttributes();let _=null,S=null;const E=[],b=[],N=new St;let R=null;const M=new Ms;M.viewport=new gr;const O=new Ms;O.viewport=new gr;const C=[M,O],I=new TG;let U=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Q){let re=E[Q];return re===void 0&&(re=new F1,E[Q]=re),re.getTargetRaySpace()},this.getControllerGrip=function(Q){let re=E[Q];return re===void 0&&(re=new F1,E[Q]=re),re.getGripSpace()},this.getHand=function(Q){let re=E[Q];return re===void 0&&(re=new F1,E[Q]=re),re.getHandSpace()};function P(Q){const re=b.indexOf(Q.inputSource);if(re===-1)return;const we=E[re];we!==void 0&&(we.update(Q.inputSource,Q.frame,l||o),we.dispatchEvent({type:Q.type,data:Q.inputSource}))}function T(){i.removeEventListener("select",P),i.removeEventListener("selectstart",P),i.removeEventListener("selectend",P),i.removeEventListener("squeeze",P),i.removeEventListener("squeezestart",P),i.removeEventListener("squeezeend",P),i.removeEventListener("end",T),i.removeEventListener("inputsourceschange",H);for(let Q=0;Q=0&&(b[Ae]=null,E[Ae].disconnect(we))}for(let re=0;re=b.length){b.push(we),Ae=Le;break}else if(b[Le]===null){b[Le]=we,Ae=Le;break}if(Ae===-1)break}const Ee=E[Ae];Ee&&Ee.connect(we)}}const V=new xe,B=new xe;function z(Q,re,we){V.setFromMatrixPosition(re.matrixWorld),B.setFromMatrixPosition(we.matrixWorld);const Ae=V.distanceTo(B),Ee=re.projectionMatrix.elements,Le=we.projectionMatrix.elements,He=Ee[14]/(Ee[10]-1),qe=Ee[14]/(Ee[10]+1),it=(Ee[9]+1)/Ee[5],De=(Ee[9]-1)/Ee[5],A=(Ee[8]-1)/Ee[0],ie=(Le[8]+1)/Le[0],te=He*A,X=He*ie,$=Ae/(-A+ie),ne=$*-A;if(re.matrixWorld.decompose(Q.position,Q.quaternion,Q.scale),Q.translateX(ne),Q.translateZ($),Q.matrixWorld.compose(Q.position,Q.quaternion,Q.scale),Q.matrixWorldInverse.copy(Q.matrixWorld).invert(),Ee[10]===-1)Q.projectionMatrix.copy(re.projectionMatrix),Q.projectionMatrixInverse.copy(re.projectionMatrixInverse);else{const ae=He+$,G=qe+$,D=te-ne,ee=X+(Ae-ne),he=it*qe/G*ae,ce=De*qe/G*ae;Q.projectionMatrix.makePerspective(D,ee,he,ce,ae,G),Q.projectionMatrixInverse.copy(Q.projectionMatrix).invert()}}function W(Q,re){re===null?Q.matrixWorld.copy(Q.matrix):Q.matrixWorld.multiplyMatrices(re.matrixWorld,Q.matrix),Q.matrixWorldInverse.copy(Q.matrixWorld).invert()}this.updateCamera=function(Q){if(i===null)return;let re=Q.near,we=Q.far;v.texture!==null&&(v.depthNear>0&&(re=v.depthNear),v.depthFar>0&&(we=v.depthFar)),I.near=O.near=M.near=re,I.far=O.far=M.far=we,(U!==I.near||L!==I.far)&&(i.updateRenderState({depthNear:I.near,depthFar:I.far}),U=I.near,L=I.far),M.layers.mask=Q.layers.mask|2,O.layers.mask=Q.layers.mask|4,I.layers.mask=M.layers.mask|O.layers.mask;const Ae=Q.parent,Ee=I.cameras;W(I,Ae);for(let Le=0;Le0&&(y.alphaTest.value=_.alphaTest);const S=e.get(_),E=S.envMap,b=S.envMapRotation;E&&(y.envMap.value=E,pu.copy(b),pu.x*=-1,pu.y*=-1,pu.z*=-1,E.isCubeTexture&&E.isRenderTargetTexture===!1&&(pu.y*=-1,pu.z*=-1),y.envMapRotation.value.setFromMatrix4(kG.makeRotationFromEuler(pu)),y.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,y.reflectivity.value=_.reflectivity,y.ior.value=_.ior,y.refractionRatio.value=_.refractionRatio),_.lightMap&&(y.lightMap.value=_.lightMap,y.lightMapIntensity.value=_.lightMapIntensity,n(_.lightMap,y.lightMapTransform)),_.aoMap&&(y.aoMap.value=_.aoMap,y.aoMapIntensity.value=_.aoMapIntensity,n(_.aoMap,y.aoMapTransform))}function o(y,_){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,_.map&&(y.map.value=_.map,n(_.map,y.mapTransform))}function a(y,_){y.dashSize.value=_.dashSize,y.totalSize.value=_.dashSize+_.gapSize,y.scale.value=_.scale}function c(y,_,S,E){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,y.size.value=_.size*S,y.scale.value=E*.5,_.map&&(y.map.value=_.map,n(_.map,y.uvTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,n(_.alphaMap,y.alphaMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest)}function l(y,_){y.diffuse.value.copy(_.color),y.opacity.value=_.opacity,y.rotation.value=_.rotation,_.map&&(y.map.value=_.map,n(_.map,y.mapTransform)),_.alphaMap&&(y.alphaMap.value=_.alphaMap,n(_.alphaMap,y.alphaMapTransform)),_.alphaTest>0&&(y.alphaTest.value=_.alphaTest)}function u(y,_){y.specular.value.copy(_.specular),y.shininess.value=Math.max(_.shininess,1e-4)}function h(y,_){_.gradientMap&&(y.gradientMap.value=_.gradientMap)}function p(y,_){y.metalness.value=_.metalness,_.metalnessMap&&(y.metalnessMap.value=_.metalnessMap,n(_.metalnessMap,y.metalnessMapTransform)),y.roughness.value=_.roughness,_.roughnessMap&&(y.roughnessMap.value=_.roughnessMap,n(_.roughnessMap,y.roughnessMapTransform)),_.envMap&&(y.envMapIntensity.value=_.envMapIntensity)}function m(y,_,S){y.ior.value=_.ior,_.sheen>0&&(y.sheenColor.value.copy(_.sheenColor).multiplyScalar(_.sheen),y.sheenRoughness.value=_.sheenRoughness,_.sheenColorMap&&(y.sheenColorMap.value=_.sheenColorMap,n(_.sheenColorMap,y.sheenColorMapTransform)),_.sheenRoughnessMap&&(y.sheenRoughnessMap.value=_.sheenRoughnessMap,n(_.sheenRoughnessMap,y.sheenRoughnessMapTransform))),_.clearcoat>0&&(y.clearcoat.value=_.clearcoat,y.clearcoatRoughness.value=_.clearcoatRoughness,_.clearcoatMap&&(y.clearcoatMap.value=_.clearcoatMap,n(_.clearcoatMap,y.clearcoatMapTransform)),_.clearcoatRoughnessMap&&(y.clearcoatRoughnessMap.value=_.clearcoatRoughnessMap,n(_.clearcoatRoughnessMap,y.clearcoatRoughnessMapTransform)),_.clearcoatNormalMap&&(y.clearcoatNormalMap.value=_.clearcoatNormalMap,n(_.clearcoatNormalMap,y.clearcoatNormalMapTransform),y.clearcoatNormalScale.value.copy(_.clearcoatNormalScale),_.side===ri&&y.clearcoatNormalScale.value.negate())),_.dispersion>0&&(y.dispersion.value=_.dispersion),_.iridescence>0&&(y.iridescence.value=_.iridescence,y.iridescenceIOR.value=_.iridescenceIOR,y.iridescenceThicknessMinimum.value=_.iridescenceThicknessRange[0],y.iridescenceThicknessMaximum.value=_.iridescenceThicknessRange[1],_.iridescenceMap&&(y.iridescenceMap.value=_.iridescenceMap,n(_.iridescenceMap,y.iridescenceMapTransform)),_.iridescenceThicknessMap&&(y.iridescenceThicknessMap.value=_.iridescenceThicknessMap,n(_.iridescenceThicknessMap,y.iridescenceThicknessMapTransform))),_.transmission>0&&(y.transmission.value=_.transmission,y.transmissionSamplerMap.value=S.texture,y.transmissionSamplerSize.value.set(S.width,S.height),_.transmissionMap&&(y.transmissionMap.value=_.transmissionMap,n(_.transmissionMap,y.transmissionMapTransform)),y.thickness.value=_.thickness,_.thicknessMap&&(y.thicknessMap.value=_.thicknessMap,n(_.thicknessMap,y.thicknessMapTransform)),y.attenuationDistance.value=_.attenuationDistance,y.attenuationColor.value.copy(_.attenuationColor)),_.anisotropy>0&&(y.anisotropyVector.value.set(_.anisotropy*Math.cos(_.anisotropyRotation),_.anisotropy*Math.sin(_.anisotropyRotation)),_.anisotropyMap&&(y.anisotropyMap.value=_.anisotropyMap,n(_.anisotropyMap,y.anisotropyMapTransform))),y.specularIntensity.value=_.specularIntensity,y.specularColor.value.copy(_.specularColor),_.specularColorMap&&(y.specularColorMap.value=_.specularColorMap,n(_.specularColorMap,y.specularColorMapTransform)),_.specularIntensityMap&&(y.specularIntensityMap.value=_.specularIntensityMap,n(_.specularIntensityMap,y.specularIntensityMapTransform))}function g(y,_){_.matcap&&(y.matcap.value=_.matcap)}function v(y,_){const S=e.get(_).light;y.referencePosition.value.setFromMatrixPosition(S.matrixWorld),y.nearDistance.value=S.shadow.camera.near,y.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function OG(t,e,n,r){let i={},s={},o=[];const a=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function c(S,E){const b=E.program;r.uniformBlockBinding(S,b)}function l(S,E){let b=i[S.id];b===void 0&&(g(S),b=u(S),i[S.id]=b,S.addEventListener("dispose",y));const N=E.program;r.updateUBOMapping(S,N);const R=e.render.frame;s[S.id]!==R&&(p(S),s[S.id]=R)}function u(S){const E=h();S.__bindingPointIndex=E;const b=t.createBuffer(),N=S.__size,R=S.usage;return t.bindBuffer(t.UNIFORM_BUFFER,b),t.bufferData(t.UNIFORM_BUFFER,N,R),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,E,b),b}function h(){for(let S=0;S0&&(b+=N-R),S.__size=b,S.__cache={},this}function v(S){const E={boundary:0,storage:0};return typeof S=="number"||typeof S=="boolean"?(E.boundary=4,E.storage=4):S.isVector2?(E.boundary=8,E.storage=8):S.isVector3||S.isColor?(E.boundary=16,E.storage=12):S.isVector4?(E.boundary=16,E.storage=16):S.isMatrix3?(E.boundary=48,E.storage=48):S.isMatrix4?(E.boundary=64,E.storage=64):S.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",S),E}function y(S){const E=S.target;E.removeEventListener("dispose",y);const b=o.indexOf(E.__bindingPointIndex);o.splice(b,1),t.deleteBuffer(i[E.id]),delete i[E.id],delete s[E.id]}function _(){for(const S in i)t.deleteBuffer(i[S]);o=[],i={},s={}}return{bind:c,update:l,dispose:_}}class LG{constructor(e={}){const{canvas:n=Ez(),context:r=null,depth:i=!0,stencil:s=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:h=!1,reverseDepthBuffer:p=!1}=e;this.isWebGLRenderer=!0;let m;if(r!==null){if(typeof WebGLRenderingContext<"u"&&r instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");m=r.getContextAttributes().alpha}else m=o;const g=new Uint32Array(4),v=new Int32Array(4);let y=null,_=null;const S=[],E=[];this.domElement=n,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=pr,this.toneMapping=ya,this.toneMappingExposure=1;const b=this;let N=!1,R=0,M=0,O=null,C=-1,I=null;const U=new gr,L=new gr;let P=null;const T=new ln(0);let H=0,V=n.width,B=n.height,z=1,W=null,K=null;const j=new gr(0,0,V,B),Y=new gr(0,0,V,B);let ge=!1;const Q=new NO;let re=!1,we=!1;const Ae=new ar,Ee=new ar,Le=new xe,He=new gr,qe={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let it=!1;function De(){return O===null?z:1}let A=r;function ie(q,fe){return n.getContext(q,fe)}try{const q={alpha:!0,depth:i,stencil:s,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:u,failIfMajorPerformanceCaveat:h};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${kv}`),n.addEventListener("webglcontextlost",ke,!1),n.addEventListener("webglcontextrestored",$e,!1),n.addEventListener("webglcontextcreationerror",Je,!1),A===null){const fe="webgl2";if(A=ie(fe,q),A===null)throw ie(fe)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(q){throw console.error("THREE.WebGLRenderer: "+q.message),q}let te,X,$,ne,ae,G,D,ee,he,ce,_e,ze,Oe,Ge,Lt,Pe,nt,et,yt,rt,Ct,Rt,Sn,le;function je(){te=new BV(A),te.init(),Rt=new bG(A,te),X=new OV(A,te,e,Rt),$=new SG(A,te),X.reverseDepthBuffer&&p&&$.buffers.depth.setReversed(!0),ne=new HV(A),ae=new oG,G=new wG(A,te,$,ae,X,Rt,ne),D=new PV(b),ee=new FV(b),he=new Kz(A),Sn=new kV(A,he),ce=new zV(A,he,ne,Sn),_e=new WV(A,ce,he,ne),yt=new GV(A,X,G),Pe=new LV(ae),ze=new sG(b,D,ee,te,X,Sn,Pe),Oe=new IG(b,ae),Ge=new cG,Lt=new pG(te),et=new NV(b,D,ee,$,_e,m,c),nt=new yG(b,_e,X),le=new OG(A,ne,X,$),rt=new IV(A,te,ne),Ct=new VV(A,te,ne),ne.programs=ze.programs,b.capabilities=X,b.extensions=te,b.properties=ae,b.renderLists=Ge,b.shadowMap=nt,b.state=$,b.info=ne}je();const Ce=new NG(b,A);this.xr=Ce,this.getContext=function(){return A},this.getContextAttributes=function(){return A.getContextAttributes()},this.forceContextLoss=function(){const q=te.get("WEBGL_lose_context");q&&q.loseContext()},this.forceContextRestore=function(){const q=te.get("WEBGL_lose_context");q&&q.restoreContext()},this.getPixelRatio=function(){return z},this.setPixelRatio=function(q){q!==void 0&&(z=q,this.setSize(V,B,!1))},this.getSize=function(q){return q.set(V,B)},this.setSize=function(q,fe,be=!0){if(Ce.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}V=q,B=fe,n.width=Math.floor(q*z),n.height=Math.floor(fe*z),be===!0&&(n.style.width=q+"px",n.style.height=fe+"px"),this.setViewport(0,0,q,fe)},this.getDrawingBufferSize=function(q){return q.set(V*z,B*z).floor()},this.setDrawingBufferSize=function(q,fe,be){V=q,B=fe,z=be,n.width=Math.floor(q*be),n.height=Math.floor(fe*be),this.setViewport(0,0,q,fe)},this.getCurrentViewport=function(q){return q.copy(U)},this.getViewport=function(q){return q.copy(j)},this.setViewport=function(q,fe,be,Te){q.isVector4?j.set(q.x,q.y,q.z,q.w):j.set(q,fe,be,Te),$.viewport(U.copy(j).multiplyScalar(z).round())},this.getScissor=function(q){return q.copy(Y)},this.setScissor=function(q,fe,be,Te){q.isVector4?Y.set(q.x,q.y,q.z,q.w):Y.set(q,fe,be,Te),$.scissor(L.copy(Y).multiplyScalar(z).round())},this.getScissorTest=function(){return ge},this.setScissorTest=function(q){$.setScissorTest(ge=q)},this.setOpaqueSort=function(q){W=q},this.setTransparentSort=function(q){K=q},this.getClearColor=function(q){return q.copy(et.getClearColor())},this.setClearColor=function(){et.setClearColor.apply(et,arguments)},this.getClearAlpha=function(){return et.getClearAlpha()},this.setClearAlpha=function(){et.setClearAlpha.apply(et,arguments)},this.clear=function(q=!0,fe=!0,be=!0){let Te=0;if(q){let me=!1;if(O!==null){const Be=O.texture.format;me=Be===Ov||Be===yb||Be===vb}if(me){const Be=O.texture.type,Ye=Be===bi||Be===Il||Be===wp||Be===ju||Be===gb||Be===_b,lt=et.getClearColor(),ut=et.getClearAlpha(),At=lt.r,kt=lt.g,ht=lt.b;Ye?(g[0]=At,g[1]=kt,g[2]=ht,g[3]=ut,A.clearBufferuiv(A.COLOR,0,g)):(v[0]=At,v[1]=kt,v[2]=ht,v[3]=ut,A.clearBufferiv(A.COLOR,0,v))}else Te|=A.COLOR_BUFFER_BIT}fe&&(Te|=A.DEPTH_BUFFER_BIT),be&&(Te|=A.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),A.clear(Te)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){n.removeEventListener("webglcontextlost",ke,!1),n.removeEventListener("webglcontextrestored",$e,!1),n.removeEventListener("webglcontextcreationerror",Je,!1),Ge.dispose(),Lt.dispose(),ae.dispose(),D.dispose(),ee.dispose(),_e.dispose(),Sn.dispose(),le.dispose(),ze.dispose(),Ce.dispose(),Ce.removeEventListener("sessionstart",$m),Ce.removeEventListener("sessionend",qm),Xo.stop()};function ke(q){q.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),N=!0}function $e(){console.log("THREE.WebGLRenderer: Context Restored."),N=!1;const q=ne.autoReset,fe=nt.enabled,be=nt.autoUpdate,Te=nt.needsUpdate,me=nt.type;je(),ne.autoReset=q,nt.enabled=fe,nt.autoUpdate=be,nt.needsUpdate=Te,nt.type=me}function Je(q){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",q.statusMessage)}function Nt(q){const fe=q.target;fe.removeEventListener("dispose",Nt),Wn(fe)}function Wn(q){Nr(q),ae.remove(q)}function Nr(q){const fe=ae.get(q).programs;fe!==void 0&&(fe.forEach(function(be){ze.releaseProgram(be)}),q.isShaderMaterial&&ze.releaseShaderCache(q))}this.renderBufferDirect=function(q,fe,be,Te,me,Be){fe===null&&(fe=qe);const Ye=me.isMesh&&me.matrixWorld.determinant()<0,lt=ix(q,fe,be,Te,me);$.setMaterial(Te,Ye);let ut=be.index,At=1;if(Te.wireframe===!0){if(ut=ce.getWireframeAttribute(be),ut===void 0)return;At=2}const kt=be.drawRange,ht=be.attributes.position;let Bt=kt.start*At,nn=(kt.start+kt.count)*At;Be!==null&&(Bt=Math.max(Bt,Be.start*At),nn=Math.min(nn,(Be.start+Be.count)*At)),ut!==null?(Bt=Math.max(Bt,0),nn=Math.min(nn,ut.count)):ht!=null&&(Bt=Math.max(Bt,0),nn=Math.min(nn,ht.count));const Et=nn-Bt;if(Et<0||Et===1/0)return;Sn.setup(me,Te,lt,be,ut);let Pt,zt=rt;if(ut!==null&&(Pt=he.get(ut),zt=Ct,zt.setIndex(Pt)),me.isMesh)Te.wireframe===!0?($.setLineWidth(Te.wireframeLinewidth*De()),zt.setMode(A.LINES)):zt.setMode(A.TRIANGLES);else if(me.isLine){let Qe=Te.linewidth;Qe===void 0&&(Qe=1),$.setLineWidth(Qe*De()),me.isLineSegments?zt.setMode(A.LINES):me.isLineLoop?zt.setMode(A.LINE_LOOP):zt.setMode(A.LINE_STRIP)}else me.isPoints?zt.setMode(A.POINTS):me.isSprite&&zt.setMode(A.TRIANGLES);if(me.isBatchedMesh)if(me._multiDrawInstances!==null)zt.renderMultiDrawInstances(me._multiDrawStarts,me._multiDrawCounts,me._multiDrawCount,me._multiDrawInstances);else if(te.get("WEBGL_multi_draw"))zt.renderMultiDraw(me._multiDrawStarts,me._multiDrawCounts,me._multiDrawCount);else{const Qe=me._multiDrawStarts,jn=me._multiDrawCounts,qt=me._multiDrawCount,jr=ut?he.get(ut).bytesPerElement:1,lr=ae.get(Te).currentProgram.getUniforms();for(let $r=0;$r{function Be(){if(Te.forEach(function(Ye){ae.get(Ye).currentProgram.isReady()&&Te.delete(Ye)}),Te.size===0){me(q);return}setTimeout(Be,10)}te.get("KHR_parallel_shader_compile")!==null?Be():setTimeout(Be,10)})};let Ki=null;function mo(q){Ki&&Ki(q)}function $m(){Xo.stop()}function qm(){Xo.start()}const Xo=new kO;Xo.setAnimationLoop(mo),typeof self<"u"&&Xo.setContext(self),this.setAnimationLoop=function(q){Ki=q,Ce.setAnimationLoop(q),q===null?Xo.stop():Xo.start()},Ce.addEventListener("sessionstart",$m),Ce.addEventListener("sessionend",qm),this.render=function(q,fe){if(fe!==void 0&&fe.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(N===!0)return;if(q.matrixWorldAutoUpdate===!0&&q.updateMatrixWorld(),fe.parent===null&&fe.matrixWorldAutoUpdate===!0&&fe.updateMatrixWorld(),Ce.enabled===!0&&Ce.isPresenting===!0&&(Ce.cameraAutoUpdate===!0&&Ce.updateCamera(fe),fe=Ce.getCamera()),q.isScene===!0&&q.onBeforeRender(b,q,fe,O),_=Lt.get(q,E.length),_.init(fe),E.push(_),Ee.multiplyMatrices(fe.projectionMatrix,fe.matrixWorldInverse),Q.setFromProjectionMatrix(Ee),we=this.localClippingEnabled,re=Pe.init(this.clippingPlanes,we),y=Ge.get(q,S.length),y.init(),S.push(y),Ce.enabled===!0&&Ce.isPresenting===!0){const Be=b.xr.getDepthSensingMesh();Be!==null&&Ql(Be,fe,-1/0,b.sortObjects)}Ql(q,fe,0,b.sortObjects),y.finish(),b.sortObjects===!0&&y.sort(W,K),it=Ce.enabled===!1||Ce.isPresenting===!1||Ce.hasDepthSensing()===!1,it&&et.addToRenderList(y,q),this.info.render.frame++,re===!0&&Pe.beginShadows();const be=_.state.shadowsArray;nt.render(be,q,fe),re===!0&&Pe.endShadows(),this.info.autoReset===!0&&this.info.reset();const Te=y.opaque,me=y.transmissive;if(_.setupLights(),fe.isArrayCamera){const Be=fe.cameras;if(me.length>0)for(let Ye=0,lt=Be.length;Ye0&&el(Te,me,q,fe),it&&et.render(q),Xm(y,q,fe);O!==null&&(G.updateMultisampleRenderTarget(O),G.updateRenderTargetMipmap(O)),q.isScene===!0&&q.onAfterRender(b,q,fe),Sn.resetDefaultState(),C=-1,I=null,E.pop(),E.length>0?(_=E[E.length-1],re===!0&&Pe.setGlobalState(b.clippingPlanes,_.state.camera)):_=null,S.pop(),S.length>0?y=S[S.length-1]:y=null};function Ql(q,fe,be,Te){if(q.visible===!1)return;if(q.layers.test(fe.layers)){if(q.isGroup)be=q.renderOrder;else if(q.isLOD)q.autoUpdate===!0&&q.update(fe);else if(q.isLight)_.pushLight(q),q.castShadow&&_.pushShadow(q);else if(q.isSprite){if(!q.frustumCulled||Q.intersectsSprite(q)){Te&&He.setFromMatrixPosition(q.matrixWorld).applyMatrix4(Ee);const Ye=_e.update(q),lt=q.material;lt.visible&&y.push(q,Ye,lt,be,He.z,null)}}else if((q.isMesh||q.isLine||q.isPoints)&&(!q.frustumCulled||Q.intersectsObject(q))){const Ye=_e.update(q),lt=q.material;if(Te&&(q.boundingSphere!==void 0?(q.boundingSphere===null&&q.computeBoundingSphere(),He.copy(q.boundingSphere.center)):(Ye.boundingSphere===null&&Ye.computeBoundingSphere(),He.copy(Ye.boundingSphere.center)),He.applyMatrix4(q.matrixWorld).applyMatrix4(Ee)),Array.isArray(lt)){const ut=Ye.groups;for(let At=0,kt=ut.length;At0&&Eh(me,fe,be),Be.length>0&&Eh(Be,fe,be),Ye.length>0&&Eh(Ye,fe,be),$.buffers.depth.setTest(!0),$.buffers.depth.setMask(!0),$.buffers.color.setMask(!0),$.setPolygonOffset(!1)}function el(q,fe,be,Te){if((be.isScene===!0?be.overrideMaterial:null)!==null)return;_.state.transmissionRenderTarget[Te.id]===void 0&&(_.state.transmissionRenderTarget[Te.id]=new Us(1,1,{generateMipmaps:!0,type:te.has("EXT_color_buffer_half_float")||te.has("EXT_color_buffer_float")?ld:bi,minFilter:Lu,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:hn.workingColorSpace}));const Be=_.state.transmissionRenderTarget[Te.id],Ye=Te.viewport||U;Be.setSize(Ye.z,Ye.w);const lt=b.getRenderTarget();b.setRenderTarget(Be),b.getClearColor(T),H=b.getClearAlpha(),H<1&&b.setClearColor(16777215,.5),b.clear(),it&&et.render(be);const ut=b.toneMapping;b.toneMapping=ya;const At=Te.viewport;if(Te.viewport!==void 0&&(Te.viewport=void 0),_.setupLightsView(Te),re===!0&&Pe.setGlobalState(b.clippingPlanes,Te),Eh(q,be,Te),G.updateMultisampleRenderTarget(Be),G.updateRenderTargetMipmap(Be),te.has("WEBGL_multisampled_render_to_texture")===!1){let kt=!1;for(let ht=0,Bt=fe.length;ht0),ht=!!be.morphAttributes.position,Bt=!!be.morphAttributes.normal,nn=!!be.morphAttributes.color;let Et=ya;Te.toneMapped&&(O===null||O.isXRRenderTarget===!0)&&(Et=b.toneMapping);const Pt=be.morphAttributes.position||be.morphAttributes.normal||be.morphAttributes.color,zt=Pt!==void 0?Pt.length:0,Qe=ae.get(Te),jn=_.state.lights;if(re===!0&&(we===!0||q!==I)){const $n=q===I&&Te.id===C;Pe.setState(Te,q,$n)}let qt=!1;Te.version===Qe.__version?(Qe.needsLights&&Qe.lightsStateVersion!==jn.state.version||Qe.outputColorSpace!==lt||me.isBatchedMesh&&Qe.batching===!1||!me.isBatchedMesh&&Qe.batching===!0||me.isBatchedMesh&&Qe.batchingColor===!0&&me.colorTexture===null||me.isBatchedMesh&&Qe.batchingColor===!1&&me.colorTexture!==null||me.isInstancedMesh&&Qe.instancing===!1||!me.isInstancedMesh&&Qe.instancing===!0||me.isSkinnedMesh&&Qe.skinning===!1||!me.isSkinnedMesh&&Qe.skinning===!0||me.isInstancedMesh&&Qe.instancingColor===!0&&me.instanceColor===null||me.isInstancedMesh&&Qe.instancingColor===!1&&me.instanceColor!==null||me.isInstancedMesh&&Qe.instancingMorph===!0&&me.morphTexture===null||me.isInstancedMesh&&Qe.instancingMorph===!1&&me.morphTexture!==null||Qe.envMap!==ut||Te.fog===!0&&Qe.fog!==Be||Qe.numClippingPlanes!==void 0&&(Qe.numClippingPlanes!==Pe.numPlanes||Qe.numIntersection!==Pe.numIntersection)||Qe.vertexAlphas!==At||Qe.vertexTangents!==kt||Qe.morphTargets!==ht||Qe.morphNormals!==Bt||Qe.morphColors!==nn||Qe.toneMapping!==Et||Qe.morphTargetsCount!==zt)&&(qt=!0):(qt=!0,Qe.__version=Te.version);let jr=Qe.currentProgram;qt===!0&&(jr=wh(Te,fe,me));let lr=!1,$r=!1,tl=!1;const bn=jr.getUniforms(),Mi=Qe.uniforms;if($.useProgram(jr.program)&&(lr=!0,$r=!0,tl=!0),Te.id!==C&&(C=Te.id,$r=!0),lr||I!==q){$.buffers.depth.getReversed()?(Ae.copy(q.projectionMatrix),bz(Ae),Tz(Ae),bn.setValue(A,"projectionMatrix",Ae)):bn.setValue(A,"projectionMatrix",q.projectionMatrix),bn.setValue(A,"viewMatrix",q.matrixWorldInverse);const Ko=bn.map.cameraPosition;Ko!==void 0&&Ko.setValue(A,Le.setFromMatrixPosition(q.matrixWorld)),X.logarithmicDepthBuffer&&bn.setValue(A,"logDepthBufFC",2/(Math.log(q.far+1)/Math.LN2)),(Te.isMeshPhongMaterial||Te.isMeshToonMaterial||Te.isMeshLambertMaterial||Te.isMeshBasicMaterial||Te.isMeshStandardMaterial||Te.isShaderMaterial)&&bn.setValue(A,"isOrthographic",q.isOrthographicCamera===!0),I!==q&&(I=q,$r=!0,tl=!0)}if(me.isSkinnedMesh){bn.setOptional(A,me,"bindMatrix"),bn.setOptional(A,me,"bindMatrixInverse");const $n=me.skeleton;$n&&($n.boneTexture===null&&$n.computeBoneTexture(),bn.setValue(A,"boneTexture",$n.boneTexture,G))}me.isBatchedMesh&&(bn.setOptional(A,me,"batchingTexture"),bn.setValue(A,"batchingTexture",me._matricesTexture,G),bn.setOptional(A,me,"batchingIdTexture"),bn.setValue(A,"batchingIdTexture",me._indirectTexture,G),bn.setOptional(A,me,"batchingColorTexture"),me._colorsTexture!==null&&bn.setValue(A,"batchingColorTexture",me._colorsTexture,G));const nl=be.morphAttributes;if((nl.position!==void 0||nl.normal!==void 0||nl.color!==void 0)&&yt.update(me,be,jr),($r||Qe.receiveShadow!==me.receiveShadow)&&(Qe.receiveShadow=me.receiveShadow,bn.setValue(A,"receiveShadow",me.receiveShadow)),Te.isMeshGouraudMaterial&&Te.envMap!==null&&(Mi.envMap.value=ut,Mi.flipEnvMap.value=ut.isCubeTexture&&ut.isRenderTargetTexture===!1?-1:1),Te.isMeshStandardMaterial&&Te.envMap===null&&fe.environment!==null&&(Mi.envMapIntensity.value=fe.environmentIntensity),$r&&(bn.setValue(A,"toneMappingExposure",b.toneMappingExposure),Qe.needsLights&&sx(Mi,tl),Be&&Te.fog===!0&&Oe.refreshFogUniforms(Mi,Be),Oe.refreshMaterialUniforms(Mi,Te,z,B,_.state.transmissionRenderTarget[q.id]),i_.upload(A,Ym(Qe),Mi,G)),Te.isShaderMaterial&&Te.uniformsNeedUpdate===!0&&(i_.upload(A,Ym(Qe),Mi,G),Te.uniformsNeedUpdate=!1),Te.isSpriteMaterial&&bn.setValue(A,"center",me.center),bn.setValue(A,"modelViewMatrix",me.modelViewMatrix),bn.setValue(A,"normalMatrix",me.normalMatrix),bn.setValue(A,"modelMatrix",me.matrixWorld),Te.isShaderMaterial||Te.isRawShaderMaterial){const $n=Te.uniformsGroups;for(let Ko=0,Yo=$n.length;Ko0&&G.useMultisampledRTT(q)===!1?me=ae.get(q).__webglMultisampledFramebuffer:Array.isArray(kt)?me=kt[be]:me=kt,U.copy(q.viewport),L.copy(q.scissor),P=q.scissorTest}else U.copy(j).multiplyScalar(z).floor(),L.copy(Y).multiplyScalar(z).floor(),P=ge;if($.bindFramebuffer(A.FRAMEBUFFER,me)&&Te&&$.drawBuffers(q,me),$.viewport(U),$.scissor(L),$.setScissorTest(P),Be){const ut=ae.get(q.texture);A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+fe,ut.__webglTexture,be)}else if(Ye){const ut=ae.get(q.texture),At=fe||0;A.framebufferTextureLayer(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,ut.__webglTexture,be||0,At)}C=-1},this.readRenderTargetPixels=function(q,fe,be,Te,me,Be,Ye){if(!(q&&q.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let lt=ae.get(q).__webglFramebuffer;if(q.isWebGLCubeRenderTarget&&Ye!==void 0&&(lt=lt[Ye]),lt){$.bindFramebuffer(A.FRAMEBUFFER,lt);try{const ut=q.texture,At=ut.format,kt=ut.type;if(!X.textureFormatReadable(At)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!X.textureTypeReadable(kt)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}fe>=0&&fe<=q.width-Te&&be>=0&&be<=q.height-me&&A.readPixels(fe,be,Te,me,Rt.convert(At),Rt.convert(kt),Be)}finally{const ut=O!==null?ae.get(O).__webglFramebuffer:null;$.bindFramebuffer(A.FRAMEBUFFER,ut)}}},this.readRenderTargetPixelsAsync=async function(q,fe,be,Te,me,Be,Ye){if(!(q&&q.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let lt=ae.get(q).__webglFramebuffer;if(q.isWebGLCubeRenderTarget&&Ye!==void 0&&(lt=lt[Ye]),lt){const ut=q.texture,At=ut.format,kt=ut.type;if(!X.textureFormatReadable(At))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!X.textureTypeReadable(kt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(fe>=0&&fe<=q.width-Te&&be>=0&&be<=q.height-me){$.bindFramebuffer(A.FRAMEBUFFER,lt);const ht=A.createBuffer();A.bindBuffer(A.PIXEL_PACK_BUFFER,ht),A.bufferData(A.PIXEL_PACK_BUFFER,Be.byteLength,A.STREAM_READ),A.readPixels(fe,be,Te,me,Rt.convert(At),Rt.convert(kt),0);const Bt=O!==null?ae.get(O).__webglFramebuffer:null;$.bindFramebuffer(A.FRAMEBUFFER,Bt);const nn=A.fenceSync(A.SYNC_GPU_COMMANDS_COMPLETE,0);return A.flush(),await wz(A,nn,4),A.bindBuffer(A.PIXEL_PACK_BUFFER,ht),A.getBufferSubData(A.PIXEL_PACK_BUFFER,0,Be),A.deleteBuffer(ht),A.deleteSync(nn),Be}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(q,fe=null,be=0){q.isTexture!==!0&&(np("WebGLRenderer: copyFramebufferToTexture function signature has changed."),fe=arguments[0]||null,q=arguments[1]);const Te=Math.pow(2,-be),me=Math.floor(q.image.width*Te),Be=Math.floor(q.image.height*Te),Ye=fe!==null?fe.x:0,lt=fe!==null?fe.y:0;G.setTexture2D(q,0),A.copyTexSubImage2D(A.TEXTURE_2D,be,0,0,Ye,lt,me,Be),$.unbindTexture()},this.copyTextureToTexture=function(q,fe,be=null,Te=null,me=0){q.isTexture!==!0&&(np("WebGLRenderer: copyTextureToTexture function signature has changed."),Te=arguments[0]||null,q=arguments[1],fe=arguments[2],me=arguments[3]||0,be=null);let Be,Ye,lt,ut,At,kt,ht,Bt,nn;const Et=q.isCompressedTexture?q.mipmaps[me]:q.image;be!==null?(Be=be.max.x-be.min.x,Ye=be.max.y-be.min.y,lt=be.isBox3?be.max.z-be.min.z:1,ut=be.min.x,At=be.min.y,kt=be.isBox3?be.min.z:0):(Be=Et.width,Ye=Et.height,lt=Et.depth||1,ut=0,At=0,kt=0),Te!==null?(ht=Te.x,Bt=Te.y,nn=Te.z):(ht=0,Bt=0,nn=0);const Pt=Rt.convert(fe.format),zt=Rt.convert(fe.type);let Qe;fe.isData3DTexture?(G.setTexture3D(fe,0),Qe=A.TEXTURE_3D):fe.isDataArrayTexture||fe.isCompressedArrayTexture?(G.setTexture2DArray(fe,0),Qe=A.TEXTURE_2D_ARRAY):(G.setTexture2D(fe,0),Qe=A.TEXTURE_2D),A.pixelStorei(A.UNPACK_FLIP_Y_WEBGL,fe.flipY),A.pixelStorei(A.UNPACK_PREMULTIPLY_ALPHA_WEBGL,fe.premultiplyAlpha),A.pixelStorei(A.UNPACK_ALIGNMENT,fe.unpackAlignment);const jn=A.getParameter(A.UNPACK_ROW_LENGTH),qt=A.getParameter(A.UNPACK_IMAGE_HEIGHT),jr=A.getParameter(A.UNPACK_SKIP_PIXELS),lr=A.getParameter(A.UNPACK_SKIP_ROWS),$r=A.getParameter(A.UNPACK_SKIP_IMAGES);A.pixelStorei(A.UNPACK_ROW_LENGTH,Et.width),A.pixelStorei(A.UNPACK_IMAGE_HEIGHT,Et.height),A.pixelStorei(A.UNPACK_SKIP_PIXELS,ut),A.pixelStorei(A.UNPACK_SKIP_ROWS,At),A.pixelStorei(A.UNPACK_SKIP_IMAGES,kt);const tl=q.isDataArrayTexture||q.isData3DTexture,bn=fe.isDataArrayTexture||fe.isData3DTexture;if(q.isRenderTargetTexture||q.isDepthTexture){const Mi=ae.get(q),nl=ae.get(fe),$n=ae.get(Mi.__renderTarget),Ko=ae.get(nl.__renderTarget);$.bindFramebuffer(A.READ_FRAMEBUFFER,$n.__webglFramebuffer),$.bindFramebuffer(A.DRAW_FRAMEBUFFER,Ko.__webglFramebuffer);for(let Yo=0;Yo0&&(n.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(n.object.backgroundIntensity=this.backgroundIntensity),n.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(n.object.environmentIntensity=this.environmentIntensity),n.object.environmentRotation=this.environmentRotation.toArray(),n}}class DO extends or{constructor(e=null,n=1,r=1,i,s,o,a,c,l=vr,u=vr,h,p){super(null,o,a,c,l,u,i,s,h,p),this.isDataTexture=!0,this.image={data:e,width:n,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class PG extends Vc{static get type(){return"PointsMaterial"}constructor(e){super(),this.isPointsMaterial=!0,this.color=new ln(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const $R=new ar,NE=new Sb,p0=new Pv,m0=new xe;class DG extends cs{constructor(e=new Bo,n=new PG){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=n,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,n){const r=this.geometry,i=this.matrixWorld,s=e.params.Points.threshold,o=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),p0.copy(r.boundingSphere),p0.applyMatrix4(i),p0.radius+=s,e.ray.intersectsSphere(p0)===!1)return;$R.copy(i).invert(),NE.copy(e.ray).applyMatrix4($R);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=r.index,h=r.attributes.position;if(l!==null){const p=Math.max(0,o.start),m=Math.min(l.count,o.start+o.count);for(let g=p,v=m;g0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;si.far)return;s.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}class UG extends or{constructor(e,n,r,i,s,o,a,c,l){super(e,n,r,i,s,o,a,c,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class FG extends Vc{static get type(){return"MeshNormalMaterial"}constructor(e){super(),this.isMeshNormalMaterial=!0,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=xO,this.normalScale=new St(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}const XR={enabled:!1,files:{},add:function(t,e){this.enabled!==!1&&(this.files[t]=e)},get:function(t){if(this.enabled!==!1)return this.files[t]},remove:function(t){delete this.files[t]},clear:function(){this.files={}}};class BG{constructor(e,n,r){const i=this;let s=!1,o=0,a=0,c;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=n,this.onError=r,this.itemStart=function(u){a++,s===!1&&i.onStart!==void 0&&i.onStart(u,o,a),s=!0},this.itemEnd=function(u){o++,i.onProgress!==void 0&&i.onProgress(u,o,a),o===a&&(s=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(u){i.onError!==void 0&&i.onError(u)},this.resolveURL=function(u){return c?c(u):u},this.setURLModifier=function(u){return c=u,this},this.addHandler=function(u,h){return l.push(u,h),this},this.removeHandler=function(u){const h=l.indexOf(u);return h!==-1&&l.splice(h,2),this},this.getHandler=function(u){for(let h=0,p=l.length;h=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,n){return n.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,JR).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:kv}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=kv);var UO={exports:{}},ch={};/** - * @license React - * react-reconciler-constants.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ch.ConcurrentRoot=1;ch.ContinuousEventPriority=4;ch.DefaultEventPriority=16;ch.DiscreteEventPriority=1;ch.IdleEventPriority=536870912;ch.LegacyRoot=0;UO.exports=ch;var df=UO.exports;function jG(t){let e;const n=new Set,r=(l,u)=>{const h=typeof l=="function"?l(e):l;if(h!==e){const p=e;e=u?h:Object.assign({},e,h),n.forEach(m=>m(e,p))}},i=()=>e,s=(l,u=i,h=Object.is)=>{console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware");let p=u(e);function m(){const g=u(e);if(!h(p,g)){const v=p;l(p=g,v)}}return n.add(m),()=>n.delete(m)},c={setState:r,getState:i,subscribe:(l,u,h)=>u||h?s(l,u,h):(n.add(l),()=>n.delete(l)),destroy:()=>n.clear()};return e=t(r,i,c),c}const $G=typeof window>"u"||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent),QR=$G?Ne.useEffect:Ne.useLayoutEffect;function qG(t){const e=typeof t=="function"?jG(t):t,n=(r=e.getState,i=Object.is)=>{const[,s]=Ne.useReducer(y=>y+1,0),o=e.getState(),a=Ne.useRef(o),c=Ne.useRef(r),l=Ne.useRef(i),u=Ne.useRef(!1),h=Ne.useRef();h.current===void 0&&(h.current=r(o));let p,m=!1;(a.current!==o||c.current!==r||l.current!==i||u.current)&&(p=r(o),m=!i(h.current,p)),QR(()=>{m&&(h.current=p),a.current=o,c.current=r,l.current=i,u.current=!1});const g=Ne.useRef(o);QR(()=>{const y=()=>{try{const S=e.getState(),E=c.current(S);l.current(h.current,E)||(a.current=S,h.current=E,s())}catch{u.current=!0,s()}},_=e.subscribe(y);return e.getState()!==g.current&&y(),_},[]);const v=m?p:h.current;return Ne.useDebugValue(v),v};return Object.assign(n,e),n[Symbol.iterator]=function(){console.warn("[useStore, api] = create() is deprecated and will be removed in v4");const r=[n,e];return{next(){const i=r.length<=0;return{value:r.shift(),done:i}}}},n}const XG=t=>typeof t=="object"&&typeof t.then=="function",Pu=[];function FO(t,e,n=(r,i)=>r===i){if(t===e)return!0;if(!t||!e)return!1;const r=t.length;if(e.length!==r)return!1;for(let i=0;i0&&(s.timeout&&clearTimeout(s.timeout),s.timeout=setTimeout(s.remove,r.lifespan)),s.response;if(!n)throw s.promise}const i={keys:e,equal:r.equal,remove:()=>{const s=Pu.indexOf(i);s!==-1&&Pu.splice(s,1)},promise:(XG(t)?t:t(...e)).then(s=>{i.response=s,r.lifespan&&r.lifespan>0&&(i.timeout=setTimeout(i.remove,r.lifespan))}).catch(s=>i.error=s)};if(Pu.push(i),!n)throw i.promise}const KG=(t,e,n)=>BO(t,e,!1,n),YG=(t,e,n)=>void BO(t,e,!0,n),ZG=t=>{if(t===void 0||t.length===0)Pu.splice(0,Pu.length);else{const e=Pu.find(n=>FO(t,n.keys,n.equal));e&&e.remove()}};var zO={exports:{}},VO={exports:{}},HO={};/** - * @license React - * scheduler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */(function(t){function e(z,W){var K=z.length;z.push(W);e:for(;0>>1,Y=z[j];if(0>>1;ji(re,K))wei(Ae,re)?(z[j]=Ae,z[we]=K,j=we):(z[j]=re,z[Q]=K,j=Q);else if(wei(Ae,K))z[j]=Ae,z[we]=K,j=we;else break e}}return W}function i(z,W){var K=z.sortIndex-W.sortIndex;return K!==0?K:z.id-W.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();t.unstable_now=function(){return o.now()-a}}var c=[],l=[],u=1,h=null,p=3,m=!1,g=!1,v=!1,y=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(z){for(var W=n(l);W!==null;){if(W.callback===null)r(l);else if(W.startTime<=z)r(l),W.sortIndex=W.expirationTime,e(c,W);else break;W=n(l)}}function b(z){if(v=!1,E(z),!g)if(n(c)!==null)g=!0,V(N);else{var W=n(l);W!==null&&B(b,W.startTime-z)}}function N(z,W){g=!1,v&&(v=!1,_(O),O=-1),m=!0;var K=p;try{for(E(W),h=n(c);h!==null&&(!(h.expirationTime>W)||z&&!U());){var j=h.callback;if(typeof j=="function"){h.callback=null,p=h.priorityLevel;var Y=j(h.expirationTime<=W);W=t.unstable_now(),typeof Y=="function"?h.callback=Y:h===n(c)&&r(c),E(W)}else r(c);h=n(c)}if(h!==null)var ge=!0;else{var Q=n(l);Q!==null&&B(b,Q.startTime-W),ge=!1}return ge}finally{h=null,p=K,m=!1}}var R=!1,M=null,O=-1,C=5,I=-1;function U(){return!(t.unstable_now()-Iz||125j?(z.sortIndex=K,e(l,z),n(c)===null&&z===n(l)&&(v?(_(O),O=-1):v=!0,B(b,K-j))):(z.sortIndex=Y,e(c,z),g||m||(g=!0,V(N))),z},t.unstable_shouldYield=U,t.unstable_wrapCallback=function(z){var W=p;return function(){var K=p;p=W;try{return z.apply(this,arguments)}finally{p=K}}}})(HO);VO.exports=HO;var IE=VO.exports;/** - * @license React - * react-reconciler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var JG=function(e){var n={},r=Ne,i=IE,s=Object.assign;function o(f){for(var d="https://reactjs.org/docs/error-decoder.html?invariant="+f,x=1;xoe||k[J]!==F[oe]){var Re=` -`+k[J].replace(" at new "," at ");return f.displayName&&Re.includes("")&&(Re=Re.replace("",f.displayName)),Re}while(1<=J&&0<=oe);break}}}finally{ut=!1,Error.prepareStackTrace=x}return(f=f?f.displayName||f.name:"")?lt(f):""}var kt=Object.prototype.hasOwnProperty,ht=[],Bt=-1;function nn(f){return{current:f}}function Et(f){0>Bt||(f.current=ht[Bt],ht[Bt]=null,Bt--)}function Pt(f,d){Bt++,ht[Bt]=f.current,f.current=d}var zt={},Qe=nn(zt),jn=nn(!1),qt=zt;function jr(f,d){var x=f.type.contextTypes;if(!x)return zt;var w=f.stateNode;if(w&&w.__reactInternalMemoizedUnmaskedChildContext===d)return w.__reactInternalMemoizedMaskedChildContext;var k={},F;for(F in x)k[F]=d[F];return w&&(f=f.stateNode,f.__reactInternalMemoizedUnmaskedChildContext=d,f.__reactInternalMemoizedMaskedChildContext=k),k}function lr(f){return f=f.childContextTypes,f!=null}function $r(){Et(jn),Et(Qe)}function tl(f,d,x){if(Qe.current!==zt)throw Error(o(168));Pt(Qe,d),Pt(jn,x)}function bn(f,d,x){var w=f.stateNode;if(d=d.childContextTypes,typeof w.getChildContext!="function")return x;w=w.getChildContext();for(var k in w)if(!(k in d))throw Error(o(108,O(f)||"Unknown",k));return s({},x,w)}function Mi(f){return f=(f=f.stateNode)&&f.__reactInternalMemoizedMergedChildContext||zt,qt=Qe.current,Pt(Qe,f),Pt(jn,jn.current),!0}function nl(f,d,x){var w=f.stateNode;if(!w)throw Error(o(169));x?(f=bn(f,d,qt),w.__reactInternalMemoizedMergedChildContext=f,Et(jn),Et(Qe),Pt(Qe,f)):Et(jn),Pt(jn,x)}var $n=Math.clz32?Math.clz32:Qm,Ko=Math.log,Yo=Math.LN2;function Qm(f){return f>>>=0,f===0?32:31-(Ko(f)/Yo|0)|0}var eg=64,tg=4194304;function Ed(f){switch(f&-f){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 f&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return f&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return f}}function ng(f,d){var x=f.pendingLanes;if(x===0)return 0;var w=0,k=f.suspendedLanes,F=f.pingedLanes,J=x&268435455;if(J!==0){var oe=J&~k;oe!==0?w=Ed(oe):(F&=J,F!==0&&(w=Ed(F)))}else J=x&~k,J!==0?w=Ed(J):F!==0&&(w=Ed(F));if(w===0)return 0;if(d!==0&&d!==w&&!(d&k)&&(k=w&-w,F=d&-d,k>=F||k===16&&(F&4194240)!==0))return d;if(w&4&&(w|=x&16),d=f.entangledLanes,d!==0)for(f=f.entanglements,d&=w;0x;x++)d.push(f);return d}function wd(f,d,x){f.pendingLanes|=d,d!==536870912&&(f.suspendedLanes=0,f.pingedLanes=0),f=f.eventTimes,d=31-$n(d),f[d]=x}function lB(f,d){var x=f.pendingLanes&~d;f.pendingLanes=d,f.suspendedLanes=0,f.pingedLanes=0,f.expiredLanes&=d,f.mutableReadLanes&=d,f.entangledLanes&=d,d=f.entanglements;var w=f.eventTimes;for(f=f.expirationTimes;0>=J,k-=J,Ka=1<<32-$n(d)+k|x<pn?(Kr=Ot,Ot=null):Kr=Ot.sibling;var mn=xt(Se,Ot,Me[pn],tt);if(mn===null){Ot===null&&(Ot=Kr);break}f&&Ot&&mn.alternate===null&&d(Se,Ot),de=F(mn,de,pn),Ut===null?pt=mn:Ut.sibling=mn,Ut=mn,Ot=Kr}if(pn===Me.length)return x(Se,Ot),qn&&tu(Se,pn),pt;if(Ot===null){for(;pnpn?(Kr=Ot,Ot=null):Kr=Ot.sibling;var ul=xt(Se,Ot,mn.value,tt);if(ul===null){Ot===null&&(Ot=Kr);break}f&&Ot&&ul.alternate===null&&d(Se,Ot),de=F(ul,de,pn),Ut===null?pt=ul:Ut.sibling=ul,Ut=ul,Ot=Kr}if(mn.done)return x(Se,Ot),qn&&tu(Se,pn),pt;if(Ot===null){for(;!mn.done;pn++,mn=Me.next())mn=It(Se,mn.value,tt),mn!==null&&(de=F(mn,de,pn),Ut===null?pt=mn:Ut.sibling=mn,Ut=mn);return qn&&tu(Se,pn),pt}for(Ot=w(Se,Ot);!mn.done;pn++,mn=Me.next())mn=Nn(Ot,Se,pn,mn.value,tt),mn!==null&&(f&&mn.alternate!==null&&Ot.delete(mn.key===null?pn:mn.key),de=F(mn,de,pn),Ut===null?pt=mn:Ut.sibling=mn,Ut=mn);return f&&Ot.forEach(function(XB){return d(Se,XB)}),qn&&tu(Se,pn),pt}function $s(Se,de,Me,tt){if(typeof Me=="object"&&Me!==null&&Me.type===u&&Me.key===null&&(Me=Me.props.children),typeof Me=="object"&&Me!==null){switch(Me.$$typeof){case c:e:{for(var pt=Me.key,Ut=de;Ut!==null;){if(Ut.key===pt){if(pt=Me.type,pt===u){if(Ut.tag===7){x(Se,Ut.sibling),de=k(Ut,Me.props.children),de.return=Se,Se=de;break e}}else if(Ut.elementType===pt||typeof pt=="object"&&pt!==null&&pt.$$typeof===E&&CM(pt)===Ut.type){x(Se,Ut.sibling),de=k(Ut,Me.props),de.ref=Ad(Se,Ut,Me),de.return=Se,Se=de;break e}x(Se,Ut);break}else d(Se,Ut);Ut=Ut.sibling}Me.type===u?(de=cu(Me.props.children,Se.mode,tt,Me.key),de.return=Se,Se=de):(tt=Wg(Me.type,Me.key,Me.props,null,Se.mode,tt),tt.ref=Ad(Se,de,Me),tt.return=Se,Se=tt)}return J(Se);case l:e:{for(Ut=Me.key;de!==null;){if(de.key===Ut)if(de.tag===4&&de.stateNode.containerInfo===Me.containerInfo&&de.stateNode.implementation===Me.implementation){x(Se,de.sibling),de=k(de,Me.children||[]),de.return=Se,Se=de;break e}else{x(Se,de);break}else d(Se,de);de=de.sibling}de=c1(Me,Se.mode,tt),de.return=Se,Se=de}return J(Se);case E:return Ut=Me._init,$s(Se,de,Ut(Me._payload),tt)}if(H(Me))return gt(Se,de,Me,tt);if(R(Me))return _i(Se,de,Me,tt);dg(Se,Me)}return typeof Me=="string"&&Me!==""||typeof Me=="number"?(Me=""+Me,de!==null&&de.tag===6?(x(Se,de.sibling),de=k(de,Me),de.return=Se,Se=de):(x(Se,de),de=a1(Me,Se.mode,tt),de.return=Se,Se=de),J(Se)):x(Se,de)}return $s}var Rh=RM(!0),NM=RM(!1),Md={},Hs=nn(Md),Cd=nn(Md),Nh=nn(Md);function ta(f){if(f===Md)throw Error(o(174));return f}function Tx(f,d){Pt(Nh,d),Pt(Cd,f),Pt(Hs,Md),f=B(d),Et(Hs),Pt(Hs,f)}function kh(){Et(Hs),Et(Cd),Et(Nh)}function kM(f){var d=ta(Nh.current),x=ta(Hs.current);d=z(x,f.type,d),x!==d&&(Pt(Cd,f),Pt(Hs,d))}function Ax(f){Cd.current===f&&(Et(Hs),Et(Cd))}var Kn=nn(0);function pg(f){for(var d=f;d!==null;){if(d.tag===13){var x=d.memoizedState;if(x!==null&&(x=x.dehydrated,x===null||Xo(x)||Ql(x)))return d}else if(d.tag===19&&d.memoizedProps.revealOrder!==void 0){if(d.flags&128)return d}else if(d.child!==null){d.child.return=d,d=d.child;continue}if(d===f)break;for(;d.sibling===null;){if(d.return===null||d.return===f)return null;d=d.return}d.sibling.return=d.return,d=d.sibling}return null}var Mx=[];function Cx(){for(var f=0;fx?x:4,f(!0);var w=Gs.transition;Gs.transition={};try{f(!1),d()}finally{dn=x,Gs.transition=w}}function jM(){return na().memoizedState}function SB(f,d,x){var w=al(f);x={lane:w,action:x,hasEagerState:!1,eagerState:null,next:null},$M(f)?qM(d,x):(XM(f,d,x),x=Ri(),f=Ws(f,w,x),f!==null&&KM(f,d,w))}function EB(f,d,x){var w=al(f),k={lane:w,action:x,hasEagerState:!1,eagerState:null,next:null};if($M(f))qM(d,k);else{XM(f,d,k);var F=f.alternate;if(f.lanes===0&&(F===null||F.lanes===0)&&(F=d.lastRenderedReducer,F!==null))try{var J=d.lastRenderedState,oe=F(J,x);if(k.hasEagerState=!0,k.eagerState=oe,Jo(oe,J))return}catch{}finally{}x=Ri(),f=Ws(f,w,x),f!==null&&KM(f,d,w)}}function $M(f){var d=f.alternate;return f===er||d!==null&&d===er}function qM(f,d){Rd=gg=!0;var x=f.pending;x===null?d.next=d:(d.next=x.next,x.next=d),f.pending=d}function XM(f,d,x){xr!==null&&f.mode&1&&!(Vt&2)?(f=d.interleaved,f===null?(x.next=x,ea===null?ea=[d]:ea.push(d)):(x.next=f.next,f.next=x),d.interleaved=x):(f=d.pending,f===null?x.next=x:(x.next=f.next,f.next=x),d.pending=x)}function KM(f,d,x){if(x&4194240){var w=d.lanes;w&=f.pendingLanes,x|=w,d.lanes=x,cx(f,x)}}var Sg={readContext:Bs,useCallback:mi,useContext:mi,useEffect:mi,useImperativeHandle:mi,useInsertionEffect:mi,useLayoutEffect:mi,useMemo:mi,useReducer:mi,useRef:mi,useState:mi,useDebugValue:mi,useDeferredValue:mi,useTransition:mi,useMutableSource:mi,useSyncExternalStore:mi,useId:mi,unstable_isNewReconciler:!1},wB={readContext:Bs,useCallback:function(f,d){return Za().memoizedState=[f,d===void 0?null:d],f},useContext:Bs,useEffect:Ox,useImperativeHandle:function(f,d,x){return x=x!=null?x.concat([f]):null,yg(4194308,4,VM.bind(null,d,f),x)},useLayoutEffect:function(f,d){return yg(4194308,4,f,d)},useInsertionEffect:function(f,d){return yg(4,2,f,d)},useMemo:function(f,d){var x=Za();return d=d===void 0?null:d,f=f(),x.memoizedState=[f,d],f},useReducer:function(f,d,x){var w=Za();return d=x!==void 0?x(d):d,w.memoizedState=w.baseState=d,f={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:f,lastRenderedState:d},w.queue=f,f=f.dispatch=SB.bind(null,er,f),[w.memoizedState,f]},useRef:function(f){var d=Za();return f={current:f},d.memoizedState=f},useState:Ix,useDebugValue:Lx,useDeferredValue:function(f){var d=Ix(f),x=d[0],w=d[1];return Ox(function(){var k=Gs.transition;Gs.transition={};try{w(f)}finally{Gs.transition=k}},[f]),x},useTransition:function(){var f=Ix(!1),d=f[0];return f=xB.bind(null,f[1]),Za().memoizedState=f,[d,f]},useMutableSource:function(){},useSyncExternalStore:function(f,d,x){var w=er,k=Za();if(qn){if(x===void 0)throw Error(o(407));x=x()}else{if(x=d(),xr===null)throw Error(o(349));Ih&30||LM(w,d,x)}k.memoizedState=x;var F={value:x,getSnapshot:d};return k.queue=F,Ox(DM.bind(null,w,F,f),[f]),w.flags|=2048,kd(9,PM.bind(null,w,F,x,d),void 0,null),x},useId:function(){var f=Za(),d=xr.identifierPrefix;if(qn){var x=Ya,w=Ka;x=(w&~(1<<32-$n(w)-1)).toString(32)+x,d=":"+d+"R"+x,x=Nd++,0Qx&&(d.flags|=128,w=!0,Pd(k,!1),d.lanes=4194304)}else{if(!w)if(f=pg(F),f!==null){if(d.flags|=128,w=!0,f=f.updateQueue,f!==null&&(d.updateQueue=f,d.flags|=4),Pd(k,!0),k.tail===null&&k.tailMode==="hidden"&&!F.alternate&&!qn)return gi(d),null}else 2*qr()-k.renderingStartTime>Qx&&x!==1073741824&&(d.flags|=128,w=!0,Pd(k,!1),d.lanes=4194304);k.isBackwards?(F.sibling=d.child,d.child=F):(f=k.last,f!==null?f.sibling=F:d.child=F,k.last=F)}return k.tail!==null?(d=k.tail,k.rendering=d,k.tail=d.sibling,k.renderingStartTime=qr(),d.sibling=null,f=Kn.current,Pt(Kn,w?f&1|2:f&1),d):(gi(d),null);case 22:case 23:return i1(),w=d.memoizedState!==null,f!==null&&f.memoizedState!==null!==w&&(d.flags|=8192),w&&d.mode&1?ws&1073741824&&(gi(d),qe&&d.subtreeFlags&6&&(d.flags|=8192)):gi(d),null;case 24:return null;case 25:return null}throw Error(o(156,d.tag))}var CB=a.ReactCurrentOwner,Es=!1;function Ci(f,d,x,w){d.child=f===null?NM(d,null,x,w):Rh(d,f.child,x,w)}function rC(f,d,x,w,k){x=x.render;var F=d.ref;return Th(d,k),w=Nx(f,d,x,w,F,k),x=kx(),f!==null&&!Es?(d.updateQueue=f.updateQueue,d.flags&=-2053,f.lanes&=~k,Ja(f,d,k)):(qn&&x&&xx(d),d.flags|=1,Ci(f,d,w,k),d.child)}function iC(f,d,x,w,k){if(f===null){var F=x.type;return typeof F=="function"&&!o1(F)&&F.defaultProps===void 0&&x.compare===null&&x.defaultProps===void 0?(d.tag=15,d.type=F,sC(f,d,F,w,k)):(f=Wg(x.type,null,w,d,d.mode,k),f.ref=d.ref,f.return=d,d.child=f)}if(F=f.child,!(f.lanes&k)){var J=F.memoizedProps;if(x=x.compare,x=x!==null?x:sg,x(J,w)&&f.ref===d.ref)return Ja(f,d,k)}return d.flags|=1,f=ll(F,w),f.ref=d.ref,f.return=d,d.child=f}function sC(f,d,x,w,k){if(f!==null&&sg(f.memoizedProps,w)&&f.ref===d.ref)if(Es=!1,(f.lanes&k)!==0)f.flags&131072&&(Es=!0);else return d.lanes=f.lanes,Ja(f,d,k);return Ux(f,d,x,w,k)}function oC(f,d,x){var w=d.pendingProps,k=w.children,F=f!==null?f.memoizedState:null;if(w.mode==="hidden")if(!(d.mode&1))d.memoizedState={baseLanes:0,cachePool:null},Pt(Oh,ws),ws|=x;else if(x&1073741824)d.memoizedState={baseLanes:0,cachePool:null},w=F!==null?F.baseLanes:x,Pt(Oh,ws),ws|=w;else return f=F!==null?F.baseLanes|x:x,d.lanes=d.childLanes=1073741824,d.memoizedState={baseLanes:f,cachePool:null},d.updateQueue=null,Pt(Oh,ws),ws|=f,null;else F!==null?(w=F.baseLanes|x,d.memoizedState=null):w=x,Pt(Oh,ws),ws|=w;return Ci(f,d,k,x),d.child}function aC(f,d){var x=d.ref;(f===null&&x!==null||f!==null&&f.ref!==x)&&(d.flags|=512,d.flags|=2097152)}function Ux(f,d,x,w,k){var F=lr(x)?qt:Qe.current;return F=jr(d,F),Th(d,k),x=Nx(f,d,x,w,F,k),w=kx(),f!==null&&!Es?(d.updateQueue=f.updateQueue,d.flags&=-2053,f.lanes&=~k,Ja(f,d,k)):(qn&&w&&xx(d),d.flags|=1,Ci(f,d,x,k),d.child)}function cC(f,d,x,w,k){if(lr(x)){var F=!0;Mi(d)}else F=!1;if(Th(d,k),d.stateNode===null)f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),EM(d,x,w),yx(d,x,w,k),w=!0;else if(f===null){var J=d.stateNode,oe=d.memoizedProps;J.props=oe;var Re=J.context,Fe=x.contextType;typeof Fe=="object"&&Fe!==null?Fe=Bs(Fe):(Fe=lr(x)?qt:Qe.current,Fe=jr(d,Fe));var at=x.getDerivedStateFromProps,It=typeof at=="function"||typeof J.getSnapshotBeforeUpdate=="function";It||typeof J.UNSAFE_componentWillReceiveProps!="function"&&typeof J.componentWillReceiveProps!="function"||(oe!==w||Re!==Fe)&&wM(d,J,w,Fe),rl=!1;var xt=d.memoizedState;J.state=xt,lg(d,w,J,k),Re=d.memoizedState,oe!==w||xt!==Re||jn.current||rl?(typeof at=="function"&&(vx(d,x,at,w),Re=d.memoizedState),(oe=rl||SM(d,x,oe,w,xt,Re,Fe))?(It||typeof J.UNSAFE_componentWillMount!="function"&&typeof J.componentWillMount!="function"||(typeof J.componentWillMount=="function"&&J.componentWillMount(),typeof J.UNSAFE_componentWillMount=="function"&&J.UNSAFE_componentWillMount()),typeof J.componentDidMount=="function"&&(d.flags|=4194308)):(typeof J.componentDidMount=="function"&&(d.flags|=4194308),d.memoizedProps=w,d.memoizedState=Re),J.props=w,J.state=Re,J.context=Fe,w=oe):(typeof J.componentDidMount=="function"&&(d.flags|=4194308),w=!1)}else{J=d.stateNode,_M(f,d),oe=d.memoizedProps,Fe=d.type===d.elementType?oe:go(d.type,oe),J.props=Fe,It=d.pendingProps,xt=J.context,Re=x.contextType,typeof Re=="object"&&Re!==null?Re=Bs(Re):(Re=lr(x)?qt:Qe.current,Re=jr(d,Re));var Nn=x.getDerivedStateFromProps;(at=typeof Nn=="function"||typeof J.getSnapshotBeforeUpdate=="function")||typeof J.UNSAFE_componentWillReceiveProps!="function"&&typeof J.componentWillReceiveProps!="function"||(oe!==It||xt!==Re)&&wM(d,J,w,Re),rl=!1,xt=d.memoizedState,J.state=xt,lg(d,w,J,k);var gt=d.memoizedState;oe!==It||xt!==gt||jn.current||rl?(typeof Nn=="function"&&(vx(d,x,Nn,w),gt=d.memoizedState),(Fe=rl||SM(d,x,Fe,w,xt,gt,Re)||!1)?(at||typeof J.UNSAFE_componentWillUpdate!="function"&&typeof J.componentWillUpdate!="function"||(typeof J.componentWillUpdate=="function"&&J.componentWillUpdate(w,gt,Re),typeof J.UNSAFE_componentWillUpdate=="function"&&J.UNSAFE_componentWillUpdate(w,gt,Re)),typeof J.componentDidUpdate=="function"&&(d.flags|=4),typeof J.getSnapshotBeforeUpdate=="function"&&(d.flags|=1024)):(typeof J.componentDidUpdate!="function"||oe===f.memoizedProps&&xt===f.memoizedState||(d.flags|=4),typeof J.getSnapshotBeforeUpdate!="function"||oe===f.memoizedProps&&xt===f.memoizedState||(d.flags|=1024),d.memoizedProps=w,d.memoizedState=gt),J.props=w,J.state=gt,J.context=Re,w=Fe):(typeof J.componentDidUpdate!="function"||oe===f.memoizedProps&&xt===f.memoizedState||(d.flags|=4),typeof J.getSnapshotBeforeUpdate!="function"||oe===f.memoizedProps&&xt===f.memoizedState||(d.flags|=1024),w=!1)}return Fx(f,d,x,w,F,k)}function Fx(f,d,x,w,k,F){aC(f,d);var J=(d.flags&128)!==0;if(!w&&!J)return k&&nl(d,x,!1),Ja(f,d,F);w=d.stateNode,CB.current=d;var oe=J&&typeof x.getDerivedStateFromError!="function"?null:w.render();return d.flags|=1,f!==null&&J?(d.child=Rh(d,f.child,null,F),d.child=Rh(d,null,oe,F)):Ci(f,d,oe,F),d.memoizedState=w.state,k&&nl(d,x,!0),d.child}function lC(f){var d=f.stateNode;d.pendingContext?tl(f,d.pendingContext,d.pendingContext!==d.context):d.context&&tl(f,d.context,!1),Tx(f,d.containerInfo)}function uC(f,d,x,w,k){return Ch(),bx(k),d.flags|=256,Ci(f,d,x,w),d.child}var bg={dehydrated:null,treeContext:null,retryLane:0};function Tg(f){return{baseLanes:f,cachePool:null}}function hC(f,d,x){var w=d.pendingProps,k=Kn.current,F=!1,J=(d.flags&128)!==0,oe;if((oe=J)||(oe=f!==null&&f.memoizedState===null?!1:(k&2)!==0),oe?(F=!0,d.flags&=-129):(f===null||f.memoizedState!==null)&&(k|=1),Pt(Kn,k&1),f===null)return wx(d),f=d.memoizedState,f!==null&&(f=f.dehydrated,f!==null)?(d.mode&1?Ql(f)?d.lanes=8:d.lanes=1073741824:d.lanes=1,null):(k=w.children,f=w.fallback,F?(w=d.mode,F=d.child,k={mode:"hidden",children:k},!(w&1)&&F!==null?(F.childLanes=0,F.pendingProps=k):F=jg(k,w,0,null),f=cu(f,w,x,null),F.return=d,f.return=d,F.sibling=f,d.child=F,d.child.memoizedState=Tg(x),d.memoizedState=bg,f):Bx(d,k));if(k=f.memoizedState,k!==null){if(oe=k.dehydrated,oe!==null){if(J)return d.flags&256?(d.flags&=-257,Ag(f,d,x,Error(o(422)))):d.memoizedState!==null?(d.child=f.child,d.flags|=128,null):(F=w.fallback,k=d.mode,w=jg({mode:"visible",children:w.children},k,0,null),F=cu(F,k,x,null),F.flags|=2,w.return=d,F.return=d,w.sibling=F,d.child=w,d.mode&1&&Rh(d,f.child,null,x),d.child.memoizedState=Tg(x),d.memoizedState=bg,F);if(!(d.mode&1))d=Ag(f,d,x,null);else if(Ql(oe))d=Ag(f,d,x,Error(o(419)));else if(w=(x&f.childLanes)!==0,Es||w){if(w=xr,w!==null){switch(x&-x){case 4:F=2;break;case 16:F=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:F=32;break;case 536870912:F=268435456;break;default:F=0}w=F&(w.suspendedLanes|x)?0:F,w!==0&&w!==k.retryLane&&(k.retryLane=w,Ws(f,w,-1))}s1(),d=Ag(f,d,x,Error(o(421)))}else Xo(oe)?(d.flags|=128,d.child=f.child,d=VB.bind(null,f),Xm(oe,d),d=null):(x=k.treeContext,De&&(Ss=wh(oe),xs=d,qn=!0,_o=null,bd=!1,x!==null&&(zs[Vs++]=Ka,zs[Vs++]=Ya,zs[Vs++]=eu,Ka=x.id,Ya=x.overflow,eu=d)),d=Bx(d,d.pendingProps.children),d.flags|=4096);return d}return F?(w=dC(f,d,w.children,w.fallback,x),F=d.child,k=f.child.memoizedState,F.memoizedState=k===null?Tg(x):{baseLanes:k.baseLanes|x,cachePool:null},F.childLanes=f.childLanes&~x,d.memoizedState=bg,w):(x=fC(f,d,w.children,x),d.memoizedState=null,x)}return F?(w=dC(f,d,w.children,w.fallback,x),F=d.child,k=f.child.memoizedState,F.memoizedState=k===null?Tg(x):{baseLanes:k.baseLanes|x,cachePool:null},F.childLanes=f.childLanes&~x,d.memoizedState=bg,w):(x=fC(f,d,w.children,x),d.memoizedState=null,x)}function Bx(f,d){return d=jg({mode:"visible",children:d},f.mode,0,null),d.return=f,f.child=d}function fC(f,d,x,w){var k=f.child;return f=k.sibling,x=ll(k,{mode:"visible",children:x}),!(d.mode&1)&&(x.lanes=w),x.return=d,x.sibling=null,f!==null&&(w=d.deletions,w===null?(d.deletions=[f],d.flags|=16):w.push(f)),d.child=x}function dC(f,d,x,w,k){var F=d.mode;f=f.child;var J=f.sibling,oe={mode:"hidden",children:x};return!(F&1)&&d.child!==f?(x=d.child,x.childLanes=0,x.pendingProps=oe,d.deletions=null):(x=ll(f,oe),x.subtreeFlags=f.subtreeFlags&14680064),J!==null?w=ll(J,w):(w=cu(w,F,k,null),w.flags|=2),w.return=d,x.return=d,x.sibling=w,d.child=x,w}function Ag(f,d,x,w){return w!==null&&bx(w),Rh(d,f.child,null,x),f=Bx(d,d.pendingProps.children),f.flags|=2,d.memoizedState=null,f}function pC(f,d,x){f.lanes|=d;var w=f.alternate;w!==null&&(w.lanes|=d),gx(f.return,d,x)}function zx(f,d,x,w,k){var F=f.memoizedState;F===null?f.memoizedState={isBackwards:d,rendering:null,renderingStartTime:0,last:w,tail:x,tailMode:k}:(F.isBackwards=d,F.rendering=null,F.renderingStartTime=0,F.last=w,F.tail=x,F.tailMode=k)}function mC(f,d,x){var w=d.pendingProps,k=w.revealOrder,F=w.tail;if(Ci(f,d,w.children,x),w=Kn.current,w&2)w=w&1|2,d.flags|=128;else{if(f!==null&&f.flags&128)e:for(f=d.child;f!==null;){if(f.tag===13)f.memoizedState!==null&&pC(f,x,d);else if(f.tag===19)pC(f,x,d);else if(f.child!==null){f.child.return=f,f=f.child;continue}if(f===d)break e;for(;f.sibling===null;){if(f.return===null||f.return===d)break e;f=f.return}f.sibling.return=f.return,f=f.sibling}w&=1}if(Pt(Kn,w),!(d.mode&1))d.memoizedState=null;else switch(k){case"forwards":for(x=d.child,k=null;x!==null;)f=x.alternate,f!==null&&pg(f)===null&&(k=x),x=x.sibling;x=k,x===null?(k=d.child,d.child=null):(k=x.sibling,x.sibling=null),zx(d,!1,k,x,F);break;case"backwards":for(x=null,k=d.child,d.child=null;k!==null;){if(f=k.alternate,f!==null&&pg(f)===null){d.child=k;break}f=k.sibling,k.sibling=x,x=k,k=f}zx(d,!0,x,null,F);break;case"together":zx(d,!1,null,null,void 0);break;default:d.memoizedState=null}return d.child}function Ja(f,d,x){if(f!==null&&(d.dependencies=f.dependencies),Lh|=d.lanes,!(x&d.childLanes))return null;if(f!==null&&d.child!==f.child)throw Error(o(153));if(d.child!==null){for(f=d.child,x=ll(f,f.pendingProps),d.child=x,x.return=d;f.sibling!==null;)f=f.sibling,x=x.sibling=ll(f,f.pendingProps),x.return=d;x.sibling=null}return d.child}function RB(f,d,x){switch(d.tag){case 3:lC(d),Ch();break;case 5:kM(d);break;case 1:lr(d.type)&&Mi(d);break;case 4:Tx(d,d.stateNode.containerInfo);break;case 10:gM(d,d.type._context,d.memoizedProps.value);break;case 13:var w=d.memoizedState;if(w!==null)return w.dehydrated!==null?(Pt(Kn,Kn.current&1),d.flags|=128,null):x&d.child.childLanes?hC(f,d,x):(Pt(Kn,Kn.current&1),f=Ja(f,d,x),f!==null?f.sibling:null);Pt(Kn,Kn.current&1);break;case 19:if(w=(x&d.childLanes)!==0,f.flags&128){if(w)return mC(f,d,x);d.flags|=128}var k=d.memoizedState;if(k!==null&&(k.rendering=null,k.tail=null,k.lastEffect=null),Pt(Kn,Kn.current),w)break;return null;case 22:case 23:return d.lanes=0,oC(f,d,x)}return Ja(f,d,x)}function NB(f,d){switch(Sx(d),d.tag){case 1:return lr(d.type)&&$r(),f=d.flags,f&65536?(d.flags=f&-65537|128,d):null;case 3:return kh(),Et(jn),Et(Qe),Cx(),f=d.flags,f&65536&&!(f&128)?(d.flags=f&-65537|128,d):null;case 5:return Ax(d),null;case 13:if(Et(Kn),f=d.memoizedState,f!==null&&f.dehydrated!==null){if(d.alternate===null)throw Error(o(340));Ch()}return f=d.flags,f&65536?(d.flags=f&-65537|128,d):null;case 19:return Et(Kn),null;case 4:return kh(),null;case 10:return mx(d.type._context),null;case 22:case 23:return i1(),null;case 24:return null;default:return null}}var Mg=!1,ru=!1,kB=typeof WeakSet=="function"?WeakSet:Set,Ze=null;function Cg(f,d){var x=f.ref;if(x!==null)if(typeof x=="function")try{x(null)}catch(w){Ji(f,d,w)}else x.current=null}function Vx(f,d,x){try{x()}catch(w){Ji(f,d,w)}}var gC=!1;function IB(f,d){for(W(f.containerInfo),Ze=d;Ze!==null;)if(f=Ze,d=f.child,(f.subtreeFlags&1028)!==0&&d!==null)d.return=f,Ze=d;else for(;Ze!==null;){f=Ze;try{var x=f.alternate;if(f.flags&1024)switch(f.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var w=x.memoizedProps,k=x.memoizedState,F=f.stateNode,J=F.getSnapshotBeforeUpdate(f.elementType===f.type?w:go(f.type,w),k);F.__reactInternalSnapshotBeforeUpdate=J}break;case 3:qe&&ke(f.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(o(163))}}catch(oe){Ji(f,f.return,oe)}if(d=f.sibling,d!==null){d.return=f.return,Ze=d;break}Ze=f.return}return x=gC,gC=!1,x}function iu(f,d,x){var w=d.updateQueue;if(w=w!==null?w.lastEffect:null,w!==null){var k=w=w.next;do{if((k.tag&f)===f){var F=k.destroy;k.destroy=void 0,F!==void 0&&Vx(d,x,F)}k=k.next}while(k!==w)}}function Dd(f,d){if(d=d.updateQueue,d=d!==null?d.lastEffect:null,d!==null){var x=d=d.next;do{if((x.tag&f)===f){var w=x.create;x.destroy=w()}x=x.next}while(x!==d)}}function Hx(f){var d=f.ref;if(d!==null){var x=f.stateNode;switch(f.tag){case 5:f=V(x);break;default:f=x}typeof d=="function"?d(f):d.current=f}}function _C(f,d,x){if(Zo&&typeof Zo.onCommitFiberUnmount=="function")try{Zo.onCommitFiberUnmount(rg,d)}catch{}switch(d.tag){case 0:case 11:case 14:case 15:if(f=d.updateQueue,f!==null&&(f=f.lastEffect,f!==null)){var w=f=f.next;do{var k=w,F=k.destroy;k=k.tag,F!==void 0&&(k&2||k&4)&&Vx(d,x,F),w=w.next}while(w!==f)}break;case 1:if(Cg(d,x),f=d.stateNode,typeof f.componentWillUnmount=="function")try{f.props=d.memoizedProps,f.state=d.memoizedState,f.componentWillUnmount()}catch(J){Ji(d,x,J)}break;case 5:Cg(d,x);break;case 4:qe?wC(f,d,x):it&&it&&(d=d.stateNode.containerInfo,x=Je(d),Nr(d,x))}}function vC(f,d,x){for(var w=d;;)if(_C(f,w,x),w.child===null||qe&&w.tag===4){if(w===d)break;for(;w.sibling===null;){if(w.return===null||w.return===d)return;w=w.return}w.sibling.return=w.return,w=w.sibling}else w.child.return=w,w=w.child}function yC(f){var d=f.alternate;d!==null&&(f.alternate=null,yC(d)),f.child=null,f.deletions=null,f.sibling=null,f.tag===5&&(d=f.stateNode,d!==null&&X(d)),f.stateNode=null,f.return=null,f.dependencies=null,f.memoizedProps=null,f.memoizedState=null,f.pendingProps=null,f.stateNode=null,f.updateQueue=null}function xC(f){return f.tag===5||f.tag===3||f.tag===4}function SC(f){e:for(;;){for(;f.sibling===null;){if(f.return===null||xC(f.return))return null;f=f.return}for(f.sibling.return=f.return,f=f.sibling;f.tag!==5&&f.tag!==6&&f.tag!==18;){if(f.flags&2||f.child===null||f.tag===4)continue e;f.child.return=f,f=f.child}if(!(f.flags&2))return f.stateNode}}function EC(f){if(qe){e:{for(var d=f.return;d!==null;){if(xC(d))break e;d=d.return}throw Error(o(160))}var x=d;switch(x.tag){case 5:d=x.stateNode,x.flags&32&&(Rt(d),x.flags&=-33),x=SC(f),Wx(f,x,d);break;case 3:case 4:d=x.stateNode.containerInfo,x=SC(f),Gx(f,x,d);break;default:throw Error(o(161))}}}function Gx(f,d,x){var w=f.tag;if(w===5||w===6)f=f.stateNode,d?yt(x,f,d):Ge(x,f);else if(w!==4&&(f=f.child,f!==null))for(Gx(f,d,x),f=f.sibling;f!==null;)Gx(f,d,x),f=f.sibling}function Wx(f,d,x){var w=f.tag;if(w===5||w===6)f=f.stateNode,d?et(x,f,d):Oe(x,f);else if(w!==4&&(f=f.child,f!==null))for(Wx(f,d,x),f=f.sibling;f!==null;)Wx(f,d,x),f=f.sibling}function wC(f,d,x){for(var w=d,k=!1,F,J;;){if(!k){k=w.return;e:for(;;){if(k===null)throw Error(o(160));switch(F=k.stateNode,k.tag){case 5:J=!1;break e;case 3:F=F.containerInfo,J=!0;break e;case 4:F=F.containerInfo,J=!0;break e}k=k.return}k=!0}if(w.tag===5||w.tag===6)vC(f,w,x),J?Ct(F,w.stateNode):rt(F,w.stateNode);else if(w.tag===18)J?be(F,w.stateNode):fe(F,w.stateNode);else if(w.tag===4){if(w.child!==null){F=w.stateNode.containerInfo,J=!0,w.child.return=w,w=w.child;continue}}else if(_C(f,w,x),w.child!==null){w.child.return=w,w=w.child;continue}if(w===d)break;for(;w.sibling===null;){if(w.return===null||w.return===d)return;w=w.return,w.tag===4&&(k=!1)}w.sibling.return=w.return,w=w.sibling}}function jx(f,d){if(qe){switch(d.tag){case 0:case 11:case 14:case 15:iu(3,d,d.return),Dd(3,d),iu(5,d,d.return);return;case 1:return;case 5:var x=d.stateNode;if(x!=null){var w=d.memoizedProps;f=f!==null?f.memoizedProps:w;var k=d.type,F=d.updateQueue;d.updateQueue=null,F!==null&&nt(x,F,k,f,w,d)}return;case 6:if(d.stateNode===null)throw Error(o(162));x=d.memoizedProps,Lt(d.stateNode,f!==null?f.memoizedProps:x,x);return;case 3:De&&f!==null&&f.memoizedState.isDehydrated&&Jm(d.stateNode.containerInfo);return;case 12:return;case 13:Rg(d);return;case 19:Rg(d);return;case 17:return}throw Error(o(163))}switch(d.tag){case 0:case 11:case 14:case 15:iu(3,d,d.return),Dd(3,d),iu(5,d,d.return);return;case 12:return;case 13:Rg(d);return;case 19:Rg(d);return;case 3:De&&f!==null&&f.memoizedState.isDehydrated&&Jm(d.stateNode.containerInfo);break;case 22:case 23:return}e:if(it){switch(d.tag){case 1:case 5:case 6:break e;case 3:case 4:d=d.stateNode,Nr(d.containerInfo,d.pendingChildren);break e}throw Error(o(163))}}function Rg(f){var d=f.updateQueue;if(d!==null){f.updateQueue=null;var x=f.stateNode;x===null&&(x=f.stateNode=new kB),d.forEach(function(w){var k=HB.bind(null,f,w);x.has(w)||(x.add(w),w.then(k,k))})}}function OB(f,d){for(Ze=d;Ze!==null;){d=Ze;var x=d.deletions;if(x!==null)for(var w=0;w";case kg:return":has("+(Xx(f)||"")+")";case Ig:return'[role="'+f.value+'"]';case Lg:return'"'+f.value+'"';case Og:return'[data-testname="'+f.value+'"]';default:throw Error(o(365))}}function CC(f,d){var x=[];f=[f,0];for(var w=0;wk&&(k=J),w&=~F}if(w=k,w=qr()-w,w=(120>w?120:480>w?480:1080>w?1080:1920>w?1920:3e3>w?3e3:4320>w?4320:1960*PB(w/1960))-w,10f?16:f,ol===null)var w=!1;else{if(f=ol,ol=null,Bg=0,Vt&6)throw Error(o(331));var k=Vt;for(Vt|=4,Ze=f.current;Ze!==null;){var F=Ze,J=F.child;if(Ze.flags&16){var oe=F.deletions;if(oe!==null){for(var Re=0;Reqr()-Jx?su(f,0):Zx|=x),Zi(f,d)}function UC(f,d){d===0&&(f.mode&1?(d=tg,tg<<=1,!(tg&130023424)&&(tg=4194304)):d=1);var x=Ri();f=Hg(f,d),f!==null&&(wd(f,d,x),Zi(f,x))}function VB(f){var d=f.memoizedState,x=0;d!==null&&(x=d.retryLane),UC(f,x)}function HB(f,d){var x=0;switch(f.tag){case 13:var w=f.stateNode,k=f.memoizedState;k!==null&&(x=k.retryLane);break;case 19:w=f.stateNode;break;default:throw Error(o(314))}w!==null&&w.delete(d),UC(f,x)}var FC;FC=function(f,d,x){if(f!==null)if(f.memoizedProps!==d.pendingProps||jn.current)Es=!0;else{if(!(f.lanes&x)&&!(d.flags&128))return Es=!1,RB(f,d,x);Es=!!(f.flags&131072)}else Es=!1,qn&&d.flags&1048576&&bM(d,fg,d.index);switch(d.lanes=0,d.tag){case 2:var w=d.type;f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),f=d.pendingProps;var k=jr(d,Qe.current);Th(d,x),k=Nx(null,d,w,f,k,x);var F=kx();return d.flags|=1,typeof k=="object"&&k!==null&&typeof k.render=="function"&&k.$$typeof===void 0?(d.tag=1,d.memoizedState=null,d.updateQueue=null,lr(w)?(F=!0,Mi(d)):F=!1,d.memoizedState=k.state!==null&&k.state!==void 0?k.state:null,_x(d),k.updater=ug,d.stateNode=k,k._reactInternals=d,yx(d,w,f,x),d=Fx(null,d,w,!0,F,x)):(d.tag=0,qn&&F&&xx(d),Ci(null,d,k,x),d=d.child),d;case 16:w=d.elementType;e:{switch(f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),f=d.pendingProps,k=w._init,w=k(w._payload),d.type=w,k=d.tag=WB(w),f=go(w,f),k){case 0:d=Ux(null,d,w,f,x);break e;case 1:d=cC(null,d,w,f,x);break e;case 11:d=rC(null,d,w,f,x);break e;case 14:d=iC(null,d,w,go(w.type,f),x);break e}throw Error(o(306,w,""))}return d;case 0:return w=d.type,k=d.pendingProps,k=d.elementType===w?k:go(w,k),Ux(f,d,w,k,x);case 1:return w=d.type,k=d.pendingProps,k=d.elementType===w?k:go(w,k),cC(f,d,w,k,x);case 3:e:{if(lC(d),f===null)throw Error(o(387));w=d.pendingProps,F=d.memoizedState,k=F.element,_M(f,d),lg(d,w,null,x);var J=d.memoizedState;if(w=J.element,De&&F.isDehydrated)if(F={element:w,isDehydrated:!1,cache:J.cache,transitions:J.transitions},d.updateQueue.baseState=F,d.memoizedState=F,d.flags&256){k=Error(o(423)),d=uC(f,d,w,x,k);break e}else if(w!==k){k=Error(o(424)),d=uC(f,d,w,x,k);break e}else for(De&&(Ss=Km(d.stateNode.containerInfo),xs=d,qn=!0,_o=null,bd=!1),x=NM(d,null,w,x),d.child=x;x;)x.flags=x.flags&-3|4096,x=x.sibling;else{if(Ch(),w===k){d=Ja(f,d,x);break e}Ci(f,d,w,x)}d=d.child}return d;case 5:return kM(d),f===null&&wx(d),w=d.type,k=d.pendingProps,F=f!==null?f.memoizedProps:null,J=k.children,re(w,k)?J=null:F!==null&&re(w,F)&&(d.flags|=32),aC(f,d),Ci(f,d,J,x),d.child;case 6:return f===null&&wx(d),null;case 13:return hC(f,d,x);case 4:return Tx(d,d.stateNode.containerInfo),w=d.pendingProps,f===null?d.child=Rh(d,null,w,x):Ci(f,d,w,x),d.child;case 11:return w=d.type,k=d.pendingProps,k=d.elementType===w?k:go(w,k),rC(f,d,w,k,x);case 7:return Ci(f,d,d.pendingProps,x),d.child;case 8:return Ci(f,d,d.pendingProps.children,x),d.child;case 12:return Ci(f,d,d.pendingProps.children,x),d.child;case 10:e:{if(w=d.type._context,k=d.pendingProps,F=d.memoizedProps,J=k.value,gM(d,w,J),F!==null)if(Jo(F.value,J)){if(F.children===k.children&&!jn.current){d=Ja(f,d,x);break e}}else for(F=d.child,F!==null&&(F.return=d);F!==null;){var oe=F.dependencies;if(oe!==null){J=F.child;for(var Re=oe.firstContext;Re!==null;){if(Re.context===w){if(F.tag===1){Re=Xa(-1,x&-x),Re.tag=2;var Fe=F.updateQueue;if(Fe!==null){Fe=Fe.shared;var at=Fe.pending;at===null?Re.next=Re:(Re.next=at.next,at.next=Re),Fe.pending=Re}}F.lanes|=x,Re=F.alternate,Re!==null&&(Re.lanes|=x),gx(F.return,x,d),oe.lanes|=x;break}Re=Re.next}}else if(F.tag===10)J=F.type===d.type?null:F.child;else if(F.tag===18){if(J=F.return,J===null)throw Error(o(341));J.lanes|=x,oe=J.alternate,oe!==null&&(oe.lanes|=x),gx(J,x,d),J=F.sibling}else J=F.child;if(J!==null)J.return=F;else for(J=F;J!==null;){if(J===d){J=null;break}if(F=J.sibling,F!==null){F.return=J.return,J=F;break}J=J.return}F=J}Ci(f,d,k.children,x),d=d.child}return d;case 9:return k=d.type,w=d.pendingProps.children,Th(d,x),k=Bs(k),w=w(k),d.flags|=1,Ci(f,d,w,x),d.child;case 14:return w=d.type,k=go(w,d.pendingProps),k=go(w.type,k),iC(f,d,w,k,x);case 15:return sC(f,d,d.type,d.pendingProps,x);case 17:return w=d.type,k=d.pendingProps,k=d.elementType===w?k:go(w,k),f!==null&&(f.alternate=null,d.alternate=null,d.flags|=2),d.tag=1,lr(w)?(f=!0,Mi(d)):f=!1,Th(d,x),EM(d,w,k),yx(d,w,k,x),Fx(null,d,w,!0,f,x);case 19:return mC(f,d,x);case 22:return oC(f,d,x)}throw Error(o(156,d.tag))};function BC(f,d){return lx(f,d)}function GB(f,d,x,w){this.tag=f,this.key=x,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=d,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=w,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function js(f,d,x,w){return new GB(f,d,x,w)}function o1(f){return f=f.prototype,!(!f||!f.isReactComponent)}function WB(f){if(typeof f=="function")return o1(f)?1:0;if(f!=null){if(f=f.$$typeof,f===v)return 11;if(f===S)return 14}return 2}function ll(f,d){var x=f.alternate;return x===null?(x=js(f.tag,d,f.key,f.mode),x.elementType=f.elementType,x.type=f.type,x.stateNode=f.stateNode,x.alternate=f,f.alternate=x):(x.pendingProps=d,x.type=f.type,x.flags=0,x.subtreeFlags=0,x.deletions=null),x.flags=f.flags&14680064,x.childLanes=f.childLanes,x.lanes=f.lanes,x.child=f.child,x.memoizedProps=f.memoizedProps,x.memoizedState=f.memoizedState,x.updateQueue=f.updateQueue,d=f.dependencies,x.dependencies=d===null?null:{lanes:d.lanes,firstContext:d.firstContext},x.sibling=f.sibling,x.index=f.index,x.ref=f.ref,x}function Wg(f,d,x,w,k,F){var J=2;if(w=f,typeof f=="function")o1(f)&&(J=1);else if(typeof f=="string")J=5;else e:switch(f){case u:return cu(x.children,k,F,d);case h:J=8,k|=8;break;case p:return f=js(12,x,d,k|2),f.elementType=p,f.lanes=F,f;case y:return f=js(13,x,d,k),f.elementType=y,f.lanes=F,f;case _:return f=js(19,x,d,k),f.elementType=_,f.lanes=F,f;case b:return jg(x,k,F,d);default:if(typeof f=="object"&&f!==null)switch(f.$$typeof){case m:J=10;break e;case g:J=9;break e;case v:J=11;break e;case S:J=14;break e;case E:J=16,w=null;break e}throw Error(o(130,f==null?f:typeof f,""))}return d=js(J,x,d,k),d.elementType=f,d.type=w,d.lanes=F,d}function cu(f,d,x,w){return f=js(7,f,w,d),f.lanes=x,f}function jg(f,d,x,w){return f=js(22,f,w,d),f.elementType=b,f.lanes=x,f.stateNode={},f}function a1(f,d,x){return f=js(6,f,null,d),f.lanes=x,f}function c1(f,d,x){return d=js(4,f.children!==null?f.children:[],f.key,d),d.lanes=x,d.stateNode={containerInfo:f.containerInfo,pendingChildren:null,implementation:f.implementation},d}function jB(f,d,x,w,k){this.tag=d,this.containerInfo=f,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Le,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=ax(0),this.expirationTimes=ax(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ax(0),this.identifierPrefix=w,this.onRecoverableError=k,De&&(this.mutableSourceEagerHydrationData=null)}function zC(f,d,x,w,k,F,J,oe,Re){return f=new jB(f,d,x,oe,Re),d===1?(d=1,F===!0&&(d|=8)):d=0,F=js(3,null,null,d),f.current=F,F.stateNode=f,F.memoizedState={element:w,isDehydrated:x,cache:null,transitions:null},_x(F),f}function VC(f){if(!f)return zt;f=f._reactInternals;e:{if(C(f)!==f||f.tag!==1)throw Error(o(170));var d=f;do{switch(d.tag){case 3:d=d.stateNode.context;break e;case 1:if(lr(d.type)){d=d.stateNode.__reactInternalMemoizedMergedChildContext;break e}}d=d.return}while(d!==null);throw Error(o(171))}if(f.tag===1){var x=f.type;if(lr(x))return bn(f,x,d)}return d}function HC(f){var d=f._reactInternals;if(d===void 0)throw typeof f.render=="function"?Error(o(188)):(f=Object.keys(f).join(","),Error(o(268,f)));return f=L(d),f===null?null:f.stateNode}function GC(f,d){if(f=f.memoizedState,f!==null&&f.dehydrated!==null){var x=f.retryLane;f.retryLane=x!==0&&x=Fe&&F>=It&&k<=at&&J<=xt){f.splice(d,1);break}else if(w!==Fe||x.width!==Re.width||xtJ){if(!(F!==It||x.height!==Re.height||atk)){Fe>w&&(Re.width+=Fe-w,Re.x=w),atF&&(Re.height+=It-F,Re.y=F),xtx&&(x=J)),J ")+` - -No matching component was found for: - `)+f.join(" > ")}return null},n.getPublicRootInstance=function(f){if(f=f.current,!f.child)return null;switch(f.child.tag){case 5:return V(f.child.stateNode);default:return f.child.stateNode}},n.injectIntoDevTools=function(f){if(f={bundleType:f.bundleType,version:f.version,rendererPackageName:f.rendererPackageName,rendererConfig:f.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:a.ReactCurrentDispatcher,findHostInstanceByFiber:$B,findFiberByHostInstance:f.findFiberByHostInstance||qB,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.0.0-fc46dba67-20220329"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")f=!1;else{var d=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(d.isDisabled||!d.supportsFiber)f=!0;else{try{rg=d.inject(f),Zo=d}catch{}f=!!d.checkDCE}}return f},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(f,d,x,w){if(!ae)throw Error(o(363));f=Kx(f,d);var k=ze(f,x,w).disconnect;return{disconnect:function(){k()}}},n.registerMutableSourceForHydration=function(f,d){var x=d._getVersion;x=x(d._source),f.mutableSourceEagerHydrationData==null?f.mutableSourceEagerHydrationData=[d,x]:f.mutableSourceEagerHydrationData.push(d,x)},n.runWithPriority=function(f,d){var x=dn;try{return dn=f,d()}finally{dn=x}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(f,d,x,w){var k=d.current,F=Ri(),J=al(k);return x=VC(x),d.context===null?d.context=x:d.pendingContext=x,d=Xa(F,J),d.payload={element:f},w=w===void 0?null:w,w!==null&&(d.callback=w),il(k,d),f=Ws(k,J,F),f!==null&&cg(f,k,J),J},n};zO.exports=JG;var QG=zO.exports;const eW=Bc(QG),Mb={},Cb=t=>void Object.assign(Mb,t);function tW(t,e){function n(u,{args:h=[],attach:p,...m},g){let v=`${u[0].toUpperCase()}${u.slice(1)}`,y;if(u==="primitive"){if(m.object===void 0)throw new Error("R3F: Primitives without 'object' are invalid!");const _=m.object;y=of(_,{type:u,root:g,attach:p,primitive:!0})}else{const _=Mb[v];if(!_)throw new Error(`R3F: ${v} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`);if(!Array.isArray(h))throw new Error("R3F: The args prop must be an array!");y=of(new _(...h),{type:u,root:g,attach:p,memoizedProps:{args:h}})}return y.__r3f.attach===void 0&&(y instanceof Bo?y.__r3f.attach="geometry":y instanceof Vc&&(y.__r3f.attach="material")),v!=="inject"&&V1(y,m),y}function r(u,h){let p=!1;if(h){var m,g;(m=h.__r3f)!=null&&m.attach?z1(u,h,h.__r3f.attach):h.isObject3D&&u.isObject3D&&(u.add(h),p=!0),p||(g=u.__r3f)==null||g.objects.push(h),h.__r3f||of(h,{}),h.__r3f.parent=u,LE(h),af(h)}}function i(u,h,p){let m=!1;if(h){var g,v;if((g=h.__r3f)!=null&&g.attach)z1(u,h,h.__r3f.attach);else if(h.isObject3D&&u.isObject3D){h.parent=u,h.dispatchEvent({type:"added"}),u.dispatchEvent({type:"childadded",child:h});const y=u.children.filter(S=>S!==h),_=y.indexOf(p);u.children=[...y.slice(0,_),h,...y.slice(_)],m=!0}m||(v=u.__r3f)==null||v.objects.push(h),h.__r3f||of(h,{}),h.__r3f.parent=u,LE(h),af(h)}}function s(u,h,p=!1){u&&[...u].forEach(m=>o(h,m,p))}function o(u,h,p){if(h){var m,g,v;if(h.__r3f&&(h.__r3f.parent=null),(m=u.__r3f)!=null&&m.objects&&(u.__r3f.objects=u.__r3f.objects.filter(b=>b!==h)),(g=h.__r3f)!=null&&g.attach)i2(u,h,h.__r3f.attach);else if(h.isObject3D&&u.isObject3D){var y;u.remove(h),(y=h.__r3f)!=null&&y.root&&uW(s_(h),h)}const S=(v=h.__r3f)==null?void 0:v.primitive,E=!S&&(p===void 0?h.dispose!==null:p);if(!S){var _;s((_=h.__r3f)==null?void 0:_.objects,h,E),s(h.children,h,E)}if(delete h.__r3f,E&&h.dispose&&h.type!=="Scene"){const b=()=>{try{h.dispose()}catch{}};typeof IS_REACT_ACT_ENVIRONMENT>"u"?IE.unstable_scheduleCallback(IE.unstable_IdlePriority,b):b()}af(u)}}function a(u,h,p,m){var g;const v=(g=u.__r3f)==null?void 0:g.parent;if(!v)return;const y=n(h,p,u.__r3f.root);if(u.children){for(const _ of u.children)_.__r3f&&r(y,_);u.children=u.children.filter(_=>!_.__r3f)}u.__r3f.objects.forEach(_=>r(y,_)),u.__r3f.objects=[],u.__r3f.autoRemovedBeforeAppend||o(v,u),y.parent&&(y.__r3f.autoRemovedBeforeAppend=!0),r(v,y),y.raycast&&y.__r3f.eventCount&&s_(y).getState().internal.interaction.push(y),[m,m.alternate].forEach(_=>{_!==null&&(_.stateNode=y,_.ref&&(typeof _.ref=="function"?_.ref(y):_.ref.current=y))})}const c=()=>{};return{reconciler:eW({createInstance:n,removeChild:o,appendChild:r,appendInitialChild:r,insertBefore:i,supportsMutation:!0,isPrimaryRenderer:!1,supportsPersistence:!1,supportsHydration:!1,noTimeout:-1,appendChildToContainer:(u,h)=>{if(!h)return;const p=u.getState().scene;p.__r3f&&(p.__r3f.root=u,r(p,h))},removeChildFromContainer:(u,h)=>{h&&o(u.getState().scene,h)},insertInContainerBefore:(u,h,p)=>{if(!h||!p)return;const m=u.getState().scene;m.__r3f&&i(m,h,p)},getRootHostContext:()=>null,getChildHostContext:u=>u,finalizeInitialChildren(u){var h;return!!((h=u==null?void 0:u.__r3f)!=null?h:{}).handlers},prepareUpdate(u,h,p,m){var g;if(((g=u==null?void 0:u.__r3f)!=null?g:{}).primitive&&m.object&&m.object!==u)return[!0];{const{args:y=[],children:_,...S}=m,{args:E=[],children:b,...N}=p;if(!Array.isArray(y))throw new Error("R3F: the args prop must be an array!");if(y.some((M,O)=>M!==E[O]))return[!0];const R=qO(u,S,N,!0);return R.changes.length?[!1,R]:null}},commitUpdate(u,[h,p],m,g,v,y){h?a(u,m,v,y):V1(u,p)},commitMount(u,h,p,m){var g;const v=(g=u.__r3f)!=null?g:{};u.raycast&&v.handlers&&v.eventCount&&s_(u).getState().internal.interaction.push(u)},getPublicInstance:u=>u,prepareForCommit:()=>null,preparePortalMount:u=>of(u.getState().scene),resetAfterCommit:()=>{},shouldSetTextContent:()=>!1,clearContainer:()=>!1,hideInstance(u){var h;const{attach:p,parent:m}=(h=u.__r3f)!=null?h:{};p&&m&&i2(m,u,p),u.isObject3D&&(u.visible=!1),af(u)},unhideInstance(u,h){var p;const{attach:m,parent:g}=(p=u.__r3f)!=null?p:{};m&&g&&z1(g,u,m),(u.isObject3D&&h.visible==null||h.visible)&&(u.visible=!0),af(u)},createTextInstance:c,hideTextInstance:c,unhideTextInstance:c,getCurrentEventPriority:()=>e?e():df.DefaultEventPriority,beforeActiveInstanceBlur:()=>{},afterActiveInstanceBlur:()=>{},detachDeletedInstance:()=>{},now:typeof performance<"u"&&On.fun(performance.now)?performance.now:On.fun(Date.now)?Date.now:()=>0,scheduleTimeout:On.fun(setTimeout)?setTimeout:void 0,cancelTimeout:On.fun(clearTimeout)?clearTimeout:void 0}),applyProps:V1}}var e2,t2;const B1=t=>"colorSpace"in t||"outputColorSpace"in t,GO=()=>{var t;return(t=Mb.ColorManagement)!=null?t:null},WO=t=>t&&t.isOrthographicCamera,Bv=typeof window<"u"&&((e2=window.document)!=null&&e2.createElement||((t2=window.navigator)==null?void 0:t2.product)==="ReactNative")?Ne.useLayoutEffect:Ne.useEffect;function nW(t){const e=Ne.useRef(t);return Bv(()=>void(e.current=t),[t]),e}class rW extends Ne.Component{constructor(...e){super(...e),this.state={error:!1}}componentDidCatch(e){this.props.set(e)}render(){return this.state.error?null:this.props.children}}rW.getDerivedStateFromError=()=>({error:!0});const jO="__default",n2=new Map,iW=t=>t&&!!t.memoized&&!!t.changes;function $O(t){var e;const n=typeof window<"u"?(e=window.devicePixelRatio)!=null?e:2:1;return Array.isArray(t)?Math.min(Math.max(t[0],n),t[1]):t}const jd=t=>{var e;return(e=t.__r3f)==null?void 0:e.root.getState()};function s_(t){let e=t.__r3f.root;for(;e.getState().previousRoot;)e=e.getState().previousRoot;return e}const On={obj:t=>t===Object(t)&&!On.arr(t)&&typeof t!="function",fun:t=>typeof t=="function",str:t=>typeof t=="string",num:t=>typeof t=="number",boo:t=>typeof t=="boolean",und:t=>t===void 0,arr:t=>Array.isArray(t),equ(t,e,{arrays:n="shallow",objects:r="reference",strict:i=!0}={}){if(typeof t!=typeof e||!!t!=!!e)return!1;if(On.str(t)||On.num(t)||On.boo(t))return t===e;const s=On.obj(t);if(s&&r==="reference")return t===e;const o=On.arr(t);if(o&&n==="reference")return t===e;if((o||s)&&t===e)return!0;let a;for(a in t)if(!(a in e))return!1;if(s&&n==="shallow"&&r==="shallow"){for(a in i?e:t)if(!On.equ(t[a],e[a],{strict:i,objects:"reference"}))return!1}else for(a in i?e:t)if(t[a]!==e[a])return!1;if(On.und(a)){if(o&&t.length===0&&e.length===0||s&&Object.keys(t).length===0&&Object.keys(e).length===0)return!0;if(t!==e)return!1}return!0}};function sW(t){const e={nodes:{},materials:{}};return t&&t.traverse(n=>{n.name&&(e.nodes[n.name]=n),n.material&&!e.materials[n.material.name]&&(e.materials[n.material.name]=n.material)}),e}function oW(t){t.dispose&&t.type!=="Scene"&&t.dispose();for(const e in t)e.dispose==null||e.dispose(),delete t[e]}function of(t,e){const n=t;return n.__r3f={type:"",root:null,previousAttach:null,memoizedProps:{},eventCount:0,handlers:{},objects:[],parent:null,...e},t}function OE(t,e){let n=t;if(e.includes("-")){const r=e.split("-"),i=r.pop();return n=r.reduce((s,o)=>s[o],t),{target:n,key:i}}else return{target:n,key:e}}const r2=/-\d+$/;function z1(t,e,n){if(On.str(n)){if(r2.test(n)){const s=n.replace(r2,""),{target:o,key:a}=OE(t,s);Array.isArray(o[a])||(o[a]=[])}const{target:r,key:i}=OE(t,n);e.__r3f.previousAttach=r[i],r[i]=e}else e.__r3f.previousAttach=n(t,e)}function i2(t,e,n){var r,i;if(On.str(n)){const{target:s,key:o}=OE(t,n),a=e.__r3f.previousAttach;a===void 0?delete s[o]:s[o]=a}else(r=e.__r3f)==null||r.previousAttach==null||r.previousAttach(t,e);(i=e.__r3f)==null||delete i.previousAttach}function qO(t,{children:e,key:n,ref:r,...i},{children:s,key:o,ref:a,...c}={},l=!1){const u=t.__r3f,h=Object.entries(i),p=[];if(l){const g=Object.keys(c);for(let v=0;v{var y;if((y=t.__r3f)!=null&&y.primitive&&g==="object"||On.equ(v,c[g]))return;if(/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(g))return p.push([g,v,!0,[]]);let _=[];g.includes("-")&&(_=g.split("-")),p.push([g,v,!1,_]);for(const S in i){const E=i[S];S.startsWith(`${g}-`)&&p.push([S,E,!1,S.split("-")])}});const m={...i};return u!=null&&u.memoizedProps&&u!=null&&u.memoizedProps.args&&(m.args=u.memoizedProps.args),u!=null&&u.memoizedProps&&u!=null&&u.memoizedProps.attach&&(m.attach=u.memoizedProps.attach),{memoized:m,changes:p}}const aW=typeof process<"u"&&!1;function V1(t,e){var n;const r=t.__r3f,i=r==null?void 0:r.root,s=i==null||i.getState==null?void 0:i.getState(),{memoized:o,changes:a}=iW(e)?e:qO(t,e),c=r==null?void 0:r.eventCount;t.__r3f&&(t.__r3f.memoizedProps=o);for(let u=0;u_[S],t),!(y&&y.set))){const[_,...S]=g.reverse();v=S.reverse().reduce((E,b)=>E[b],t),h=_}if(p===jO+"remove")if(v.constructor){let _=n2.get(v.constructor);_||(_=new v.constructor,n2.set(v.constructor,_)),p=_[h]}else p=0;if(m&&r)p?r.handlers[h]=p:delete r.handlers[h],r.eventCount=Object.keys(r.handlers).length;else if(y&&y.set&&(y.copy||y instanceof bf)){if(Array.isArray(p))y.fromArray?y.fromArray(p):y.set(...p);else if(y.copy&&p&&p.constructor&&(aW?y.constructor.name===p.constructor.name:y.constructor===p.constructor))y.copy(p);else if(p!==void 0){const _=y instanceof ln;!_&&y.setScalar?y.setScalar(p):y instanceof bf&&p instanceof bf?y.mask=p.mask:y.set(p),!GO()&&s&&!s.linear&&_&&y.convertSRGBToLinear()}}else if(v[h]=p,v[h]instanceof or&&v[h].format===to&&v[h].type===bi&&s){const _=v[h];B1(_)&&B1(s.gl)?_.colorSpace=s.gl.outputColorSpace:_.encoding=s.gl.outputEncoding}af(t)}if(r&&r.parent&&t.raycast&&c!==r.eventCount){const u=s_(t).getState().internal,h=u.interaction.indexOf(t);h>-1&&u.interaction.splice(h,1),r.eventCount&&u.interaction.push(t)}return!(a.length===1&&a[0][0]==="onUpdate")&&a.length&&(n=t.__r3f)!=null&&n.parent&&LE(t),t}function af(t){var e,n;const r=(e=t.__r3f)==null||(n=e.root)==null||n.getState==null?void 0:n.getState();r&&r.internal.frames===0&&r.invalidate()}function LE(t){t.onUpdate==null||t.onUpdate(t)}function cW(t,e){t.manual||(WO(t)?(t.left=e.width/-2,t.right=e.width/2,t.top=e.height/2,t.bottom=e.height/-2):t.aspect=e.width/e.height,t.updateProjectionMatrix(),t.updateMatrixWorld())}function g0(t){return(t.eventObject||t.object).uuid+"/"+t.index+t.instanceId}function lW(){var t;const e=typeof self<"u"&&self||typeof window<"u"&&window;if(!e)return df.DefaultEventPriority;switch((t=e.event)==null?void 0:t.type){case"click":case"contextmenu":case"dblclick":case"pointercancel":case"pointerdown":case"pointerup":return df.DiscreteEventPriority;case"pointermove":case"pointerout":case"pointerover":case"pointerenter":case"pointerleave":case"wheel":return df.ContinuousEventPriority;default:return df.DefaultEventPriority}}function XO(t,e,n,r){const i=n.get(e);i&&(n.delete(e),n.size===0&&(t.delete(r),i.target.releasePointerCapture(r)))}function uW(t,e){const{internal:n}=t.getState();n.interaction=n.interaction.filter(r=>r!==e),n.initialHits=n.initialHits.filter(r=>r!==e),n.hovered.forEach((r,i)=>{(r.eventObject===e||r.object===e)&&n.hovered.delete(i)}),n.capturedMap.forEach((r,i)=>{XO(n.capturedMap,e,r,i)})}function hW(t){function e(c){const{internal:l}=t.getState(),u=c.offsetX-l.initialClick[0],h=c.offsetY-l.initialClick[1];return Math.round(Math.sqrt(u*u+h*h))}function n(c){return c.filter(l=>["Move","Over","Enter","Out","Leave"].some(u=>{var h;return(h=l.__r3f)==null?void 0:h.handlers["onPointer"+u]}))}function r(c,l){const u=t.getState(),h=new Set,p=[],m=l?l(u.internal.interaction):u.internal.interaction;for(let _=0;_{const E=jd(_.object),b=jd(S.object);return!E||!b?_.distance-S.distance:b.events.priority-E.events.priority||_.distance-S.distance}).filter(_=>{const S=g0(_);return h.has(S)?!1:(h.add(S),!0)});u.events.filter&&(v=u.events.filter(v,u));for(const _ of v){let S=_.object;for(;S;){var y;(y=S.__r3f)!=null&&y.eventCount&&p.push({..._,eventObject:S}),S=S.parent}}if("pointerId"in c&&u.internal.capturedMap.has(c.pointerId))for(let _ of u.internal.capturedMap.get(c.pointerId).values())h.has(g0(_.intersection))||p.push(_.intersection);return p}function i(c,l,u,h){const p=t.getState();if(c.length){const m={stopped:!1};for(const g of c){const v=jd(g.object)||p,{raycaster:y,pointer:_,camera:S,internal:E}=v,b=new xe(_.x,_.y,0).unproject(S),N=I=>{var U,L;return(U=(L=E.capturedMap.get(I))==null?void 0:L.has(g.eventObject))!=null?U:!1},R=I=>{const U={intersection:g,target:l.target};E.capturedMap.has(I)?E.capturedMap.get(I).set(g.eventObject,U):E.capturedMap.set(I,new Map([[g.eventObject,U]])),l.target.setPointerCapture(I)},M=I=>{const U=E.capturedMap.get(I);U&&XO(E.capturedMap,g.eventObject,U,I)};let O={};for(let I in l){let U=l[I];typeof U!="function"&&(O[I]=U)}let C={...g,...O,pointer:_,intersections:c,stopped:m.stopped,delta:u,unprojectedPoint:b,ray:y.ray,camera:S,stopPropagation(){const I="pointerId"in l&&E.capturedMap.get(l.pointerId);if((!I||I.has(g.eventObject))&&(C.stopped=m.stopped=!0,E.hovered.size&&Array.from(E.hovered.values()).find(U=>U.eventObject===g.eventObject))){const U=c.slice(0,c.indexOf(g));s([...U,g])}},target:{hasPointerCapture:N,setPointerCapture:R,releasePointerCapture:M},currentTarget:{hasPointerCapture:N,setPointerCapture:R,releasePointerCapture:M},nativeEvent:l};if(h(C),m.stopped===!0)break}}return c}function s(c){const{internal:l}=t.getState();for(const u of l.hovered.values())if(!c.length||!c.find(h=>h.object===u.object&&h.index===u.index&&h.instanceId===u.instanceId)){const p=u.eventObject.__r3f,m=p==null?void 0:p.handlers;if(l.hovered.delete(g0(u)),p!=null&&p.eventCount){const g={...u,intersections:c};m.onPointerOut==null||m.onPointerOut(g),m.onPointerLeave==null||m.onPointerLeave(g)}}}function o(c,l){for(let u=0;us([]);case"onLostPointerCapture":return l=>{const{internal:u}=t.getState();"pointerId"in l&&u.capturedMap.has(l.pointerId)&&requestAnimationFrame(()=>{u.capturedMap.has(l.pointerId)&&(u.capturedMap.delete(l.pointerId),s([]))})}}return function(u){const{onPointerMissed:h,internal:p}=t.getState();p.lastEvent.current=u;const m=c==="onPointerMove",g=c==="onClick"||c==="onContextMenu"||c==="onDoubleClick",y=r(u,m?n:void 0),_=g?e(u):0;c==="onPointerDown"&&(p.initialClick=[u.offsetX,u.offsetY],p.initialHits=y.map(E=>E.eventObject)),g&&!y.length&&_<=2&&(o(u,p.interaction),h&&h(u)),m&&s(y);function S(E){const b=E.eventObject,N=b.__r3f,R=N==null?void 0:N.handlers;if(N!=null&&N.eventCount)if(m){if(R.onPointerOver||R.onPointerEnter||R.onPointerOut||R.onPointerLeave){const M=g0(E),O=p.hovered.get(M);O?O.stopped&&E.stopPropagation():(p.hovered.set(M,E),R.onPointerOver==null||R.onPointerOver(E),R.onPointerEnter==null||R.onPointerEnter(E))}R.onPointerMove==null||R.onPointerMove(E)}else{const M=R[c];M?(!g||p.initialHits.includes(b))&&(o(u,p.interaction.filter(O=>!p.initialHits.includes(O))),M(E)):g&&p.initialHits.includes(b)&&o(u,p.interaction.filter(O=>!p.initialHits.includes(O)))}}i(y,u,_,S)}}return{handlePointer:a}}const KO=t=>!!(t!=null&&t.render),YO=Ne.createContext(null),fW=(t,e)=>{const n=qG((a,c)=>{const l=new xe,u=new xe,h=new xe;function p(_=c().camera,S=u,E=c().size){const{width:b,height:N,top:R,left:M}=E,O=b/N;S instanceof xe?h.copy(S):h.set(...S);const C=_.getWorldPosition(l).distanceTo(h);if(WO(_))return{width:b/_.zoom,height:N/_.zoom,top:R,left:M,factor:1,distance:C,aspect:O};{const I=_.fov*Math.PI/180,U=2*Math.tan(I/2)*C,L=U*(b/N);return{width:L,height:U,top:R,left:M,factor:b/L,distance:C,aspect:O}}}let m;const g=_=>a(S=>({performance:{...S.performance,current:_}})),v=new St;return{set:a,get:c,gl:null,camera:null,raycaster:null,events:{priority:1,enabled:!0,connected:!1},xr:null,scene:null,invalidate:(_=1)=>t(c(),_),advance:(_,S)=>e(_,S,c()),legacy:!1,linear:!1,flat:!1,controls:null,clock:new HG,pointer:v,mouse:v,frameloop:"always",onPointerMissed:void 0,performance:{current:1,min:.5,max:1,debounce:200,regress:()=>{const _=c();m&&clearTimeout(m),_.performance.current!==_.performance.min&&g(_.performance.min),m=setTimeout(()=>g(c().performance.max),_.performance.debounce)}},size:{width:0,height:0,top:0,left:0,updateStyle:!1},viewport:{initialDpr:0,dpr:0,width:0,height:0,top:0,left:0,aspect:0,distance:0,factor:0,getCurrentViewport:p},setEvents:_=>a(S=>({...S,events:{...S.events,..._}})),setSize:(_,S,E,b,N)=>{const R=c().camera,M={width:_,height:S,top:b||0,left:N||0,updateStyle:E};a(O=>({size:M,viewport:{...O.viewport,...p(R,u,M)}}))},setDpr:_=>a(S=>{const E=$O(_);return{viewport:{...S.viewport,dpr:E,initialDpr:S.viewport.initialDpr||E}}}),setFrameloop:(_="always")=>{const S=c().clock;S.stop(),S.elapsedTime=0,_!=="never"&&(S.start(),S.elapsedTime=0),a(()=>({frameloop:_}))},previousRoot:void 0,internal:{active:!1,priority:0,frames:0,lastEvent:Ne.createRef(),interaction:[],hovered:new Map,subscribers:[],initialClick:[0,0],initialHits:[],capturedMap:new Map,subscribe:(_,S,E)=>{const b=c().internal;return b.priority=b.priority+(S>0?1:0),b.subscribers.push({ref:_,priority:S,store:E}),b.subscribers=b.subscribers.sort((N,R)=>N.priority-R.priority),()=>{const N=c().internal;N!=null&&N.subscribers&&(N.priority=N.priority-(S>0?1:0),N.subscribers=N.subscribers.filter(R=>R.ref!==_))}}}}}),r=n.getState();let i=r.size,s=r.viewport.dpr,o=r.camera;return n.subscribe(()=>{const{camera:a,size:c,viewport:l,gl:u,set:h}=n.getState();if(c.width!==i.width||c.height!==i.height||l.dpr!==s){var p;i=c,s=l.dpr,cW(a,c),u.setPixelRatio(l.dpr);const m=(p=c.updateStyle)!=null?p:typeof HTMLCanvasElement<"u"&&u.domElement instanceof HTMLCanvasElement;u.setSize(c.width,c.height,m)}a!==o&&(o=a,h(m=>({viewport:{...m.viewport,...m.viewport.getCurrentViewport(a)}})))}),n.subscribe(a=>t(a)),n};function ZO(t,e){const n={callback:t};return e.add(n),()=>void e.delete(n)}let _0,JO=new Set,QO=new Set,dW=new Set;const pW=t=>ZO(t,JO),mW=t=>ZO(t,QO);function H1(t,e){if(t.size)for(const{callback:n}of t.values())n(e)}function $d(t,e){switch(t){case"before":return H1(JO,e);case"after":return H1(QO,e);case"tail":return H1(dW,e)}}let G1,W1;function j1(t,e,n){let r=e.clock.getDelta();for(e.frameloop==="never"&&typeof t=="number"&&(r=t-e.clock.elapsedTime,e.clock.oldTime=e.clock.elapsedTime,e.clock.elapsedTime=t),G1=e.internal.subscribers,_0=0;_00)&&!((u=s.gl.xr)!=null&&u.isPresenting)&&(r+=j1(l,s))}if(n=!1,$d("after",l),r===0)return $d("tail",l),e=!1,cancelAnimationFrame(i)}function a(l,u=1){var h;if(!l)return t.forEach(p=>a(p.store.getState(),u));(h=l.gl.xr)!=null&&h.isPresenting||!l.internal.active||l.frameloop==="never"||(u>1?l.internal.frames=Math.min(60,l.internal.frames+u):n?l.internal.frames=2:l.internal.frames=1,e||(e=!0,requestAnimationFrame(o)))}function c(l,u=!0,h,p){if(u&&$d("before",l),h)j1(l,h,p);else for(const m of t.values())j1(l,m.store.getState());u&&$d("after",l)}return{loop:o,invalidate:a,advance:c}}function _W(t){const e=Ne.useRef(null);return Bv(()=>void(e.current=t.current.__r3f),[t]),e}function eL(){const t=Ne.useContext(YO);if(!t)throw new Error("R3F: Hooks can only be used within the Canvas component!");return t}function va(t=n=>n,e){return eL()(t,e)}function zv(t,e=0){const n=eL(),r=n.getState().internal.subscribe,i=nW(t);return Bv(()=>r(i,e,n),[e,r,n]),null}const s2=new WeakMap;function tL(t,e){return function(n,...r){let i=s2.get(n);return i||(i=new n,s2.set(n,i)),t&&t(i),Promise.all(r.map(s=>new Promise((o,a)=>i.load(s,c=>{c.scene&&Object.assign(c,sW(c.scene)),o(c)},e,c=>a(new Error(`Could not load ${s}: ${c==null?void 0:c.message}`))))))}}function tm(t,e,n,r){const i=Array.isArray(e)?e:[e],s=KG(tL(n,r),[t,...i],{equal:On.equ});return Array.isArray(e)?s:s[0]}tm.preload=function(t,e,n){const r=Array.isArray(e)?e:[e];return YG(tL(n),[t,...r])};tm.clear=function(t,e){const n=Array.isArray(e)?e:[e];return ZG([t,...n])};const Bf=new Map,{invalidate:o2,advance:a2}=gW(Bf),{reconciler:P_,applyProps:Yh}=tW(Bf,lW),Zh={objects:"shallow",strict:!1},vW=(t,e)=>{const n=typeof t=="function"?t(e):t;return KO(n)?n:new LG({powerPreference:"high-performance",canvas:e,antialias:!0,alpha:!0,...t})};function yW(t,e){const n=typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement;if(e){const{width:r,height:i,top:s,left:o,updateStyle:a=n}=e;return{width:r,height:i,top:s,left:o,updateStyle:a}}else if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement&&t.parentElement){const{width:r,height:i,top:s,left:o}=t.parentElement.getBoundingClientRect();return{width:r,height:i,top:s,left:o,updateStyle:n}}else if(typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return{width:t.width,height:t.height,top:0,left:0,updateStyle:n};return{width:0,height:0,top:0,left:0}}function xW(t){const e=Bf.get(t),n=e==null?void 0:e.fiber,r=e==null?void 0:e.store;e&&console.warn("R3F.createRoot should only be called once!");const i=typeof reportError=="function"?reportError:console.error,s=r||fW(o2,a2),o=n||P_.createContainer(s,df.ConcurrentRoot,null,!1,null,"",i,null);e||Bf.set(t,{fiber:o,store:s});let a,c=!1,l;return{configure(u={}){let{gl:h,size:p,scene:m,events:g,onCreated:v,shadows:y=!1,linear:_=!1,flat:S=!1,legacy:E=!1,orthographic:b=!1,frameloop:N="always",dpr:R=[1,2],performance:M,raycaster:O,camera:C,onPointerMissed:I}=u,U=s.getState(),L=U.gl;U.gl||U.set({gl:L=vW(h,t)});let P=U.raycaster;P||U.set({raycaster:P=new GG});const{params:T,...H}=O||{};if(On.equ(H,P,Zh)||Yh(P,{...H}),On.equ(T,P.params,Zh)||Yh(P,{params:{...P.params,...T}}),!U.camera||U.camera===l&&!On.equ(l,C,Zh)){l=C;const K=C instanceof Dv,j=K?C:b?new Uv(0,0,0,0,.1,1e3):new Ms(75,0,.1,1e3);K||(j.position.z=5,C&&(Yh(j,C),("aspect"in C||"left"in C||"right"in C||"bottom"in C||"top"in C)&&(j.manual=!0,j.updateProjectionMatrix())),!U.camera&&!(C!=null&&C.rotation)&&j.lookAt(0,0,0)),U.set({camera:j}),P.camera=j}if(!U.scene){let K;m instanceof L_?K=m:(K=new L_,m&&Yh(K,m)),U.set({scene:of(K)})}if(!U.xr){var V;const K=(ge,Q)=>{const re=s.getState();re.frameloop!=="never"&&a2(ge,!0,re,Q)},j=()=>{const ge=s.getState();ge.gl.xr.enabled=ge.gl.xr.isPresenting,ge.gl.xr.setAnimationLoop(ge.gl.xr.isPresenting?K:null),ge.gl.xr.isPresenting||o2(ge)},Y={connect(){const ge=s.getState().gl;ge.xr.addEventListener("sessionstart",j),ge.xr.addEventListener("sessionend",j)},disconnect(){const ge=s.getState().gl;ge.xr.removeEventListener("sessionstart",j),ge.xr.removeEventListener("sessionend",j)}};typeof((V=L.xr)==null?void 0:V.addEventListener)=="function"&&Y.connect(),U.set({xr:Y})}if(L.shadowMap){const K=L.shadowMap.enabled,j=L.shadowMap.type;if(L.shadowMap.enabled=!!y,On.boo(y))L.shadowMap.type=J0;else if(On.str(y)){var B;const Y={basic:E5,percentage:pb,soft:J0,variance:ca};L.shadowMap.type=(B=Y[y])!=null?B:J0}else On.obj(y)&&Object.assign(L.shadowMap,y);(K!==L.shadowMap.enabled||j!==L.shadowMap.type)&&(L.shadowMap.needsUpdate=!0)}const z=GO();z&&("enabled"in z?z.enabled=!E:"legacyMode"in z&&(z.legacyMode=E)),c||Yh(L,{outputEncoding:_?3e3:3001,toneMapping:S?ya:cO}),U.legacy!==E&&U.set(()=>({legacy:E})),U.linear!==_&&U.set(()=>({linear:_})),U.flat!==S&&U.set(()=>({flat:S})),h&&!On.fun(h)&&!KO(h)&&!On.equ(h,L,Zh)&&Yh(L,h),g&&!U.events.handlers&&U.set({events:g(s)});const W=yW(t,p);return On.equ(W,U.size,Zh)||U.setSize(W.width,W.height,W.updateStyle,W.top,W.left),R&&U.viewport.dpr!==$O(R)&&U.setDpr(R),U.frameloop!==N&&U.setFrameloop(N),U.onPointerMissed||U.set({onPointerMissed:I}),M&&!On.equ(M,U.performance,Zh)&&U.set(K=>({performance:{...K.performance,...M}})),a=v,c=!0,this},render(u){return c||this.configure(),P_.updateContainer(ve.jsx(SW,{store:s,children:u,onCreated:a,rootElement:t}),o,null,()=>{}),s},unmount(){EW(t)}}}function SW({store:t,children:e,onCreated:n,rootElement:r}){return Bv(()=>{const i=t.getState();i.set(s=>({internal:{...s.internal,active:!0}})),n&&n(i),t.getState().events.connected||i.events.connect==null||i.events.connect(r)},[]),ve.jsx(YO.Provider,{value:t,children:e})}function EW(t,e){const n=Bf.get(t),r=n==null?void 0:n.fiber;if(r){const i=n==null?void 0:n.store.getState();i&&(i.internal.active=!1),P_.updateContainer(null,r,null,()=>{i&&setTimeout(()=>{try{var s,o,a,c;i.events.disconnect==null||i.events.disconnect(),(s=i.gl)==null||(o=s.renderLists)==null||o.dispose==null||o.dispose(),(a=i.gl)==null||a.forceContextLoss==null||a.forceContextLoss(),(c=i.gl)!=null&&c.xr&&i.xr.disconnect(),oW(i),Bf.delete(t)}catch{}},500)})}}P_.injectIntoDevTools({bundleType:0,rendererPackageName:"@react-three/fiber",version:Ne.version});const $1={onClick:["click",!1],onContextMenu:["contextmenu",!1],onDoubleClick:["dblclick",!1],onWheel:["wheel",!0],onPointerDown:["pointerdown",!0],onPointerUp:["pointerup",!0],onPointerLeave:["pointerleave",!0],onPointerMove:["pointermove",!0],onPointerCancel:["pointercancel",!0],onLostPointerCapture:["lostpointercapture",!0]};function wW(t){const{handlePointer:e}=hW(t);return{priority:1,enabled:!0,compute(n,r,i){r.pointer.set(n.offsetX/r.size.width*2-1,-(n.offsetY/r.size.height)*2+1),r.raycaster.setFromCamera(r.pointer,r.camera)},connected:void 0,handlers:Object.keys($1).reduce((n,r)=>({...n,[r]:e(r)}),{}),update:()=>{var n;const{events:r,internal:i}=t.getState();(n=i.lastEvent)!=null&&n.current&&r.handlers&&r.handlers.onPointerMove(i.lastEvent.current)},connect:n=>{var r;const{set:i,events:s}=t.getState();s.disconnect==null||s.disconnect(),i(o=>({events:{...o.events,connected:n}})),Object.entries((r=s.handlers)!=null?r:[]).forEach(([o,a])=>{const[c,l]=$1[o];n.addEventListener(c,a,{passive:l})})},disconnect:()=>{const{set:n,events:r}=t.getState();if(r.connected){var i;Object.entries((i=r.handlers)!=null?i:[]).forEach(([s,o])=>{if(r&&r.connected instanceof HTMLElement){const[a]=$1[s];r.connected.removeEventListener(a,o)}}),n(s=>({events:{...s.events,connected:void 0}}))}}}}var Rb={exports:{}};function nL(t,e=100,n={}){if(typeof t!="function")throw new TypeError(`Expected the first parameter to be a function, got \`${typeof t}\`.`);if(e<0)throw new RangeError("`wait` must not be negative.");const{immediate:r}=typeof n=="boolean"?{immediate:n}:n;let i,s,o,a,c;function l(){const p=i,m=s;return i=void 0,s=void 0,c=t.apply(p,m),c}function u(){const p=Date.now()-a;p=0?o=setTimeout(u,e-p):(o=void 0,r||(c=l()))}const h=function(...p){if(i&&this!==i&&Object.getPrototypeOf(this)===Object.getPrototypeOf(i))throw new Error("Debounced method called with different contexts of the same prototype.");i=this,s=p,a=Date.now();const m=r&&!o;return o||(o=setTimeout(u,e)),m&&(c=l()),c};return Object.defineProperty(h,"isPending",{get(){return o!==void 0}}),h.clear=()=>{o&&(clearTimeout(o),o=void 0)},h.flush=()=>{o&&h.trigger()},h.trigger=()=>{c=l(),h.clear()},h}Rb.exports.debounce=nL;Rb.exports=nL;var bW=Rb.exports;const TW=Bc(bW);var rL={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(To,function(){return n.importState=function(i){var s=new n;return s.importState(i),s},n;function n(){return function(i){var s=0,o=0,a=0,c=1;i.length==0&&(i=[+new Date]);var l=r();s=l(" "),o=l(" "),a=l(" ");for(var u=0;u>>0,c-=i,c*=i,i=c>>>0,c-=i,i+=c*4294967296}return(i>>>0)*23283064365386963e-26};return s.version="Mash 0.9",s}})})(rL);var AW=rL.exports;const MW=Bc(AW);new St;new St;function Cn(t,e,n){return Math.max(e,Math.min(n,t))}const CW=MW("089fad0j9awfem09wavefc09uwaef");function c2(t){return 2*Math.floor(t/2)}function RW(t,e){return Math.round(t/e)*e}function NW(){return CW()}function sp(t,e){const n=Math.min(t,e),i=Math.max(t,e)-n+1;return n+Math.floor(NW()*i)}/*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2017-2022 Joachim Wester - * MIT licensed - */var kW=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),IW=Object.prototype.hasOwnProperty;function PE(t,e){return IW.call(t,e)}function DE(t){if(Array.isArray(t)){for(var e=new Array(t.length),n=0;n=48&&r<=57){e++;continue}return!1}return!0}function bu(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function iL(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function FE(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&p===void 0&&(l[m]===void 0?p=c.slice(0,u).join("/"):u==h-1&&(p=e.path),p!==void 0&&g(e,0,t,p)),u++,Array.isArray(l)){if(m==="-")m=l.length;else{if(n&&!UE(m))throw new tr("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);UE(m)&&(m=~~m)}if(u>=h){if(n&&e.op==="add"&&m>l.length)throw new tr("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);var o=LW[e.op].call(e,l,m,t);if(o.test===!1)throw new tr("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return o}}else if(u>=h){var o=pf[e.op].call(e,l,m,t);if(o.test===!1)throw new tr("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return o}if(l=l[m],n&&u0)throw new tr('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new tr("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new tr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&FE(t.value))throw new tr("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var i=t.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new tr("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new tr("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var o={op:"_get",path:t.from,value:void 0},a=sL([o],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new tr("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new tr("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function sL(t,e,n){try{if(!Array.isArray(t))throw new tr("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Vv(Bi(e),Bi(t),n||!0);else{n=n||U_;for(var r=0;r0&&(t.patches=[],t.callback&&t.callback(r)),r}function Ib(t,e,n,r,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=DE(e),o=DE(t),a=!1,c=o.length-1;c>=0;c--){var l=o[c],u=t[l];if(PE(e,l)&&!(e[l]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var h=e[l];typeof u=="object"&&u!=null&&typeof h=="object"&&h!=null&&Array.isArray(u)===Array.isArray(h)?Ib(u,h,n,r+"/"+bu(l),i):u!==h&&(i&&n.push({op:"test",path:r+"/"+bu(l),value:Bi(u)}),n.push({op:"replace",path:r+"/"+bu(l),value:Bi(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&n.push({op:"test",path:r+"/"+bu(l),value:Bi(u)}),n.push({op:"remove",path:r+"/"+bu(l)}),a=!0):(i&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}))}if(!(!a&&s.length==o.length))for(var c=0;ch.length?u:h})}function i(l){return l.reduce(function(u,h){return u.lengthcrypto.getRandomValues(new Uint8Array(t)),n9=(t,e,n)=>{let r=(2<{let o="";for(;;){let a=n(i),c=i;for(;c--;)if(o+=t[a[c]&r]||"",o.length===s)return o}}},lL=(t,e=21)=>n9(t,e,t9),r9=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t));for(;t--;)e+=e9[n[t]&63];return e};var uL="abcdefghijklmnopqrstuvwxyz",hL="ABCDEFGHIJKLMNOPQRSTUVWXYZ",fL="0123456789",i9="346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz",s9="6789BCDFGHJKLMNPQRTWbcdfghjkmnpqrtwz";const o9=fL,a9=uL,c9=hL;var l9=o9+a9+c9,zE={lowercase:uL,uppercase:hL,numbers:fL,nolookalikes:i9,nolookalikesSafe:s9,alphanumeric:l9};function fr(){return`sid_${r9(12).replaceAll("-",".")}`}const u9=lL(zE.numbers,4),h9=lL(`${zE.numbers}${zE.lowercase}`,16);function f9(){return`pid_${u9()}_${h9()}`}function d9(t){return(t==null?void 0:t.startsWith("pid_"))??!1}function p9(){return QW({capitalize:!1,adjectiveCount:1})}var wn=(t=>(t[t.BLACK=0]="BLACK",t[t.DKBLUE=1]="DKBLUE",t[t.DKGREEN=2]="DKGREEN",t[t.DKCYAN=3]="DKCYAN",t[t.DKRED=4]="DKRED",t[t.DKPURPLE=5]="DKPURPLE",t[t.DKYELLOW=6]="DKYELLOW",t[t.LTGRAY=7]="LTGRAY",t[t.DKGRAY=8]="DKGRAY",t[t.BLUE=9]="BLUE",t[t.GREEN=10]="GREEN",t[t.CYAN=11]="CYAN",t[t.RED=12]="RED",t[t.PURPLE=13]="PURPLE",t[t.YELLOW=14]="YELLOW",t[t.WHITE=15]="WHITE",t[t.ONBLACK=16]="ONBLACK",t[t.ONDKBLUE=17]="ONDKBLUE",t[t.ONDKGREEN=18]="ONDKGREEN",t[t.ONDKCYAN=19]="ONDKCYAN",t[t.ONDKRED=20]="ONDKRED",t[t.ONDKPURPLE=21]="ONDKPURPLE",t[t.ONDKYELLOW=22]="ONDKYELLOW",t[t.ONLTGRAY=23]="ONLTGRAY",t[t.ONDKGRAY=24]="ONDKGRAY",t[t.ONBLUE=25]="ONBLUE",t[t.ONGREEN=26]="ONGREEN",t[t.ONCYAN=27]="ONCYAN",t[t.ONRED=28]="ONRED",t[t.ONPURPLE=29]="ONPURPLE",t[t.ONYELLOW=30]="ONYELLOW",t[t.ONWHITE=31]="ONWHITE",t[t.ONCLEAR=32]="ONCLEAR",t[t.ONSHADOW=33]="ONSHADOW",t[t.ONBORROW=34]="ONBORROW",t))(wn||{}),zn=(t=>(t[t.ISWALK=0]="ISWALK",t[t.ISSOLID=1]="ISSOLID",t[t.ISSWIM=2]="ISSWIM",t[t.ISBULLET=3]="ISBULLET",t))(zn||{}),F_=(t=>(t[t.ISTERRAIN=0]="ISTERRAIN",t[t.ISOBJECT=1]="ISOBJECT",t))(F_||{}),st=(t=>(t[t.IDLE=0]="IDLE",t[t.NORTH=1]="NORTH",t[t.SOUTH=2]="SOUTH",t[t.WEST=3]="WEST",t[t.EAST=4]="EAST",t[t.BY=5]="BY",t[t.AT=6]="AT",t[t.FLOW=7]="FLOW",t[t.SEEK=8]="SEEK",t[t.RNDNS=9]="RNDNS",t[t.RNDNE=10]="RNDNE",t[t.RND=11]="RND",t[t.CW=12]="CW",t[t.CCW=13]="CCW",t[t.OPP=14]="OPP",t[t.RNDP=15]="RNDP",t))(st||{}),dt=(t=>(t[t.LOADER=0]="LOADER",t[t.BOARD=1]="BOARD",t[t.OBJECT=2]="OBJECT",t[t.TERRAIN=3]="TERRAIN",t[t.CHARSET=4]="CHARSET",t[t.PALETTE=5]="PALETTE",t[t.CONST=6]="CONST",t[t.RANGE=7]="RANGE",t[t.SELECT=8]="SELECT",t[t.NUMBER=9]="NUMBER",t[t.TEXT=10]="TEXT",t[t.LINK=11]="LINK",t[t.HOTKEY=12]="HOTKEY",t[t.SCROLL=13]="SCROLL",t[t.COPYIT=14]="COPYIT",t))(dt||{});function $t(t){return t.toLowerCase().trim()}function m9(t,e,n,r){return{id:fr(),target:t,sender:e,data:n,player:r}}function dL(t){const[e,...n]=t.split(":");return{target:e,path:n.join(":")}}function lh(t,e,n){const r=fr(),i=$t(t),s=e.map($t),o={id(){return r},name(){return t},topics(){return e},emit(a,c,l){Yt.emit(a,r,c,l)},reply(a,c,l,u){o.emit(`${a.sender}:${c}`,l,u)},handle(a){const{target:c,path:l}=dL(a.target),u=$t(c);s.findIndex(h=>h==="all"||h===u)!==-1&&n(a),(r===c||u==="all"||i===u)&&n({...a,target:l})}};return Yt.connect(o),o}const q1=new Set,Yt={emit(t,e,n,r){Yt.invoke(m9(t,e,n,r))},invoke(t){q1.forEach(e=>e.handle(t))},connect(t){q1.add(t)},disconnect(t){q1.delete(t)}};function Vn(t,e,n,r){const i=r??"";return Yt.emit(`error:${e}`,t,n,i),T9(t,n,i)}function g9(t,e){Yt.emit("gadgetserver:desync",t,void 0,e)}function _9(t,e){Yt.emit("gadgetserver:clearscroll",t,void 0,e)}function v9(t,e){Yt.emit("register:dev",t,void 0,e)}function y9(t,e){Yt.emit("register:share",t,void 0,e)}function x9(t){Yt.emit("register:refresh",t)}function S9(t){Yt.emit("register:nuke",t)}function E9(t,e,n){Yt.emit("synth:tts",t,[e,n])}function w9(t,e,n){Yt.emit("synth:play",t,[e,n])}function X1(t,e,n,r){Yt.emit("synth:voice",t,[e,n,r])}function b9(t,e,n,r,i){Yt.emit("synth:voicefx",t,[e,n,r,i])}function ro(t,...e){return Yt.emit("tape:info",t,e),!0}function T9(t,...e){return Yt.emit("tape:error",t,e),!1}function A9(t){Yt.emit("tape:terminal:open",t)}function Lb(t){Yt.emit("tape:terminal:close",t)}function pL(t,e){Yt.emit("tape:terminal:inclayout",t,e)}function u2(t){Yt.emit("tape:crash",t)}function M9(t,e,n,r,i,s){Yt.emit("tape:editor:open",t,[e,n,r,i],s)}function C9(t){Yt.emit("tape:editor:close",t)}function R9(t,e){Yt.emit("vm:init",t,void 0,e)}function N9(t,e,n,r){Yt.emit("vm:books",t,[e,n],r)}function k9(t,e){Yt.emit("vm:login",t,void 0,e)}function I9(t,e){Yt.emit("vm:endgame",t,void 0,e)}function O9(t,e){Yt.emit("vm:doot",t,void 0,e)}function L9(t,e,n,r){Yt.emit("vm:input",t,[e,n],r)}function mL(t,e){return`${t}${e}`}function P9(t,e,n,r){Yt.emit("vm:codewatch",t,[e,n],r)}function D9(t,e,n,r){Yt.emit("vm:coderelease",t,[e,n],r)}function Hv(t,e,n){Yt.emit("vm:cli",t,e,n)}function Tu(t,e=""){Yt.emit("vm:flush",t,e)}function VE(t,e,n){Yt.emit("vm:loadfile",t,e,n)}function qu(t){"@babel/helpers - typeof";return qu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},qu(t)}function Cs(){Cs=function(){return e};var t,e={},n=Object.prototype,r=n.hasOwnProperty,i=Object.defineProperty||function(V,B,z){V[B]=z.value},s=typeof Symbol=="function"?Symbol:{},o=s.iterator||"@@iterator",a=s.asyncIterator||"@@asyncIterator",c=s.toStringTag||"@@toStringTag";function l(V,B,z){return Object.defineProperty(V,B,{value:z,enumerable:!0,configurable:!0,writable:!0}),V[B]}try{l({},"")}catch{l=function(z,W,K){return z[W]=K}}function u(V,B,z,W){var K=B&&B.prototype instanceof _?B:_,j=Object.create(K.prototype),Y=new T(W||[]);return i(j,"_invoke",{value:I(V,z,Y)}),j}function h(V,B,z){try{return{type:"normal",arg:V.call(B,z)}}catch(W){return{type:"throw",arg:W}}}e.wrap=u;var p="suspendedStart",m="suspendedYield",g="executing",v="completed",y={};function _(){}function S(){}function E(){}var b={};l(b,o,function(){return this});var N=Object.getPrototypeOf,R=N&&N(N(H([])));R&&R!==n&&r.call(R,o)&&(b=R);var M=E.prototype=_.prototype=Object.create(b);function O(V){["next","throw","return"].forEach(function(B){l(V,B,function(z){return this._invoke(B,z)})})}function C(V,B){function z(K,j,Y,ge){var Q=h(V[K],V,j);if(Q.type!=="throw"){var re=Q.arg,we=re.value;return we&&qu(we)=="object"&&r.call(we,"__await")?B.resolve(we.__await).then(function(Ae){z("next",Ae,Y,ge)},function(Ae){z("throw",Ae,Y,ge)}):B.resolve(we).then(function(Ae){re.value=Ae,Y(re)},function(Ae){return z("throw",Ae,Y,ge)})}ge(Q.arg)}var W;i(this,"_invoke",{value:function(j,Y){function ge(){return new B(function(Q,re){z(j,Y,Q,re)})}return W=W?W.then(ge,ge):ge()}})}function I(V,B,z){var W=p;return function(K,j){if(W===g)throw Error("Generator is already running");if(W===v){if(K==="throw")throw j;return{value:t,done:!0}}for(z.method=K,z.arg=j;;){var Y=z.delegate;if(Y){var ge=U(Y,z);if(ge){if(ge===y)continue;return ge}}if(z.method==="next")z.sent=z._sent=z.arg;else if(z.method==="throw"){if(W===p)throw W=v,z.arg;z.dispatchException(z.arg)}else z.method==="return"&&z.abrupt("return",z.arg);W=g;var Q=h(V,B,z);if(Q.type==="normal"){if(W=z.done?v:m,Q.arg===y)continue;return{value:Q.arg,done:z.done}}Q.type==="throw"&&(W=v,z.method="throw",z.arg=Q.arg)}}}function U(V,B){var z=B.method,W=V.iterator[z];if(W===t)return B.delegate=null,z==="throw"&&V.iterator.return&&(B.method="return",B.arg=t,U(V,B),B.method==="throw")||z!=="return"&&(B.method="throw",B.arg=new TypeError("The iterator does not provide a '"+z+"' method")),y;var K=h(W,V.iterator,B.arg);if(K.type==="throw")return B.method="throw",B.arg=K.arg,B.delegate=null,y;var j=K.arg;return j?j.done?(B[V.resultName]=j.value,B.next=V.nextLoc,B.method!=="return"&&(B.method="next",B.arg=t),B.delegate=null,y):j:(B.method="throw",B.arg=new TypeError("iterator result is not an object"),B.delegate=null,y)}function L(V){var B={tryLoc:V[0]};1 in V&&(B.catchLoc=V[1]),2 in V&&(B.finallyLoc=V[2],B.afterLoc=V[3]),this.tryEntries.push(B)}function P(V){var B=V.completion||{};B.type="normal",delete B.arg,V.completion=B}function T(V){this.tryEntries=[{tryLoc:"root"}],V.forEach(L,this),this.reset(!0)}function H(V){if(V||V===""){var B=V[o];if(B)return B.call(V);if(typeof V.next=="function")return V;if(!isNaN(V.length)){var z=-1,W=function K(){for(;++z=0;--K){var j=this.tryEntries[K],Y=j.completion;if(j.tryLoc==="root")return W("end");if(j.tryLoc<=this.prev){var ge=r.call(j,"catchLoc"),Q=r.call(j,"finallyLoc");if(ge&&Q){if(this.prev=0;--W){var K=this.tryEntries[W];if(K.tryLoc<=this.prev&&r.call(K,"finallyLoc")&&this.prev=0;--z){var W=this.tryEntries[z];if(W.finallyLoc===B)return this.complete(W.completion,W.afterLoc),P(W),y}},catch:function(B){for(var z=this.tryEntries.length-1;z>=0;--z){var W=this.tryEntries[z];if(W.tryLoc===B){var K=W.completion;if(K.type==="throw"){var j=K.arg;P(W)}return j}}throw Error("illegal catch attempt")},delegateYield:function(B,z,W){return this.delegate={iterator:H(B),resultName:z,nextLoc:W},this.method==="next"&&(this.arg=t),y}},e}function h2(t,e,n,r,i,s,o){try{var a=t[s](o),c=a.value}catch(l){return void n(l)}a.done?e(c):Promise.resolve(c).then(r,i)}function Tf(t){return function(){var e=this,n=arguments;return new Promise(function(r,i){var s=t.apply(e,n);function o(c){h2(s,r,i,o,a,"next",c)}function a(c){h2(s,r,i,o,a,"throw",c)}o(void 0)})}}function U9(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function F9(t,e){if(qu(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(qu(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function gL(t){var e=F9(t,"string");return qu(e)=="symbol"?e:e+""}function B9(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=Array(e);nt==null,J9=t=>encodeURIComponent(t).replaceAll(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),GE=Symbol("encodeFragmentIdentifier");function Q9(t){switch(t.arrayFormat){case"index":return e=>(n,r)=>{const i=n.length;return r===void 0||t.skipNull&&r===null||t.skipEmptyString&&r===""?n:r===null?[...n,[Tr(e,t),"[",i,"]"].join("")]:[...n,[Tr(e,t),"[",Tr(i,t),"]=",Tr(r,t)].join("")]};case"bracket":return e=>(n,r)=>r===void 0||t.skipNull&&r===null||t.skipEmptyString&&r===""?n:r===null?[...n,[Tr(e,t),"[]"].join("")]:[...n,[Tr(e,t),"[]=",Tr(r,t)].join("")];case"colon-list-separator":return e=>(n,r)=>r===void 0||t.skipNull&&r===null||t.skipEmptyString&&r===""?n:r===null?[...n,[Tr(e,t),":list="].join("")]:[...n,[Tr(e,t),":list=",Tr(r,t)].join("")];case"comma":case"separator":case"bracket-separator":{const e=t.arrayFormat==="bracket-separator"?"[]=":"=";return n=>(r,i)=>i===void 0||t.skipNull&&i===null||t.skipEmptyString&&i===""?r:(i=i===null?"":i,r.length===0?[[Tr(n,t),e,Tr(i,t)].join("")]:[[r,Tr(i,t)].join(t.arrayFormatSeparator)])}default:return e=>(n,r)=>r===void 0||t.skipNull&&r===null||t.skipEmptyString&&r===""?n:r===null?[...n,Tr(e,t)]:[...n,[Tr(e,t),"=",Tr(r,t)].join("")]}}function ej(t){let e;switch(t.arrayFormat){case"index":return(n,r,i)=>{if(e=/\[(\d*)]$/.exec(n),n=n.replace(/\[\d*]$/,""),!e){i[n]=r;return}i[n]===void 0&&(i[n]={}),i[n][e[1]]=r};case"bracket":return(n,r,i)=>{if(e=/(\[])$/.exec(n),n=n.replace(/\[]$/,""),!e){i[n]=r;return}if(i[n]===void 0){i[n]=[r];return}i[n]=[...i[n],r]};case"colon-list-separator":return(n,r,i)=>{if(e=/(:list)$/.exec(n),n=n.replace(/:list$/,""),!e){i[n]=r;return}if(i[n]===void 0){i[n]=[r];return}i[n]=[...i[n],r]};case"comma":case"separator":return(n,r,i)=>{const s=typeof r=="string"&&r.includes(t.arrayFormatSeparator),o=typeof r=="string"&&!s&&pc(r,t).includes(t.arrayFormatSeparator);r=o?pc(r,t):r;const a=s||o?r.split(t.arrayFormatSeparator).map(c=>pc(c,t)):r===null?r:pc(r,t);i[n]=a};case"bracket-separator":return(n,r,i)=>{const s=/(\[])$/.test(n);if(n=n.replace(/\[]$/,""),!s){i[n]=r&&pc(r,t);return}const o=r===null?[]:pc(r,t).split(t.arrayFormatSeparator);if(i[n]===void 0){i[n]=o;return}i[n]=[...i[n],...o]};default:return(n,r,i)=>{if(i[n]===void 0){i[n]=r;return}i[n]=[...[i[n]].flat(),r]}}}function xL(t){if(typeof t!="string"||t.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function Tr(t,e){return e.encode?e.strict?J9(t):encodeURIComponent(t):t}function pc(t,e){return e.decode?K9(t):t}function SL(t){return Array.isArray(t)?t.sort():typeof t=="object"?SL(Object.keys(t)).sort((e,n)=>Number(e)-Number(n)).map(e=>t[e]):t}function EL(t){const e=t.indexOf("#");return e!==-1&&(t=t.slice(0,e)),t}function tj(t){let e="";const n=t.indexOf("#");return n!==-1&&(e=t.slice(n)),e}function m2(t,e,n){return n==="string"&&typeof t=="string"?t:typeof n=="function"&&typeof t=="string"?n(t):e.parseBooleans&&t!==null&&(t.toLowerCase()==="true"||t.toLowerCase()==="false")?t.toLowerCase()==="true":n==="number"&&!Number.isNaN(Number(t))&&typeof t=="string"&&t.trim()!==""||e.parseNumbers&&!Number.isNaN(Number(t))&&typeof t=="string"&&t.trim()!==""?Number(t):t}function Db(t){t=EL(t);const e=t.indexOf("?");return e===-1?"":t.slice(e+1)}function Ub(t,e){e={decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1,types:Object.create(null),...e},xL(e.arrayFormatSeparator);const n=ej(e),r=Object.create(null);if(typeof t!="string"||(t=t.trim().replace(/^[?#&]/,""),!t))return r;for(const i of t.split("&")){if(i==="")continue;const s=e.decode?i.replaceAll("+"," "):i;let[o,a]=yL(s,"=");o===void 0&&(o=s),a=a===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?a:pc(a,e),n(pc(o,e),a,r)}for(const[i,s]of Object.entries(r))if(typeof s=="object"&&s!==null&&e.types[i]!=="string")for(const[o,a]of Object.entries(s)){const c=e.types[i]?e.types[i].replace("[]",""):void 0;s[o]=m2(a,e,c)}else typeof s=="object"&&s!==null&&e.types[i]==="string"?r[i]=Object.values(s).join(e.arrayFormatSeparator):r[i]=m2(s,e,e.types[i]);return e.sort===!1?r:(e.sort===!0?Object.keys(r).sort():Object.keys(r).sort(e.sort)).reduce((i,s)=>{const o=r[s];return i[s]=o&&typeof o=="object"&&!Array.isArray(o)?SL(o):o,i},Object.create(null))}function wL(t,e){if(!t)return"";e={encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:",",...e},xL(e.arrayFormatSeparator);const n=o=>e.skipNull&&Z9(t[o])||e.skipEmptyString&&t[o]==="",r=Q9(e),i={};for(const[o,a]of Object.entries(t))n(o)||(i[o]=a);const s=Object.keys(i);return e.sort!==!1&&s.sort(e.sort),s.map(o=>{const a=t[o];return a===void 0?"":a===null?Tr(o,e):Array.isArray(a)?a.length===0&&e.arrayFormat==="bracket-separator"?Tr(o,e)+"[]":a.reduce(r(o),[]).join("&"):Tr(o,e)+"="+Tr(a,e)}).filter(o=>o.length>0).join("&")}function bL(t,e){var i;e={decode:!0,...e};let[n,r]=yL(t,"#");return n===void 0&&(n=t),{url:((i=n==null?void 0:n.split("?"))==null?void 0:i[0])??"",query:Ub(Db(t),e),...e&&e.parseFragmentIdentifier&&r?{fragmentIdentifier:pc(r,e)}:{}}}function TL(t,e){e={encode:!0,strict:!0,[GE]:!0,...e};const n=EL(t.url).split("?")[0]||"",r=Db(t.url),i={...Ub(r,{sort:!1}),...t.query};let s=wL(i,e);s&&(s=`?${s}`);let o=tj(t.url);if(typeof t.fragmentIdentifier=="string"){const a=new URL(n);a.hash=t.fragmentIdentifier,o=e[GE]?a.hash:`#${t.fragmentIdentifier}`}return`${n}${s}${o}`}function AL(t,e,n){n={parseFragmentIdentifier:!0,[GE]:!1,...n};const{url:r,query:i,fragmentIdentifier:s}=bL(t,n);return TL({url:r,query:Y9(i,e),fragmentIdentifier:s},n)}function nj(t,e,n){const r=Array.isArray(e)?i=>!e.includes(i):(i,s)=>!e(i,s);return AL(t,r,n)}const rj=Object.freeze(Object.defineProperty({__proto__:null,exclude:nj,extract:Db,parse:Ub,parseUrl:bL,pick:AL,stringify:wL,stringifyUrl:TL},Symbol.toStringTag,{value:"Module"}));var ai=[];for(var K1=0;K1<256;++K1)ai.push((K1+256).toString(16).slice(1));function ij(t,e=0){return(ai[t[e+0]]+ai[t[e+1]]+ai[t[e+2]]+ai[t[e+3]]+"-"+ai[t[e+4]]+ai[t[e+5]]+"-"+ai[t[e+6]]+ai[t[e+7]]+"-"+ai[t[e+8]]+ai[t[e+9]]+"-"+ai[t[e+10]]+ai[t[e+11]]+ai[t[e+12]]+ai[t[e+13]]+ai[t[e+14]]+ai[t[e+15]]).toLowerCase()}var v0,sj=new Uint8Array(16);function oj(){if(!v0&&(v0=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!v0))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return v0(sj)}var aj=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const g2={randomUUID:aj};function cj(t,e,n){if(g2.randomUUID&&!e&&!t)return g2.randomUUID();t=t||{};var r=t.random||(t.rng||oj)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,ij(r)}var lj=function(e,n){var r=n.voice;return'').concat(e,"")},uj=function(e,n){var r=n.style;return r?'').concat(e,""):e},hj=function(e,n){var r=n.pitch,i=n.rate;return!r&&!i?e:'').concat(e,"")},fj=function(e){return''.concat(e,"")},dj=function(e,n){var r=hj(e,n);return r=uj(r,n),r=lj(r,n),r=fj(r),r},_2=function(e,n){for(var r=[],i=0,s=Object.entries(e);i=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s,o=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var l=n.next();return o=l.done,l},e:function(l){a=!0,s=l},f:function(){try{o||n.return==null||n.return()}finally{if(a)throw s}}}}var mj=function(e){var n={},r=pj(e.slice(0,e.indexOf(`\r -\r -`)).split(`\r -`)),i;try{for(r.s();!(i=r.n()).done;){var s=i.value,o=s.split(":",2),a=Pb(o,2),c=a[0],l=a[1];n[c]=l}}catch(u){r.e(u)}finally{r.f()}return{data:e.slice(e.indexOf(`\r -\r -`)+4),headers:n}},gj="wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1",_j="6A5AA1D4EAFF4E9FB37E23D68491D6F4",vj=JSON.stringify({context:{synthesis:{audio:{metadataoptions:{sentenceBoundaryEnabled:!1,wordBoundaryEnabled:!0},outputFormat:"audio-24khz-48kbitrate-mono-mp3"}}}}),yj=function(e){var n=new Date().toString(),r={"Content-Type":"application/json; charset=utf-8",Path:"speech.config","X-Timestamp":n},i={"Content-Type":"application/ssml+xml",Path:"ssml","X-RequestId":e,"X-Timestamp":n};return{configHeader:r,contentHeader:i}},ML=function(){var t=Tf(Cs().mark(function e(n){var r,i,s,o,a,c,l,u,h,p,m,g,v,y=arguments;return Cs().wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return r=n.payload,i=y.length>1&&y[1]!==void 0?y[1]:{},s=i.proxyUrl,o=i.token,a=r.input,c=r.options,l=cj().replaceAll("-",""),u=rj.stringifyUrl({query:{ConnectionId:l,TrustedClientToken:o||_j},url:s||gj}),h=yj(l),p=h.configHeader,m=h.contentHeader,g=_2(p,vj),v=_2(m,dj(a,c)),S.abrupt("return",new Promise(function(E,b){var N=new WebSocket(u);N.binaryType="arraybuffer";var R=function(){N.send(g),N.send(v)},M=new ArrayBuffer(0),O=function(){var I=Tf(Cs().mark(function U(L){var P,T,H,V,B,z,W,K;return Cs().wrap(function(Y){for(;;)switch(Y.prev=Y.next){case 0:if(typeof L.data!="string"){Y.next=13;break}P=mj(L.data),T=P.headers,Y.t0=T.Path,Y.next=Y.t0==="turn.end"?5:11;break;case 5:if(N.close(),M.byteLength){Y.next=8;break}return Y.abrupt("return");case 8:return H=new Response(M),E(H),Y.abrupt("break",11);case 11:Y.next=14;break;case 13:L.data instanceof ArrayBuffer&&(V=new DataView(L.data),B=V.getInt16(0),L.data.byteLength>B+2&&(z=L.data.slice(2+B),W=new ArrayBuffer(M.byteLength+z.byteLength),K=new Uint8Array(W),K.set(new Uint8Array(M),0),K.set(new Uint8Array(z),M.byteLength),M=W));case 14:case"end":return Y.stop()}},U)}));return function(L){return I.apply(this,arguments)}}(),C=function(){b(new Error("WebSocket error occurred.")),N.close()};N.addEventListener("open",R),N.addEventListener("message",O),N.addEventListener("error",C)}));case 9:case"end":return S.stop()}},e)}));return function(n){return t.apply(this,arguments)}}(),CL=typeof global=="object"&&global&&global.Object===Object&&global,xj=typeof self=="object"&&self&&self.Object===Object&&self,Pa=CL||xj||Function("return this")(),co=Pa.Symbol,RL=Object.prototype,Sj=RL.hasOwnProperty,Ej=RL.toString,qd=co?co.toStringTag:void 0;function wj(t){var e=Sj.call(t,qd),n=t[qd];try{t[qd]=void 0;var r=!0}catch{}var i=Ej.call(t);return r&&(e?t[qd]=n:delete t[qd]),i}var bj=Object.prototype,Tj=bj.toString;function Aj(t){return Tj.call(t)}var Mj="[object Null]",Cj="[object Undefined]",v2=co?co.toStringTag:void 0;function $l(t){return t==null?t===void 0?Cj:Mj:v2&&v2 in Object(t)?wj(t):Aj(t)}function Io(t){return t!=null&&typeof t=="object"}var Rj="[object Symbol]";function Gv(t){return typeof t=="symbol"||Io(t)&&$l(t)==Rj}function Wv(t,e){for(var n=-1,r=t==null?0:t.length,i=Array(r);++n0){if(++e>=a$)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function h$(t){return function(){return t}}var B_=function(){try{var t=hh(Object,"defineProperty");return t({},"",{}),t}catch{}}(),f$=B_?function(t,e){return B_(t,"toString",{configurable:!0,enumerable:!1,value:h$(e),writable:!0})}:Vf,d$=u$(f$);function kL(t,e){for(var n=-1,r=t==null?0:t.length;++n-1}var g$=9007199254740991,_$=/^(?:0|[1-9]\d*)$/;function $v(t,e){var n=typeof t;return e=e??g$,!!e&&(n=="number"||n!="symbol"&&_$.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=S$}function Da(t){return t!=null&&Hb(t.length)&&!Hc(t)}function LL(t,e,n){if(!lo(n))return!1;var r=typeof e;return(r=="number"?Da(n)&&$v(e,n.length):r=="string"&&e in n)?nm(n[e],t):!1}function E$(t){return Vb(function(e,n){var r=-1,i=n.length,s=i>1?n[i-1]:void 0,o=i>2?n[2]:void 0;for(s=t.length>3&&typeof s=="function"?(i--,s):void 0,o&&LL(n[0],n[1],o)&&(s=i<3?void 0:s,i=1),e=Object(e);++r-1}function O7(t,e){var n=this.__data__,r=Yv(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}function Gc(t){var e=-1,n=t==null?0:t.length;for(this.clear();++ei?0:i+e),n=n>i?i:n,n<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var s=Array(i);++r=r?t:Kb(t,e,n)}var Y7="\\ud800-\\udfff",Z7="\\u0300-\\u036f",J7="\\ufe20-\\ufe2f",Q7="\\u20d0-\\u20ff",eq=Z7+J7+Q7,tq="\\ufe0e\\ufe0f",nq="\\u200d",rq=RegExp("["+nq+Y7+eq+tq+"]");function WL(t){return rq.test(t)}function iq(t){return t.split("")}var jL="\\ud800-\\udfff",sq="\\u0300-\\u036f",oq="\\ufe20-\\ufe2f",aq="\\u20d0-\\u20ff",cq=sq+oq+aq,lq="\\ufe0e\\ufe0f",uq="["+jL+"]",jE="["+cq+"]",$E="\\ud83c[\\udffb-\\udfff]",hq="(?:"+jE+"|"+$E+")",$L="[^"+jL+"]",qL="(?:\\ud83c[\\udde6-\\uddff]){2}",XL="[\\ud800-\\udbff][\\udc00-\\udfff]",fq="\\u200d",KL=hq+"?",YL="["+lq+"]?",dq="(?:"+fq+"(?:"+[$L,qL,XL].join("|")+")"+YL+KL+")*",pq=YL+KL+dq,mq="(?:"+[$L+jE+"?",jE,qL,XL,uq].join("|")+")",gq=RegExp($E+"(?="+$E+")|"+mq+pq,"g");function _q(t){return t.match(gq)||[]}function vq(t){return WL(t)?_q(t):iq(t)}function yq(t){return function(e){e=HL(e);var n=WL(e)?vq(e):void 0,r=n?n[0]:e.charAt(0),i=n?K7(n,1).join(""):e.slice(1);return r[t]()+i}}var ZL=yq("toUpperCase");function xq(t,e,n,r){var i=-1,s=t==null?0:t.length;for(r&&s&&(n=t[++i]);++ia))return!1;var l=s.get(t),u=s.get(e);if(l&&u)return l==e&&u==t;var h=-1,p=!0,m=n&JX?new Hf:void 0;for(s.set(t,e),s.set(e,t);++h2?e[2]:void 0;for(i&&LL(e[0],e[1],i)&&(r=1);++n=HK&&(s=Jb,o=!1,e=new Hf(e));e:for(;++i-1?i[s?e[o]:o]:void 0}}var XK=Math.max;function KK(t,e,n){var r=t==null?0:t.length;if(!r)return-1;var i=n==null?0:jv(n);return i<0&&(i=XK(r+i,0)),IL(t,Ua(e),i)}var Wf=qK(KK);function Oo(t){return t&&t.length?t[0]:void 0}function YK(t,e){var n=-1,r=Da(t)?Array(t.length):[];return fh(t,function(i,s,o){r[++n]=e(i,s,o)}),r}function ot(t,e){var n=un(t)?Wv:YK;return n(t,Ua(e))}function io(t,e){return Xb(ot(t,e))}var ZK=Object.prototype,JK=ZK.hasOwnProperty,hP=zK(function(t,e,n){JK.call(t,n)?t[n].push(e):Bb(t,n,[e])}),QK=Object.prototype,eY=QK.hasOwnProperty;function tY(t,e){return t!=null&&eY.call(t,e)}function wt(t,e){return t!=null&&cP(t,e,tY)}var nY="[object String]";function ds(t){return typeof t=="string"||!un(t)&&Io(t)&&$l(t)==nY}function rY(t,e){return Wv(e,function(n){return t[n]})}function Rr(t){return t==null?[]:rY(t,uo(t))}var iY=Math.max;function qi(t,e,n,r){t=Da(t)?t:Rr(t),n=n&&!r?jv(n):0;var i=t.length;return n<0&&(n=iY(i+n,0)),ds(t)?n<=i&&t.indexOf(e,n)>-1:!!i&&Fb(t,e,n)>-1}function K2(t,e,n){var r=t==null?0:t.length;if(!r)return-1;var i=0;return Fb(t,e,i)}var sY="[object Map]",oY="[object Set]",aY=Object.prototype,cY=aY.hasOwnProperty;function Dn(t){if(t==null)return!0;if(Da(t)&&(un(t)||typeof t=="string"||typeof t.splice=="function"||Ap(t)||Gb(t)||Xv(t)))return!t.length;var e=Ys(t);if(e==sY||e==oY)return!t.size;if(rm(t))return!zL(t).length;for(var n in t)if(cY.call(t,n))return!1;return!0}var lY="[object RegExp]";function uY(t){return Io(t)&&$l(t)==lY}var Y2=Ol&&Ol.isRegExp,Ic=Y2?Kv(Y2):uY;function Oc(t){return t===void 0}var hY="Expected a function";function fY(t){if(typeof t!="function")throw new TypeError(hY);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}function dY(t,e,n,r){if(!lo(t))return t;e=Jv(e,t);for(var i=-1,s=e.length,o=s-1,a=t;a!=null&&++i=yY){var l=vY(t);if(l)return Qb(l);o=!1,i=Jb,c=new Hf}else c=a;e:for(;++r0&&arguments[0]!==void 0?arguments[0]:{},r=n.serviceUrl,i=n.locale,s=n.headers;U9(this,t),ha(this,"locale",void 0),ha(this,"serviceUrl",void 0),ha(this,"headers",void 0),ha(this,"fetch",function(){var o=Tf(Cs().mark(function a(c){var l;return Cs().wrap(function(h){for(;;)switch(h.prev=h.next){case 0:return h.next=2,e.serviceUrl?fetch(e.serviceUrl,{body:JSON.stringify(c),headers:e.headers,method:"POST"}):ML({payload:c});case 2:return l=h.sent,h.abrupt("return",l);case 4:case"end":return h.stop()}},a)}));return function(a){return o.apply(this,arguments)}}()),ha(this,"create",function(){var o=Tf(Cs().mark(function a(c){return Cs().wrap(function(u){for(;;)switch(u.prev=u.next){case 0:return u.abrupt("return",e.fetch(c));case 1:case"end":return u.stop()}},a)}));return function(a){return o.apply(this,arguments)}}()),ha(this,"createAudio",function(){var o=Tf(Cs().mark(function a(c){var l,u;return Cs().wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,e.create(c);case 2:return l=p.sent,p.next=5,l.arrayBuffer();case 5:return u=p.sent,p.abrupt("return",V9(u));case 7:case"end":return p.stop()}},a)}));return function(a){return o.apply(this,arguments)}}()),this.locale=i,this.serviceUrl=r,this.headers=s}return z9(t,[{key:"voiceOptions",get:function(){return SY(this.locale)}}]),t}();ha(om,"localeOptions",$9());ha(om,"voiceList",a_);ha(om,"voiceName",c_);ha(om,"createRequest",ML);const fP="15.0.4",Z2=(t,e,n)=>({endTime:e,insertTime:n,type:"exponentialRampToValue",value:t}),J2=(t,e,n)=>({endTime:e,insertTime:n,type:"linearRampToValue",value:t}),YE=(t,e)=>({startTime:e,type:"setValue",value:t}),dP=(t,e,n)=>({duration:n,startTime:e,type:"setValueCurve",values:t}),pP=(t,e,{startTime:n,target:r,timeConstant:i})=>r+(e-r)*Math.exp((n-t)/i),mf=t=>t.type==="exponentialRampToValue",V_=t=>t.type==="linearRampToValue",yl=t=>mf(t)||V_(t),rT=t=>t.type==="setValue",dc=t=>t.type==="setValueCurve",H_=(t,e,n,r)=>{const i=t[e];return i===void 0?r:yl(i)||rT(i)?i.value:dc(i)?i.values[i.values.length-1]:pP(n,H_(t,e-1,i.startTime,r),i)},Q2=(t,e,n,r,i)=>n===void 0?[r.insertTime,i]:yl(n)?[n.endTime,n.value]:rT(n)?[n.startTime,n.value]:dc(n)?[n.startTime+n.duration,n.values[n.values.length-1]]:[n.startTime,H_(t,e-1,n.startTime,i)],ZE=t=>t.type==="cancelAndHold",JE=t=>t.type==="cancelScheduledValues",_l=t=>ZE(t)||JE(t)?t.cancelTime:mf(t)||V_(t)?t.endTime:t.startTime,eN=(t,e,n,{endTime:r,value:i})=>n===i?i:0n+(t-e)/(r-e)*(i-n),EY=(t,e)=>{const n=Math.floor(e),r=Math.ceil(e);return n===r?t[n]:(1-(e-n))*t[n]+(1-(r-e))*t[r]},wY=(t,{duration:e,startTime:n,values:r})=>{const i=(t-n)/e*(r.length-1);return EY(r,i)},x0=t=>t.type==="setTarget";class bY{constructor(e){this._automationEvents=[],this._currenTime=0,this._defaultValue=e}[Symbol.iterator](){return this._automationEvents[Symbol.iterator]()}add(e){const n=_l(e);if(ZE(e)||JE(e)){const r=this._automationEvents.findIndex(s=>JE(e)&&dc(s)?s.startTime+s.duration>=n:_l(s)>=n),i=this._automationEvents[r];if(r!==-1&&(this._automationEvents=this._automationEvents.slice(0,r)),ZE(e)){const s=this._automationEvents[this._automationEvents.length-1];if(i!==void 0&&yl(i)){if(s!==void 0&&x0(s))throw new Error("The internal list is malformed.");const o=s===void 0?i.insertTime:dc(s)?s.startTime+s.duration:_l(s),a=s===void 0?this._defaultValue:dc(s)?s.values[s.values.length-1]:s.value,c=mf(i)?eN(n,o,a,i):tN(n,o,a,i),l=mf(i)?Z2(c,n,this._currenTime):J2(c,n,this._currenTime);this._automationEvents.push(l)}if(s!==void 0&&x0(s)&&this._automationEvents.push(YE(this.getValue(n),n)),s!==void 0&&dc(s)&&s.startTime+s.duration>n){const o=n-s.startTime,a=(s.values.length-1)/s.duration,c=Math.max(2,1+Math.ceil(o*a)),l=o/(c-1)*a,u=s.values.slice(0,c);if(l<1)for(let h=1;h_l(o)>n),i=r===-1?this._automationEvents[this._automationEvents.length-1]:this._automationEvents[r-1];if(i!==void 0&&dc(i)&&_l(i)+i.duration>n)return!1;const s=mf(e)?Z2(e.value,e.endTime,this._currenTime):V_(e)?J2(e.value,n,this._currenTime):e;if(r===-1)this._automationEvents.push(s);else{if(dc(e)&&n+e.duration>_l(this._automationEvents[r]))return!1;this._automationEvents.splice(r,0,s)}}return!0}flush(e){const n=this._automationEvents.findIndex(r=>_l(r)>e);if(n>1){const r=this._automationEvents.slice(n-1),i=r[0];x0(i)&&r.unshift(YE(H_(this._automationEvents,n-2,i.startTime,this._defaultValue),i.startTime)),this._automationEvents=r}}getValue(e){if(this._automationEvents.length===0)return this._defaultValue;const n=this._automationEvents.findIndex(o=>_l(o)>e),r=this._automationEvents[n],i=(n===-1?this._automationEvents.length:n)-1,s=this._automationEvents[i];if(s!==void 0&&x0(s)&&(r===void 0||!yl(r)||r.insertTime>e))return pP(e,H_(this._automationEvents,i-1,s.startTime,this._defaultValue),s);if(s!==void 0&&rT(s)&&(r===void 0||!yl(r)))return s.value;if(s!==void 0&&dc(s)&&(r===void 0||!yl(r)||s.startTime+s.duration>e))return e({cancelTime:t,type:"cancelAndHold"}),AY=t=>({cancelTime:t,type:"cancelScheduledValues"}),MY=(t,e)=>({endTime:e,type:"exponentialRampToValue",value:t}),CY=(t,e)=>({endTime:e,type:"linearRampToValue",value:t}),RY=(t,e,n)=>({startTime:e,target:t,timeConstant:n,type:"setTarget"}),NY=()=>new DOMException("","AbortError"),kY=t=>(e,n,[r,i,s],o)=>{t(e[i],[n,r,s],a=>a[0]===n&&a[1]===r,o)},IY=t=>(e,n,r)=>{const i=[];for(let s=0;s(e,n)=>{t.set(e,{activeInputs:new Set,passiveInputs:new WeakMap,renderer:n})},jf=new WeakSet,mP=new WeakMap,iT=new WeakMap,gP=new WeakMap,sT=new WeakMap,ny=new WeakMap,_P=new WeakMap,QE=new WeakMap,ew=new WeakMap,tw=new WeakMap,vP={construct(){return vP}},LY=t=>{try{const e=new Proxy(t,vP);new e}catch{return!1}return!0},nN=/^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/,rN=(t,e)=>{const n=[];let r=t.replace(/^[\s]+/,""),i=r.match(nN);for(;i!==null;){const s=i[1].slice(1,-1),o=i[0].replace(/([\s]+)?;?$/,"").replace(s,new URL(s,e).toString());n.push(o),r=r.slice(i[0].length).replace(/^[\s]+/,""),i=r.match(nN)}return[n.join(";"),r]},iN=t=>{if(t!==void 0&&!Array.isArray(t))throw new TypeError("The parameterDescriptors property of given value for processorCtor is not an array.")},sN=t=>{if(!LY(t))throw new TypeError("The given value for processorCtor should be a constructor.");if(t.prototype===null||typeof t.prototype!="object")throw new TypeError("The given value for processorCtor should have a prototype.")},PY=(t,e,n,r,i,s,o,a,c,l,u,h,p)=>{let m=0;return(g,v,y={credentials:"omit"})=>{const _=u.get(g);if(_!==void 0&&_.has(v))return Promise.resolve();const S=l.get(g);if(S!==void 0){const N=S.get(v);if(N!==void 0)return N}const E=s(g),b=E.audioWorklet===void 0?i(v).then(([N,R])=>{const[M,O]=rN(N,R),C=`${M};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${O} -})})(window,'_AWGS')`;return n(C)}).then(()=>{const N=p._AWGS.pop();if(N===void 0)throw new SyntaxError;r(E.currentTime,E.sampleRate,()=>N(class{},void 0,(R,M)=>{if(R.trim()==="")throw e();const O=ew.get(E);if(O!==void 0){if(O.has(R))throw e();sN(M),iN(M.parameterDescriptors),O.set(R,M)}else sN(M),iN(M.parameterDescriptors),ew.set(E,new Map([[R,M]]))},E.sampleRate,void 0,void 0))}):Promise.all([i(v),Promise.resolve(t(h,h))]).then(([[N,R],M])=>{const O=m+1;m=O;const[C,I]=rN(N,R),T=`${C};((AudioWorkletProcessor,registerProcessor)=>{${I} -})(${M?"AudioWorkletProcessor":"class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}"},(n,p)=>registerProcessor(n,class extends p{${M?"":"__c = (a) => a.forEach(e=>this.__b.add(e.buffer));"}process(i,o,p){${M?"":"i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));"}return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac${O}',class extends AudioWorkletProcessor{process(){return !1}})`,H=new Blob([T],{type:"application/javascript; charset=utf-8"}),V=URL.createObjectURL(H);return E.audioWorklet.addModule(V,y).then(()=>{if(a(E))return E;const B=o(E);return B.audioWorklet.addModule(V,y).then(()=>B)}).then(B=>{if(c===null)throw new SyntaxError;try{new c(B,`__sac${O}`)}catch{throw new SyntaxError}}).finally(()=>URL.revokeObjectURL(V))});return S===void 0?l.set(g,new Map([[v,b]])):S.set(v,b),b.then(()=>{const N=u.get(g);N===void 0?u.set(g,new Set([v])):N.add(v)}).finally(()=>{const N=l.get(g);N!==void 0&&N.delete(v)}),b}},Lo=(t,e)=>{const n=t.get(e);if(n===void 0)throw new Error("A value with the given key could not be found.");return n},ry=(t,e)=>{const n=Array.from(t).filter(e);if(n.length>1)throw Error("More than one element was found.");if(n.length===0)throw Error("No element was found.");const[r]=n;return t.delete(r),r},yP=(t,e,n,r)=>{const i=Lo(t,e),s=ry(i,o=>o[0]===n&&o[1]===r);return i.size===0&&t.delete(e),s},am=t=>Lo(_P,t),$f=t=>{if(jf.has(t))throw new Error("The AudioNode is already stored.");jf.add(t),am(t).forEach(e=>e(!0))},xP=t=>"port"in t,cm=t=>{if(!jf.has(t))throw new Error("The AudioNode is not stored.");jf.delete(t),am(t).forEach(e=>e(!1))},nw=(t,e)=>{!xP(t)&&e.every(n=>n.size===0)&&cm(t)},DY=(t,e,n,r,i,s,o,a,c,l,u,h,p)=>{const m=new WeakMap;return(g,v,y,_,S)=>{const{activeInputs:E,passiveInputs:b}=s(v),{outputs:N}=s(g),R=a(g),M=O=>{const C=c(v),I=c(g);if(O){const U=yP(b,g,y,_);t(E,g,U,!1),!S&&!h(g)&&n(I,C,y,_),p(v)&&$f(v)}else{const U=r(E,g,y,_);e(b,_,U,!1),!S&&!h(g)&&i(I,C,y,_);const L=o(v);if(L===0)u(v)&&nw(v,E);else{const P=m.get(v);P!==void 0&&clearTimeout(P),m.set(v,setTimeout(()=>{u(v)&&nw(v,E)},L*1e3))}}};return l(N,[v,y,_],O=>O[0]===v&&O[1]===y&&O[2]===_,!0)?(R.add(M),u(g)?t(E,g,[y,_,M],!0):e(b,_,[g,y,M],!0),!0):!1}},UY=t=>(e,n,[r,i,s],o)=>{const a=e.get(r);a===void 0?e.set(r,new Set([[i,n,s]])):t(a,[i,n,s],c=>c[0]===i&&c[1]===n,o)},FY=t=>(e,n)=>{const r=t(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});n.connect(r).connect(e.destination);const i=()=>{n.removeEventListener("ended",i),n.disconnect(r),r.disconnect()};n.addEventListener("ended",i)},BY=t=>(e,n)=>{t(e).add(n)},zY={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",fftSize:2048,maxDecibels:-30,minDecibels:-100,smoothingTimeConstant:.8},VY=(t,e,n,r,i,s)=>class extends t{constructor(a,c){const l=i(a),u={...zY,...c},h=r(l,u),p=s(l)?e():null;super(a,!1,h,p),this._nativeAnalyserNode=h}get fftSize(){return this._nativeAnalyserNode.fftSize}set fftSize(a){this._nativeAnalyserNode.fftSize=a}get frequencyBinCount(){return this._nativeAnalyserNode.frequencyBinCount}get maxDecibels(){return this._nativeAnalyserNode.maxDecibels}set maxDecibels(a){const c=this._nativeAnalyserNode.maxDecibels;if(this._nativeAnalyserNode.maxDecibels=a,!(a>this._nativeAnalyserNode.minDecibels))throw this._nativeAnalyserNode.maxDecibels=c,n()}get minDecibels(){return this._nativeAnalyserNode.minDecibels}set minDecibels(a){const c=this._nativeAnalyserNode.minDecibels;if(this._nativeAnalyserNode.minDecibels=a,!(this._nativeAnalyserNode.maxDecibels>a))throw this._nativeAnalyserNode.minDecibels=c,n()}get smoothingTimeConstant(){return this._nativeAnalyserNode.smoothingTimeConstant}set smoothingTimeConstant(a){this._nativeAnalyserNode.smoothingTimeConstant=a}getByteFrequencyData(a){this._nativeAnalyserNode.getByteFrequencyData(a)}getByteTimeDomainData(a){this._nativeAnalyserNode.getByteTimeDomainData(a)}getFloatFrequencyData(a){this._nativeAnalyserNode.getFloatFrequencyData(a)}getFloatTimeDomainData(a){this._nativeAnalyserNode.getFloatTimeDomainData(a)}},Ai=(t,e)=>t.context===e,HY=(t,e,n)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!Ai(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,fftSize:a.fftSize,maxDecibels:a.maxDecibels,minDecibels:a.minDecibels,smoothingTimeConstant:a.smoothingTimeConstant};a=t(o,l)}return r.set(o,a),await n(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},G_=t=>{try{t.copyToChannel(new Float32Array(1),0,-1)}catch{return!1}return!0},Fa=()=>new DOMException("","IndexSizeError"),oT=t=>{t.getChannelData=(e=>n=>{try{return e.call(t,n)}catch(r){throw r.code===12?Fa():r}})(t.getChannelData)},GY={numberOfChannels:1},WY=(t,e,n,r,i,s,o,a)=>{let c=null;return class SP{constructor(u){if(i===null)throw new Error("Missing the native OfflineAudioContext constructor.");const{length:h,numberOfChannels:p,sampleRate:m}={...GY,...u};c===null&&(c=new i(1,1,44100));const g=r!==null&&e(s,s)?new r({length:h,numberOfChannels:p,sampleRate:m}):c.createBuffer(p,h,m);if(g.numberOfChannels===0)throw n();return typeof g.copyFromChannel!="function"?(o(g),oT(g)):e(G_,()=>G_(g))||a(g),t.add(g),g}static[Symbol.hasInstance](u){return u!==null&&typeof u=="object"&&Object.getPrototypeOf(u)===SP.prototype||t.has(u)}}},ns=-34028234663852886e22,Ui=-ns,wc=t=>jf.has(t),jY={buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1},$Y=(t,e,n,r,i,s,o,a)=>class extends t{constructor(l,u){const h=s(l),p={...jY,...u},m=i(h,p),g=o(h),v=g?e():null;super(l,!1,m,v),this._audioBufferSourceNodeRenderer=v,this._isBufferNullified=!1,this._isBufferSet=p.buffer!==null,this._nativeAudioBufferSourceNode=m,this._onended=null,this._playbackRate=n(this,g,m.playbackRate,Ui,ns)}get buffer(){return this._isBufferNullified?null:this._nativeAudioBufferSourceNode.buffer}set buffer(l){if(this._nativeAudioBufferSourceNode.buffer=l,l!==null){if(this._isBufferSet)throw r();this._isBufferSet=!0}}get loop(){return this._nativeAudioBufferSourceNode.loop}set loop(l){this._nativeAudioBufferSourceNode.loop=l}get loopEnd(){return this._nativeAudioBufferSourceNode.loopEnd}set loopEnd(l){this._nativeAudioBufferSourceNode.loopEnd=l}get loopStart(){return this._nativeAudioBufferSourceNode.loopStart}set loopStart(l){this._nativeAudioBufferSourceNode.loopStart=l}get onended(){return this._onended}set onended(l){const u=typeof l=="function"?a(this,l):null;this._nativeAudioBufferSourceNode.onended=u;const h=this._nativeAudioBufferSourceNode.onended;this._onended=h!==null&&h===u?l:h}get playbackRate(){return this._playbackRate}start(l=0,u=0,h){if(this._nativeAudioBufferSourceNode.start(l,u,h),this._audioBufferSourceNodeRenderer!==null&&(this._audioBufferSourceNodeRenderer.start=h===void 0?[l,u]:[l,u,h]),this.context.state!=="closed"){$f(this);const p=()=>{this._nativeAudioBufferSourceNode.removeEventListener("ended",p),wc(this)&&cm(this)};this._nativeAudioBufferSourceNode.addEventListener("ended",p)}}stop(l=0){this._nativeAudioBufferSourceNode.stop(l),this._audioBufferSourceNodeRenderer!==null&&(this._audioBufferSourceNodeRenderer.stop=l)}},qY=(t,e,n,r,i)=>()=>{const s=new WeakMap;let o=null,a=null;const c=async(l,u)=>{let h=n(l);const p=Ai(h,u);if(!p){const m={buffer:h.buffer,channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,loop:h.loop,loopEnd:h.loopEnd,loopStart:h.loopStart,playbackRate:h.playbackRate.value};h=e(u,m),o!==null&&h.start(...o),a!==null&&h.stop(a)}return s.set(u,h),p?await t(u,l.playbackRate,h.playbackRate):await r(u,l.playbackRate,h.playbackRate),await i(l,u,h),h};return{set start(l){o=l},set stop(l){a=l},render(l,u){const h=s.get(u);return h!==void 0?Promise.resolve(h):c(l,u)}}},XY=t=>"playbackRate"in t,KY=t=>"frequency"in t&&"gain"in t,YY=t=>"offset"in t,ZY=t=>!("frequency"in t)&&"gain"in t,JY=t=>"detune"in t&&"frequency"in t&&!("gain"in t),QY=t=>"pan"in t,zi=t=>Lo(mP,t),lm=t=>Lo(gP,t),rw=(t,e)=>{const{activeInputs:n}=zi(t);n.forEach(i=>i.forEach(([s])=>{e.includes(t)||rw(s,[...e,t])}));const r=XY(t)?[t.playbackRate]:xP(t)?Array.from(t.parameters.values()):KY(t)?[t.Q,t.detune,t.frequency,t.gain]:YY(t)?[t.offset]:ZY(t)?[t.gain]:JY(t)?[t.detune,t.frequency]:QY(t)?[t.pan]:[];for(const i of r){const s=lm(i);s!==void 0&&s.activeInputs.forEach(([o])=>rw(o,e))}wc(t)&&cm(t)},EP=t=>{rw(t.destination,[])},eZ=t=>t===void 0||typeof t=="number"||typeof t=="string"&&(t==="balanced"||t==="interactive"||t==="playback"),tZ=(t,e,n,r,i,s,o,a,c)=>class extends t{constructor(u={}){if(c===null)throw new Error("Missing the native AudioContext constructor.");let h;try{h=new c(u)}catch(g){throw g.code===12&&g.message==="sampleRate is not in range"?n():g}if(h===null)throw r();if(!eZ(u.latencyHint))throw new TypeError(`The provided value '${u.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(u.sampleRate!==void 0&&h.sampleRate!==u.sampleRate)throw n();super(h,2);const{latencyHint:p}=u,{sampleRate:m}=h;if(this._baseLatency=typeof h.baseLatency=="number"?h.baseLatency:p==="balanced"?512/m:p==="interactive"||p===void 0?256/m:p==="playback"?1024/m:Math.max(2,Math.min(128,Math.round(p*m/128)))*128/m,this._nativeAudioContext=h,c.name==="webkitAudioContext"?(this._nativeGainNode=h.createGain(),this._nativeOscillatorNode=h.createOscillator(),this._nativeGainNode.gain.value=1e-37,this._nativeOscillatorNode.connect(this._nativeGainNode).connect(h.destination),this._nativeOscillatorNode.start()):(this._nativeGainNode=null,this._nativeOscillatorNode=null),this._state=null,h.state==="running"){this._state="suspended";const g=()=>{this._state==="suspended"&&(this._state=null),h.removeEventListener("statechange",g)};h.addEventListener("statechange",g)}}get baseLatency(){return this._baseLatency}get state(){return this._state!==null?this._state:this._nativeAudioContext.state}close(){return this.state==="closed"?this._nativeAudioContext.close().then(()=>{throw e()}):(this._state==="suspended"&&(this._state=null),this._nativeAudioContext.close().then(()=>{this._nativeGainNode!==null&&this._nativeOscillatorNode!==null&&(this._nativeOscillatorNode.stop(),this._nativeGainNode.disconnect(),this._nativeOscillatorNode.disconnect()),EP(this)}))}createMediaElementSource(u){return new i(this,{mediaElement:u})}createMediaStreamDestination(){return new s(this)}createMediaStreamSource(u){return new o(this,{mediaStream:u})}createMediaStreamTrackSource(u){return new a(this,{mediaStreamTrack:u})}resume(){return this._state==="suspended"?new Promise((u,h)=>{const p=()=>{this._nativeAudioContext.removeEventListener("statechange",p),this._nativeAudioContext.state==="running"?u():this.resume().then(u,h)};this._nativeAudioContext.addEventListener("statechange",p)}):this._nativeAudioContext.resume().catch(u=>{throw u===void 0||u.code===15?e():u})}suspend(){return this._nativeAudioContext.suspend().catch(u=>{throw u===void 0?e():u})}},nZ=(t,e,n,r,i,s,o,a)=>class extends t{constructor(l,u){const h=s(l),p=o(h),m=i(h,u,p),g=p?e(a):null;super(l,!1,m,g),this._isNodeOfNativeOfflineAudioContext=p,this._nativeAudioDestinationNode=m}get channelCount(){return this._nativeAudioDestinationNode.channelCount}set channelCount(l){if(this._isNodeOfNativeOfflineAudioContext)throw r();if(l>this._nativeAudioDestinationNode.maxChannelCount)throw n();this._nativeAudioDestinationNode.channelCount=l}get channelCountMode(){return this._nativeAudioDestinationNode.channelCountMode}set channelCountMode(l){if(this._isNodeOfNativeOfflineAudioContext)throw r();this._nativeAudioDestinationNode.channelCountMode=l}get maxChannelCount(){return this._nativeAudioDestinationNode.maxChannelCount}},rZ=t=>{const e=new WeakMap,n=async(r,i)=>{const s=i.destination;return e.set(i,s),await t(r,i,s),s};return{render(r,i){const s=e.get(i);return s!==void 0?Promise.resolve(s):n(r,i)}}},iZ=(t,e,n,r,i,s,o,a)=>(c,l)=>{const u=l.listener,h=()=>{const N=new Float32Array(1),R=e(l,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:9}),M=o(l);let O=!1,C=[0,0,-1,0,1,0],I=[0,0,0];const U=()=>{if(O)return;O=!0;const H=r(l,256,9,0);H.onaudioprocess=({inputBuffer:V})=>{const B=[s(V,N,0),s(V,N,1),s(V,N,2),s(V,N,3),s(V,N,4),s(V,N,5)];B.some((W,K)=>W!==C[K])&&(u.setOrientation(...B),C=B);const z=[s(V,N,6),s(V,N,7),s(V,N,8)];z.some((W,K)=>W!==I[K])&&(u.setPosition(...z),I=z)},R.connect(H)},L=H=>V=>{V!==C[H]&&(C[H]=V,u.setOrientation(...C))},P=H=>V=>{V!==I[H]&&(I[H]=V,u.setPosition(...I))},T=(H,V,B)=>{const z=n(l,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:V});z.connect(R,0,H),z.start(),Object.defineProperty(z.offset,"defaultValue",{get(){return V}});const W=t({context:c},M,z.offset,Ui,ns);return a(W,"value",K=>()=>K.call(W),K=>j=>{try{K.call(W,j)}catch(Y){if(Y.code!==9)throw Y}U(),M&&B(j)}),W.cancelAndHoldAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.cancelAndHoldAtTime),W.cancelScheduledValues=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.cancelScheduledValues),W.exponentialRampToValueAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.exponentialRampToValueAtTime),W.linearRampToValueAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.linearRampToValueAtTime),W.setTargetAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.setTargetAtTime),W.setValueAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.setValueAtTime),W.setValueCurveAtTime=(K=>M?()=>{throw i()}:(...j)=>{const Y=K.apply(W,j);return U(),Y})(W.setValueCurveAtTime),W};return{forwardX:T(0,0,L(0)),forwardY:T(1,0,L(1)),forwardZ:T(2,-1,L(2)),positionX:T(6,0,P(0)),positionY:T(7,0,P(1)),positionZ:T(8,0,P(2)),upX:T(3,0,L(3)),upY:T(4,1,L(4)),upZ:T(5,0,L(5))}},{forwardX:p,forwardY:m,forwardZ:g,positionX:v,positionY:y,positionZ:_,upX:S,upY:E,upZ:b}=u.forwardX===void 0?h():u;return{get forwardX(){return p},get forwardY(){return m},get forwardZ(){return g},get positionX(){return v},get positionY(){return y},get positionZ(){return _},get upX(){return S},get upY(){return E},get upZ(){return b}}},W_=t=>"context"in t,um=t=>W_(t[0]),dh=(t,e,n,r)=>{for(const i of t)if(n(i)){if(r)return!1;throw Error("The set contains at least one similar element.")}return t.add(e),!0},oN=(t,e,[n,r],i)=>{dh(t,[e,n,r],s=>s[0]===e&&s[1]===n,i)},aN=(t,[e,n,r],i)=>{const s=t.get(e);s===void 0?t.set(e,new Set([[n,r]])):dh(s,[n,r],o=>o[0]===n,i)},fd=t=>"inputs"in t,j_=(t,e,n,r)=>{if(fd(e)){const i=e.inputs[r];return t.connect(i,n,0),[i,n,0]}return t.connect(e,n,r),[e,n,r]},wP=(t,e,n)=>{for(const r of t)if(r[0]===e&&r[1]===n)return t.delete(r),r;return null},sZ=(t,e,n)=>ry(t,r=>r[0]===e&&r[1]===n),bP=(t,e)=>{if(!am(t).delete(e))throw new Error("Missing the expected event listener.")},TP=(t,e,n)=>{const r=Lo(t,e),i=ry(r,s=>s[0]===n);return r.size===0&&t.delete(e),i},$_=(t,e,n,r)=>{fd(e)?t.disconnect(e.inputs[r],n,0):t.disconnect(e,n,r)},Gn=t=>Lo(iT,t),Np=t=>Lo(sT,t),Ku=t=>QE.has(t),u_=t=>!jf.has(t),cN=(t,e)=>new Promise(n=>{if(e!==null)n(!0);else{const r=t.createScriptProcessor(256,1,1),i=t.createGain(),s=t.createBuffer(1,2,44100),o=s.getChannelData(0);o[0]=1,o[1]=1;const a=t.createBufferSource();a.buffer=s,a.loop=!0,a.connect(r).connect(t.destination),a.connect(i),a.disconnect(i),r.onaudioprocess=c=>{const l=c.inputBuffer.getChannelData(0);Array.prototype.some.call(l,u=>u===1)?n(!0):n(!1),a.stop(),r.onaudioprocess=null,a.disconnect(r),r.disconnect(t.destination)},a.start()}}),Q1=(t,e)=>{const n=new Map;for(const r of t)for(const i of r){const s=n.get(i);n.set(i,s===void 0?1:s+1)}n.forEach((r,i)=>e(i,r))},q_=t=>"context"in t,oZ=t=>{const e=new Map;t.connect=(n=>(r,i=0,s=0)=>{const o=q_(r)?n(r,i,s):n(r,i),a=e.get(r);return a===void 0?e.set(r,[{input:s,output:i}]):a.every(c=>c.input!==s||c.output!==i)&&a.push({input:s,output:i}),o})(t.connect.bind(t)),t.disconnect=(n=>(r,i,s)=>{if(n.apply(t),r===void 0)e.clear();else if(typeof r=="number")for(const[o,a]of e){const c=a.filter(l=>l.output!==r);c.length===0?e.delete(o):e.set(o,c)}else if(e.has(r))if(i===void 0)e.delete(r);else{const o=e.get(r);if(o!==void 0){const a=o.filter(c=>c.output!==i&&(c.input!==s||s===void 0));a.length===0?e.delete(r):e.set(r,a)}}for(const[o,a]of e)a.forEach(c=>{q_(o)?t.connect(o,c.output,c.input):t.connect(o,c.output)})})(t.disconnect)},aZ=(t,e,n,r)=>{const{activeInputs:i,passiveInputs:s}=lm(e),{outputs:o}=zi(t),a=am(t),c=l=>{const u=Gn(t),h=Np(e);if(l){const p=TP(s,t,n);oN(i,t,p,!1),!r&&!Ku(t)&&u.connect(h,n)}else{const p=sZ(i,t,n);aN(s,p,!1),!r&&!Ku(t)&&u.disconnect(h,n)}};return dh(o,[e,n],l=>l[0]===e&&l[1]===n,!0)?(a.add(c),wc(t)?oN(i,t,[n,c],!0):aN(s,[t,n,c],!0),!0):!1},cZ=(t,e,n,r)=>{const{activeInputs:i,passiveInputs:s}=zi(e),o=wP(i[r],t,n);return o===null?[yP(s,t,n,r)[2],!1]:[o[2],!0]},lZ=(t,e,n)=>{const{activeInputs:r,passiveInputs:i}=lm(e),s=wP(r,t,n);return s===null?[TP(i,t,n)[1],!1]:[s[2],!0]},aT=(t,e,n,r,i)=>{const[s,o]=cZ(t,n,r,i);if(s!==null&&(bP(t,s),o&&!e&&!Ku(t)&&$_(Gn(t),Gn(n),r,i)),wc(n)){const{activeInputs:a}=zi(n);nw(n,a)}},cT=(t,e,n,r)=>{const[i,s]=lZ(t,n,r);i!==null&&(bP(t,i),s&&!e&&!Ku(t)&&Gn(t).disconnect(Np(n),r))},uZ=(t,e)=>{const n=zi(t),r=[];for(const i of n.outputs)um(i)?aT(t,e,...i):cT(t,e,...i),r.push(i[0]);return n.outputs.clear(),r},hZ=(t,e,n)=>{const r=zi(t),i=[];for(const s of r.outputs)s[1]===n&&(um(s)?aT(t,e,...s):cT(t,e,...s),i.push(s[0]),r.outputs.delete(s));return i},fZ=(t,e,n,r,i)=>{const s=zi(t);return Array.from(s.outputs).filter(o=>o[0]===n&&(r===void 0||o[1]===r)&&(i===void 0||o[2]===i)).map(o=>(um(o)?aT(t,e,...o):cT(t,e,...o),s.outputs.delete(o),o[0]))},dZ=(t,e,n,r,i,s,o,a,c,l,u,h,p,m,g,v)=>class extends l{constructor(_,S,E,b){super(E),this._context=_,this._nativeAudioNode=E;const N=u(_);h(N)&&n(cN,()=>cN(N,v))!==!0&&oZ(E),iT.set(this,E),_P.set(this,new Set),_.state!=="closed"&&S&&$f(this),t(this,b,E)}get channelCount(){return this._nativeAudioNode.channelCount}set channelCount(_){this._nativeAudioNode.channelCount=_}get channelCountMode(){return this._nativeAudioNode.channelCountMode}set channelCountMode(_){this._nativeAudioNode.channelCountMode=_}get channelInterpretation(){return this._nativeAudioNode.channelInterpretation}set channelInterpretation(_){this._nativeAudioNode.channelInterpretation=_}get context(){return this._context}get numberOfInputs(){return this._nativeAudioNode.numberOfInputs}get numberOfOutputs(){return this._nativeAudioNode.numberOfOutputs}connect(_,S=0,E=0){if(S<0||S>=this._nativeAudioNode.numberOfOutputs)throw i();const b=u(this._context),N=g(b);if(p(_)||m(_))throw s();if(W_(_)){const O=Gn(_);try{const I=j_(this._nativeAudioNode,O,S,E),U=u_(this);(N||U)&&this._nativeAudioNode.disconnect(...I),this.context.state!=="closed"&&!U&&u_(_)&&$f(_)}catch(I){throw I.code===12?s():I}if(e(this,_,S,E,N)){const I=c([this],_);Q1(I,r(N))}return _}const R=Np(_);if(R.name==="playbackRate"&&R.maxValue===1024)throw o();try{this._nativeAudioNode.connect(R,S),(N||u_(this))&&this._nativeAudioNode.disconnect(R,S)}catch(O){throw O.code===12?s():O}if(aZ(this,_,S,N)){const O=c([this],_);Q1(O,r(N))}}disconnect(_,S,E){let b;const N=u(this._context),R=g(N);if(_===void 0)b=uZ(this,R);else if(typeof _=="number"){if(_<0||_>=this.numberOfOutputs)throw i();b=hZ(this,R,_)}else{if(S!==void 0&&(S<0||S>=this.numberOfOutputs)||W_(_)&&E!==void 0&&(E<0||E>=_.numberOfInputs))throw i();if(b=fZ(this,R,_,S,E),b.length===0)throw s()}for(const M of b){const O=c([this],M);Q1(O,a)}}},pZ=(t,e,n,r,i,s,o,a,c,l,u,h,p)=>(m,g,v,y=null,_=null)=>{const S=v.value,E=new bY(S),b=g?r(E):null,N={get defaultValue(){return S},get maxValue(){return y===null?v.maxValue:y},get minValue(){return _===null?v.minValue:_},get value(){return v.value},set value(R){v.value=R,N.setValueAtTime(R,m.context.currentTime)},cancelAndHoldAtTime(R){if(typeof v.cancelAndHoldAtTime=="function")b===null&&E.flush(m.context.currentTime),E.add(i(R)),v.cancelAndHoldAtTime(R);else{const M=Array.from(E).pop();b===null&&E.flush(m.context.currentTime),E.add(i(R));const O=Array.from(E).pop();v.cancelScheduledValues(R),M!==O&&O!==void 0&&(O.type==="exponentialRampToValue"?v.exponentialRampToValueAtTime(O.value,O.endTime):O.type==="linearRampToValue"?v.linearRampToValueAtTime(O.value,O.endTime):O.type==="setValue"?v.setValueAtTime(O.value,O.startTime):O.type==="setValueCurve"&&v.setValueCurveAtTime(O.values,O.startTime,O.duration))}return N},cancelScheduledValues(R){return b===null&&E.flush(m.context.currentTime),E.add(s(R)),v.cancelScheduledValues(R),N},exponentialRampToValueAtTime(R,M){if(R===0)throw new RangeError;if(!Number.isFinite(M)||M<0)throw new RangeError;const O=m.context.currentTime;return b===null&&E.flush(O),Array.from(E).length===0&&(E.add(l(S,O)),v.setValueAtTime(S,O)),E.add(o(R,M)),v.exponentialRampToValueAtTime(R,M),N},linearRampToValueAtTime(R,M){const O=m.context.currentTime;return b===null&&E.flush(O),Array.from(E).length===0&&(E.add(l(S,O)),v.setValueAtTime(S,O)),E.add(a(R,M)),v.linearRampToValueAtTime(R,M),N},setTargetAtTime(R,M,O){return b===null&&E.flush(m.context.currentTime),E.add(c(R,M,O)),v.setTargetAtTime(R,M,O),N},setValueAtTime(R,M){return b===null&&E.flush(m.context.currentTime),E.add(l(R,M)),v.setValueAtTime(R,M),N},setValueCurveAtTime(R,M,O){const C=R instanceof Float32Array?R:new Float32Array(R);if(h!==null&&h.name==="webkitAudioContext"){const I=M+O,U=m.context.sampleRate,L=Math.ceil(M*U),P=Math.floor(I*U),T=P-L,H=new Float32Array(T);for(let B=0;B({replay(e){for(const n of t)if(n.type==="exponentialRampToValue"){const{endTime:r,value:i}=n;e.exponentialRampToValueAtTime(i,r)}else if(n.type==="linearRampToValue"){const{endTime:r,value:i}=n;e.linearRampToValueAtTime(i,r)}else if(n.type==="setTarget"){const{startTime:r,target:i,timeConstant:s}=n;e.setTargetAtTime(i,r,s)}else if(n.type==="setValue"){const{startTime:r,value:i}=n;e.setValueAtTime(i,r)}else if(n.type==="setValueCurve"){const{duration:r,startTime:i,values:s}=n;e.setValueCurveAtTime(s,i,r)}else throw new Error("Can't apply an unknown automation.")}});class AP{constructor(e){this._map=new Map(e)}get size(){return this._map.size}entries(){return this._map.entries()}forEach(e,n=null){return this._map.forEach((r,i)=>e.call(n,r,i,this))}get(e){return this._map.get(e)}has(e){return this._map.has(e)}keys(){return this._map.keys()}values(){return this._map.values()}}const gZ={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,parameterData:{},processorOptions:{}},_Z=(t,e,n,r,i,s,o,a,c,l,u,h,p,m)=>class extends e{constructor(v,y,_){var S;const E=a(v),b=c(E),N=u({...gZ,..._});p(N);const R=ew.get(E),M=R==null?void 0:R.get(y),O=b||E.state!=="closed"?E:(S=o(E))!==null&&S!==void 0?S:E,C=i(O,b?null:v.baseLatency,l,y,M,N),I=b?r(y,N,M):null;super(v,!0,C,I);const U=[];C.parameters.forEach((P,T)=>{const H=n(this,b,P);U.push([T,H])}),this._nativeAudioWorkletNode=C,this._onprocessorerror=null,this._parameters=new AP(U),b&&t(E,this);const{activeInputs:L}=s(this);h(C,L)}get onprocessorerror(){return this._onprocessorerror}set onprocessorerror(v){const y=typeof v=="function"?m(this,v):null;this._nativeAudioWorkletNode.onprocessorerror=y;const _=this._nativeAudioWorkletNode.onprocessorerror;this._onprocessorerror=_!==null&&_===y?v:_}get parameters(){return this._parameters===null?this._nativeAudioWorkletNode.parameters:this._parameters}get port(){return this._nativeAudioWorkletNode.port}};function X_(t,e,n,r,i){if(typeof t.copyFromChannel=="function")e[n].byteLength===0&&(e[n]=new Float32Array(128)),t.copyFromChannel(e[n],r,i);else{const s=t.getChannelData(r);if(e[n].byteLength===0)e[n]=s.slice(i,i+128);else{const o=new Float32Array(s.buffer,i*Float32Array.BYTES_PER_ELEMENT,128);e[n].set(o)}}}const MP=(t,e,n,r,i)=>{typeof t.copyToChannel=="function"?e[n].byteLength!==0&&t.copyToChannel(e[n],r,i):e[n].byteLength!==0&&t.getChannelData(r).set(e[n],i)},K_=(t,e)=>{const n=[];for(let r=0;r{const n=Lo(tw,t),r=Gn(e);return Lo(n,r)},yZ=async(t,e,n,r,i,s,o)=>{const a=e===null?Math.ceil(t.context.length/128)*128:e.length,c=r.channelCount*r.numberOfInputs,l=i.reduce((y,_)=>y+_,0),u=l===0?null:n.createBuffer(l,a,n.sampleRate);if(s===void 0)throw new Error("Missing the processor constructor.");const h=zi(t),p=await vZ(n,t),m=K_(r.numberOfInputs,r.channelCount),g=K_(r.numberOfOutputs,i),v=Array.from(t.parameters.keys()).reduce((y,_)=>({...y,[_]:new Float32Array(128)}),{});for(let y=0;y0&&e!==null)for(let _=0;_{X_(e,v,_,c+S,y)});for(let _=0;_h.activeInputs[b].size===0?[]:E),S=o(y/n.sampleRate,n.sampleRate,()=>p.process(_,g,v));if(u!==null)for(let E=0,b=0;E(y,_,S)=>{const E=new WeakMap;let b=null;const N=async(R,M)=>{let O=u(R),C=null;const I=Ai(O,M),U=Array.isArray(_.outputChannelCount)?_.outputChannelCount:Array.from(_.outputChannelCount);if(h===null){const L=U.reduce((V,B)=>V+B,0),P=i(M,{channelCount:Math.max(1,L),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,L)}),T=[];for(let V=0;V{const j=new p(W,Math.ceil(R.context.length/128)*128,M.sampleRate),Y=[],ge=[];for(let we=0;we<_.numberOfInputs;we+=1)Y.push(o(j,{channelCount:_.channelCount,channelCountMode:_.channelCountMode,channelInterpretation:_.channelInterpretation,gain:1})),ge.push(i(j,{channelCount:_.channelCount,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:_.channelCount}));const Q=await Promise.all(Array.from(R.parameters.values()).map(async we=>{const Ae=s(j,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:we.value});return await m(j,we,Ae.offset),Ae})),re=r(j,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,B+z)});for(let we=0;we<_.numberOfInputs;we+=1){Y[we].connect(ge[we]);for(let Ae=0;Ae<_.channelCount;Ae+=1)ge[we].connect(re,Ae,we*_.channelCount+Ae)}for(const[we,Ae]of Q.entries())Ae.connect(re,0,B+we),Ae.start(0);return re.connect(j.destination),await Promise.all(Y.map(we=>g(R,j,we))),v(j)})(),M,_,U,S,l)}const L=await b,P=n(M,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),[T,H,V]=C;L!==null&&(P.buffer=L,P.start(0)),P.connect(T);for(let B=0,z=0;Bclass extends g{constructor(N,R){super(N,R),this._nativeContext=N,this._audioWorklet=t===void 0?void 0:{addModule:(M,O)=>t(this,M,O)}}get audioWorklet(){return this._audioWorklet}createAnalyser(){return new e(this)}createBiquadFilter(){return new i(this)}createBuffer(N,R,M){return new n({length:R,numberOfChannels:N,sampleRate:M})}createBufferSource(){return new r(this)}createChannelMerger(N=6){return new s(this,{numberOfInputs:N})}createChannelSplitter(N=6){return new o(this,{numberOfOutputs:N})}createConstantSource(){return new a(this)}createConvolver(){return new c(this)}createDelay(N=1){return new u(this,{maxDelayTime:N})}createDynamicsCompressor(){return new h(this)}createGain(){return new p(this)}createIIRFilter(N,R){return new m(this,{feedback:R,feedforward:N})}createOscillator(){return new v(this)}createPanner(){return new y(this)}createPeriodicWave(N,R,M={disableNormalization:!1}){return new _(this,{...M,imag:R,real:N})}createStereoPanner(){return new S(this)}createWaveShaper(){return new E(this)}decodeAudioData(N,R,M){return l(this._nativeContext,N).then(O=>(typeof R=="function"&&R(O),O),O=>{throw typeof M=="function"&&M(O),O})}},EZ={Q:1,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:350,gain:0,type:"lowpass"},wZ=(t,e,n,r,i,s,o,a)=>class extends t{constructor(l,u){const h=s(l),p={...EZ,...u},m=i(h,p),g=o(h),v=g?n():null;super(l,!1,m,v),this._Q=e(this,g,m.Q,Ui,ns),this._detune=e(this,g,m.detune,1200*Math.log2(Ui),-1200*Math.log2(Ui)),this._frequency=e(this,g,m.frequency,l.sampleRate/2,0),this._gain=e(this,g,m.gain,40*Math.log10(Ui),ns),this._nativeBiquadFilterNode=m,a(this,1)}get detune(){return this._detune}get frequency(){return this._frequency}get gain(){return this._gain}get Q(){return this._Q}get type(){return this._nativeBiquadFilterNode.type}set type(l){this._nativeBiquadFilterNode.type=l}getFrequencyResponse(l,u,h){try{this._nativeBiquadFilterNode.getFrequencyResponse(l,u,h)}catch(p){throw p.code===11?r():p}if(l.length!==u.length||u.length!==h.length)throw r()}},bZ=(t,e,n,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=n(a);const u=Ai(l,c);if(!u){const h={Q:l.Q.value,channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,detune:l.detune.value,frequency:l.frequency.value,gain:l.gain.value,type:l.type};l=e(c,h)}return s.set(c,l),u?(await t(c,a.Q,l.Q),await t(c,a.detune,l.detune),await t(c,a.frequency,l.frequency),await t(c,a.gain,l.gain)):(await r(c,a.Q,l.Q),await r(c,a.detune,l.detune),await r(c,a.frequency,l.frequency),await r(c,a.gain,l.gain)),await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},TZ=(t,e)=>(n,r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t.get(n);if(s!==void 0)return s;try{const o=r();return o instanceof Promise?(t.set(n,o),o.catch(()=>!1).then(a=>(t.delete(n),e.set(n,a),a))):(e.set(n,o),o)}catch{return e.set(n,!1),!1}},AZ={channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6},MZ=(t,e,n,r,i)=>class extends t{constructor(o,a){const c=r(o),l={...AZ,...a},u=n(c,l),h=i(c)?e():null;super(o,!1,u,h)}},CZ=(t,e,n)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!Ai(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,numberOfInputs:a.numberOfInputs};a=t(o,l)}return r.set(o,a),await n(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},RZ={channelCount:6,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:6},NZ=(t,e,n,r,i,s)=>class extends t{constructor(a,c){const l=r(a),u=s({...RZ,...c}),h=n(l,u),p=i(l)?e():null;super(a,!1,h,p)}},kZ=(t,e,n)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!Ai(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,numberOfOutputs:a.numberOfOutputs};a=t(o,l)}return r.set(o,a),await n(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},IZ=t=>(e,n,r)=>t(n,e,r),OZ=t=>(e,n,r=0,i=0)=>{const s=e[r];if(s===void 0)throw t();return q_(n)?s.connect(n,0,i):s.connect(n,0)},LZ=t=>(e,n)=>{const r=t(e,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),i=e.createBuffer(1,2,44100);return r.buffer=i,r.loop=!0,r.connect(n),r.start(),()=>{r.stop(),r.disconnect(n)}},PZ={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",offset:1},DZ=(t,e,n,r,i,s,o)=>class extends t{constructor(c,l){const u=i(c),h={...PZ,...l},p=r(u,h),m=s(u),g=m?n():null;super(c,!1,p,g),this._constantSourceNodeRenderer=g,this._nativeConstantSourceNode=p,this._offset=e(this,m,p.offset,Ui,ns),this._onended=null}get offset(){return this._offset}get onended(){return this._onended}set onended(c){const l=typeof c=="function"?o(this,c):null;this._nativeConstantSourceNode.onended=l;const u=this._nativeConstantSourceNode.onended;this._onended=u!==null&&u===l?c:u}start(c=0){if(this._nativeConstantSourceNode.start(c),this._constantSourceNodeRenderer!==null&&(this._constantSourceNodeRenderer.start=c),this.context.state!=="closed"){$f(this);const l=()=>{this._nativeConstantSourceNode.removeEventListener("ended",l),wc(this)&&cm(this)};this._nativeConstantSourceNode.addEventListener("ended",l)}}stop(c=0){this._nativeConstantSourceNode.stop(c),this._constantSourceNodeRenderer!==null&&(this._constantSourceNodeRenderer.stop=c)}},UZ=(t,e,n,r,i)=>()=>{const s=new WeakMap;let o=null,a=null;const c=async(l,u)=>{let h=n(l);const p=Ai(h,u);if(!p){const m={channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,offset:h.offset.value};h=e(u,m),o!==null&&h.start(o),a!==null&&h.stop(a)}return s.set(u,h),p?await t(u,l.offset,h.offset):await r(u,l.offset,h.offset),await i(l,u,h),h};return{set start(l){o=l},set stop(l){a=l},render(l,u){const h=s.get(u);return h!==void 0?Promise.resolve(h):c(l,u)}}},FZ=t=>e=>(t[0]=e,t[0]),BZ={buffer:null,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",disableNormalization:!1},zZ=(t,e,n,r,i,s)=>class extends t{constructor(a,c){const l=r(a),u={...BZ,...c},h=n(l,u),m=i(l)?e():null;super(a,!1,h,m),this._isBufferNullified=!1,this._nativeConvolverNode=h,u.buffer!==null&&s(this,u.buffer.duration)}get buffer(){return this._isBufferNullified?null:this._nativeConvolverNode.buffer}set buffer(a){if(this._nativeConvolverNode.buffer=a,a===null&&this._nativeConvolverNode.buffer!==null){const c=this._nativeConvolverNode.context;this._nativeConvolverNode.buffer=c.createBuffer(1,1,c.sampleRate),this._isBufferNullified=!0,s(this,0)}else this._isBufferNullified=!1,s(this,this._nativeConvolverNode.buffer===null?0:this._nativeConvolverNode.buffer.duration)}get normalize(){return this._nativeConvolverNode.normalize}set normalize(a){this._nativeConvolverNode.normalize=a}},VZ=(t,e,n)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!Ai(a,o)){const l={buffer:a.buffer,channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,disableNormalization:!a.normalize};a=t(o,l)}return r.set(o,a),fd(a)?await n(s,o,a.inputs[0]):await n(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},HZ=(t,e)=>(n,r,i)=>{if(e===null)throw new Error("Missing the native OfflineAudioContext constructor.");try{return new e(n,r,i)}catch(s){throw s.name==="SyntaxError"?t():s}},GZ=()=>new DOMException("","DataCloneError"),lN=t=>{const{port1:e,port2:n}=new MessageChannel;return new Promise(r=>{const i=()=>{n.onmessage=null,e.close(),n.close(),r()};n.onmessage=()=>i();try{e.postMessage(t,[t])}catch{}finally{i()}})},WZ=(t,e,n,r,i,s,o,a,c,l,u)=>(h,p)=>{const m=o(h)?h:s(h);if(i.has(p)){const g=n();return Promise.reject(g)}try{i.add(p)}catch{}return e(c,()=>c(m))?m.decodeAudioData(p).then(g=>(lN(p).catch(()=>{}),e(a,()=>a(g))||u(g),t.add(g),g)):new Promise((g,v)=>{const y=async()=>{try{await lN(p)}catch{}},_=S=>{v(S),y()};try{m.decodeAudioData(p,S=>{typeof S.copyFromChannel!="function"&&(l(S),oT(S)),t.add(S),y().then(()=>g(S))},S=>{_(S===null?r():S)})}catch(S){_(S)}})},jZ=(t,e,n,r,i,s,o,a)=>(c,l)=>{const u=e.get(c);if(u===void 0)throw new Error("Missing the expected cycle count.");const h=s(c.context),p=a(h);if(u===l){if(e.delete(c),!p&&o(c)){const m=r(c),{outputs:g}=n(c);for(const v of g)if(um(v)){const y=r(v[0]);t(m,y,v[1],v[2])}else{const y=i(v[0]);m.connect(y,v[1])}}}else e.set(c,u-l)},$Z={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",delayTime:0,maxDelayTime:1},qZ=(t,e,n,r,i,s,o)=>class extends t{constructor(c,l){const u=i(c),h={...$Z,...l},p=r(u,h),m=s(u),g=m?n(h.maxDelayTime):null;super(c,!1,p,g),this._delayTime=e(this,m,p.delayTime),o(this,h.maxDelayTime)}get delayTime(){return this._delayTime}},XZ=(t,e,n,r,i)=>s=>{const o=new WeakMap,a=async(c,l)=>{let u=n(c);const h=Ai(u,l);if(!h){const p={channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,delayTime:u.delayTime.value,maxDelayTime:s};u=e(l,p)}return o.set(l,u),h?await t(l,c.delayTime,u.delayTime):await r(l,c.delayTime,u.delayTime),await i(c,l,u),u};return{render(c,l){const u=o.get(l);return u!==void 0?Promise.resolve(u):a(c,l)}}},KZ=t=>(e,n,r,i)=>t(e[i],s=>s[0]===n&&s[1]===r),YZ=t=>(e,n)=>{t(e).delete(n)},ZZ=t=>"delayTime"in t,JZ=(t,e,n)=>function r(i,s){const o=W_(s)?s:n(t,s);if(ZZ(o))return[];if(i[0]===o)return[i];if(i.includes(o))return[];const{outputs:a}=e(o);return Array.from(a).map(c=>r([...i,o],c[0])).reduce((c,l)=>c.concat(l),[])},S0=(t,e,n)=>{const r=e[n];if(r===void 0)throw t();return r},QZ=t=>(e,n=void 0,r=void 0,i=0)=>n===void 0?e.forEach(s=>s.disconnect()):typeof n=="number"?S0(t,e,n).disconnect():q_(n)?r===void 0?e.forEach(s=>s.disconnect(n)):i===void 0?S0(t,e,r).disconnect(n,0):S0(t,e,r).disconnect(n,0,i):r===void 0?e.forEach(s=>s.disconnect(n)):S0(t,e,r).disconnect(n,0),eJ={attack:.003,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",knee:30,ratio:12,release:.25,threshold:-24},tJ=(t,e,n,r,i,s,o,a)=>class extends t{constructor(l,u){const h=s(l),p={...eJ,...u},m=r(h,p),g=o(h),v=g?n():null;super(l,!1,m,v),this._attack=e(this,g,m.attack),this._knee=e(this,g,m.knee),this._nativeDynamicsCompressorNode=m,this._ratio=e(this,g,m.ratio),this._release=e(this,g,m.release),this._threshold=e(this,g,m.threshold),a(this,.006)}get attack(){return this._attack}get channelCount(){return this._nativeDynamicsCompressorNode.channelCount}set channelCount(l){const u=this._nativeDynamicsCompressorNode.channelCount;if(this._nativeDynamicsCompressorNode.channelCount=l,l>2)throw this._nativeDynamicsCompressorNode.channelCount=u,i()}get channelCountMode(){return this._nativeDynamicsCompressorNode.channelCountMode}set channelCountMode(l){const u=this._nativeDynamicsCompressorNode.channelCountMode;if(this._nativeDynamicsCompressorNode.channelCountMode=l,l==="max")throw this._nativeDynamicsCompressorNode.channelCountMode=u,i()}get knee(){return this._knee}get ratio(){return this._ratio}get reduction(){return typeof this._nativeDynamicsCompressorNode.reduction.value=="number"?this._nativeDynamicsCompressorNode.reduction.value:this._nativeDynamicsCompressorNode.reduction}get release(){return this._release}get threshold(){return this._threshold}},nJ=(t,e,n,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=n(a);const u=Ai(l,c);if(!u){const h={attack:l.attack.value,channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,knee:l.knee.value,ratio:l.ratio.value,release:l.release.value,threshold:l.threshold.value};l=e(c,h)}return s.set(c,l),u?(await t(c,a.attack,l.attack),await t(c,a.knee,l.knee),await t(c,a.ratio,l.ratio),await t(c,a.release,l.release),await t(c,a.threshold,l.threshold)):(await r(c,a.attack,l.attack),await r(c,a.knee,l.knee),await r(c,a.ratio,l.ratio),await r(c,a.release,l.release),await r(c,a.threshold,l.threshold)),await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},rJ=()=>new DOMException("","EncodingError"),iJ=t=>e=>new Promise((n,r)=>{if(t===null){r(new SyntaxError);return}const i=t.document.head;if(i===null)r(new SyntaxError);else{const s=t.document.createElement("script"),o=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(o),c=t.onerror,l=()=>{t.onerror=c,URL.revokeObjectURL(a)};t.onerror=(u,h,p,m,g)=>{if(h===a||h===t.location.href&&p===1&&m===1)return l(),r(g),!1;if(c!==null)return c(u,h,p,m,g)},s.onerror=()=>{l(),r(new SyntaxError)},s.onload=()=>{l(),n()},s.src=a,s.type="module",i.appendChild(s)}}),sJ=t=>class{constructor(n){this._nativeEventTarget=n,this._listeners=new WeakMap}addEventListener(n,r,i){if(r!==null){let s=this._listeners.get(r);s===void 0&&(s=t(this,r),typeof r=="function"&&this._listeners.set(r,s)),this._nativeEventTarget.addEventListener(n,s,i)}}dispatchEvent(n){return this._nativeEventTarget.dispatchEvent(n)}removeEventListener(n,r,i){const s=r===null?void 0:this._listeners.get(r);this._nativeEventTarget.removeEventListener(n,s===void 0?null:s,i)}},oJ=t=>(e,n,r)=>{Object.defineProperties(t,{currentFrame:{configurable:!0,get(){return Math.round(e*n)}},currentTime:{configurable:!0,get(){return e}}});try{return r()}finally{t!==null&&(delete t.currentFrame,delete t.currentTime)}},aJ=t=>async e=>{try{const n=await fetch(e);if(n.ok)return[await n.text(),n.url]}catch{}throw t()},cJ={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",gain:1},lJ=(t,e,n,r,i,s)=>class extends t{constructor(a,c){const l=i(a),u={...cJ,...c},h=r(l,u),p=s(l),m=p?n():null;super(a,!1,h,m),this._gain=e(this,p,h.gain,Ui,ns)}get gain(){return this._gain}},uJ=(t,e,n,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=n(a);const u=Ai(l,c);if(!u){const h={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,gain:l.gain.value};l=e(c,h)}return s.set(c,l),u?await t(c,a.gain,l.gain):await r(c,a.gain,l.gain),await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},hJ=(t,e)=>n=>e(t,n),fJ=t=>e=>{const n=t(e);if(n.renderer===null)throw new Error("Missing the renderer of the given AudioNode in the audio graph.");return n.renderer},dJ=t=>e=>{var n;return(n=t.get(e))!==null&&n!==void 0?n:0},pJ=t=>e=>{const n=t(e);if(n.renderer===null)throw new Error("Missing the renderer of the given AudioParam in the audio graph.");return n.renderer},mJ=t=>e=>t.get(e),si=()=>new DOMException("","InvalidStateError"),gJ=t=>e=>{const n=t.get(e);if(n===void 0)throw si();return n},_J=(t,e)=>n=>{let r=t.get(n);if(r!==void 0)return r;if(e===null)throw new Error("Missing the native OfflineAudioContext constructor.");return r=new e(1,1,44100),t.set(n,r),r},vJ=t=>e=>{const n=t.get(e);if(n===void 0)throw new Error("The context has no set of AudioWorkletNodes.");return n},iy=()=>new DOMException("","InvalidAccessError"),yJ=t=>{t.getFrequencyResponse=(e=>(n,r,i)=>{if(n.length!==r.length||r.length!==i.length)throw iy();return e.call(t,n,r,i)})(t.getFrequencyResponse)},xJ={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers"},SJ=(t,e,n,r,i,s)=>class extends t{constructor(a,c){const l=r(a),u=i(l),h={...xJ,...c},p=e(l,u?null:a.baseLatency,h),m=u?n(h.feedback,h.feedforward):null;super(a,!1,p,m),yJ(p),this._nativeIIRFilterNode=p,s(this,1)}getFrequencyResponse(a,c,l){return this._nativeIIRFilterNode.getFrequencyResponse(a,c,l)}},CP=(t,e,n,r,i,s,o,a,c,l,u)=>{const h=l.length;let p=a;for(let m=0;m{const i=n instanceof Float64Array?n:new Float64Array(n),s=r instanceof Float64Array?r:new Float64Array(r),o=i.length,a=s.length,c=Math.min(o,a);if(i[0]!==1){for(let g=0;g(s,o)=>{const a=new WeakMap;let c=null;const l=async(u,h)=>{let p=null,m=e(u);const g=Ai(m,h);if(h.createIIRFilter===void 0?p=t(h,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}):g||(m=h.createIIRFilter(o,s)),a.set(h,p===null?m:p),p!==null){if(c===null){if(n===null)throw new Error("Missing the native OfflineAudioContext constructor.");const y=new n(u.context.destination.channelCount,u.context.length,h.sampleRate);c=(async()=>{await r(u,y,y.destination);const _=await i(y);return EJ(_,h,s,o)})()}const v=await c;return p.buffer=v,p.start(0),p}return await r(u,h,m),m};return{render(u,h){const p=a.get(h);return p!==void 0?Promise.resolve(p):l(u,h)}}},bJ=(t,e,n,r,i,s)=>o=>(a,c)=>{const l=t.get(a);if(l===void 0){if(!o&&s(a)){const u=r(a),{outputs:h}=n(a);for(const p of h)if(um(p)){const m=r(p[0]);e(u,m,p[1],p[2])}else{const m=i(p[0]);u.disconnect(m,p[1])}}t.set(a,c)}else t.set(a,l+c)},TJ=(t,e)=>n=>{const r=t.get(n);return e(r)||e(n)},AJ=(t,e)=>n=>t.has(n)||e(n),MJ=(t,e)=>n=>t.has(n)||e(n),CJ=(t,e)=>n=>{const r=t.get(n);return e(r)||e(n)},RJ=t=>e=>t!==null&&e instanceof t,NJ=t=>e=>t!==null&&typeof t.AudioNode=="function"&&e instanceof t.AudioNode,kJ=t=>e=>t!==null&&typeof t.AudioParam=="function"&&e instanceof t.AudioParam,IJ=(t,e)=>n=>t(n)||e(n),OJ=t=>e=>t!==null&&e instanceof t,LJ=t=>t!==null&&t.isSecureContext,PJ=(t,e,n,r)=>class extends t{constructor(s,o){const a=n(s),c=e(a,o);if(r(a))throw TypeError();super(s,!0,c,null),this._nativeMediaElementAudioSourceNode=c}get mediaElement(){return this._nativeMediaElementAudioSourceNode.mediaElement}},DJ={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers"},UJ=(t,e,n,r)=>class extends t{constructor(s,o){const a=n(s);if(r(a))throw new TypeError;const c={...DJ,...o},l=e(a,c);super(s,!1,l,null),this._nativeMediaStreamAudioDestinationNode=l}get stream(){return this._nativeMediaStreamAudioDestinationNode.stream}},FJ=(t,e,n,r)=>class extends t{constructor(s,o){const a=n(s),c=e(a,o);if(r(a))throw new TypeError;super(s,!0,c,null),this._nativeMediaStreamAudioSourceNode=c}get mediaStream(){return this._nativeMediaStreamAudioSourceNode.mediaStream}},BJ=(t,e,n)=>class extends t{constructor(i,s){const o=n(i),a=e(o,s);super(i,!0,a,null)}},zJ=(t,e,n,r,i,s)=>class extends n{constructor(a,c){super(a),this._nativeContext=a,ny.set(this,a),r(a)&&i.set(a,new Set),this._destination=new t(this,c),this._listener=e(this,a),this._onstatechange=null}get currentTime(){return this._nativeContext.currentTime}get destination(){return this._destination}get listener(){return this._listener}get onstatechange(){return this._onstatechange}set onstatechange(a){const c=typeof a=="function"?s(this,a):null;this._nativeContext.onstatechange=c;const l=this._nativeContext.onstatechange;this._onstatechange=l!==null&&l===c?a:l}get sampleRate(){return this._nativeContext.sampleRate}get state(){return this._nativeContext.state}},kp=t=>{const e=new Uint32Array([1179011410,40,1163280727,544501094,16,131073,44100,176400,1048580,1635017060,4,0]);try{const n=t.decodeAudioData(e.buffer,()=>{});return n===void 0?!1:(n.catch(()=>{}),!0)}catch{}return!1},VJ=(t,e)=>(n,r,i)=>{const s=new Set;return n.connect=(o=>(a,c=0,l=0)=>{const u=s.size===0;if(e(a))return o.call(n,a,c,l),t(s,[a,c,l],h=>h[0]===a&&h[1]===c&&h[2]===l,!0),u&&r(),a;o.call(n,a,c),t(s,[a,c],h=>h[0]===a&&h[1]===c,!0),u&&r()})(n.connect),n.disconnect=(o=>(a,c,l)=>{const u=s.size>0;if(a===void 0)o.apply(n),s.clear();else if(typeof a=="number"){o.call(n,a);for(const p of s)p[1]===a&&s.delete(p)}else{e(a)?o.call(n,a,c,l):o.call(n,a,c);for(const p of s)p[0]===a&&(c===void 0||p[1]===c)&&(l===void 0||p[2]===l)&&s.delete(p)}const h=s.size===0;u&&h&&i()})(n.disconnect),n},Xn=(t,e,n)=>{const r=e[n];r!==void 0&&r!==t[n]&&(t[n]=r)},Gr=(t,e)=>{Xn(t,e,"channelCount"),Xn(t,e,"channelCountMode"),Xn(t,e,"channelInterpretation")},uN=t=>typeof t.getFloatTimeDomainData=="function",HJ=t=>{t.getFloatTimeDomainData=e=>{const n=new Uint8Array(e.length);t.getByteTimeDomainData(n);const r=Math.max(n.length,t.fftSize);for(let i=0;i(n,r)=>{const i=n.createAnalyser();if(Gr(i,r),!(r.maxDecibels>r.minDecibels))throw e();return Xn(i,r,"fftSize"),Xn(i,r,"maxDecibels"),Xn(i,r,"minDecibels"),Xn(i,r,"smoothingTimeConstant"),t(uN,()=>uN(i))||HJ(i),i},WJ=t=>t===null?null:t.hasOwnProperty("AudioBuffer")?t.AudioBuffer:null,nr=(t,e,n)=>{const r=e[n];r!==void 0&&r!==t[n].value&&(t[n].value=r)},jJ=t=>{t.start=(e=>{let n=!1;return(r=0,i=0,s)=>{if(n)throw si();e.call(t,r,i,s),n=!0}})(t.start)},lT=t=>{t.start=(e=>(n=0,r=0,i)=>{if(typeof i=="number"&&i<0||r<0||n<0)throw new RangeError("The parameters can't be negative.");e.call(t,n,r,i)})(t.start)},uT=t=>{t.stop=(e=>(n=0)=>{if(n<0)throw new RangeError("The parameter can't be negative.");e.call(t,n)})(t.stop)},$J=(t,e,n,r,i,s,o,a,c,l,u)=>(h,p)=>{const m=h.createBufferSource();return Gr(m,p),nr(m,p,"playbackRate"),Xn(m,p,"buffer"),Xn(m,p,"loop"),Xn(m,p,"loopEnd"),Xn(m,p,"loopStart"),e(n,()=>n(h))||jJ(m),e(r,()=>r(h))||c(m),e(i,()=>i(h))||l(m,h),e(s,()=>s(h))||lT(m),e(o,()=>o(h))||u(m,h),e(a,()=>a(h))||uT(m),t(h,m),m},qJ=t=>t===null?null:t.hasOwnProperty("AudioContext")?t.AudioContext:t.hasOwnProperty("webkitAudioContext")?t.webkitAudioContext:null,XJ=(t,e)=>(n,r,i)=>{const s=n.destination;if(s.channelCount!==r)try{s.channelCount=r}catch{}i&&s.channelCountMode!=="explicit"&&(s.channelCountMode="explicit"),s.maxChannelCount===0&&Object.defineProperty(s,"maxChannelCount",{value:r});const o=t(n,{channelCount:r,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,gain:1});return e(o,"channelCount",a=>()=>a.call(o),a=>c=>{a.call(o,c);try{s.channelCount=c}catch(l){if(c>s.maxChannelCount)throw l}}),e(o,"channelCountMode",a=>()=>a.call(o),a=>c=>{a.call(o,c),s.channelCountMode=c}),e(o,"channelInterpretation",a=>()=>a.call(o),a=>c=>{a.call(o,c),s.channelInterpretation=c}),Object.defineProperty(o,"maxChannelCount",{get:()=>s.maxChannelCount}),o.connect(s),o},KJ=t=>t===null?null:t.hasOwnProperty("AudioWorkletNode")?t.AudioWorkletNode:null,YJ=t=>{const{port1:e}=new MessageChannel;try{e.postMessage(t)}finally{e.close()}},ZJ=(t,e,n,r,i)=>(s,o,a,c,l,u)=>{if(a!==null)try{const h=new a(s,c,u),p=new Map;let m=null;if(Object.defineProperties(h,{channelCount:{get:()=>u.channelCount,set:()=>{throw t()}},channelCountMode:{get:()=>"explicit",set:()=>{throw t()}},onprocessorerror:{get:()=>m,set:g=>{typeof m=="function"&&h.removeEventListener("processorerror",m),m=typeof g=="function"?g:null,typeof m=="function"&&h.addEventListener("processorerror",m)}}}),h.addEventListener=(g=>(...v)=>{if(v[0]==="processorerror"){const y=typeof v[1]=="function"?v[1]:typeof v[1]=="object"&&v[1]!==null&&typeof v[1].handleEvent=="function"?v[1].handleEvent:null;if(y!==null){const _=p.get(v[1]);_!==void 0?v[1]=_:(v[1]=S=>{S.type==="error"?(Object.defineProperties(S,{type:{value:"processorerror"}}),y(S)):y(new ErrorEvent(v[0],{...S}))},p.set(y,v[1]))}}return g.call(h,"error",v[1],v[2]),g.call(h,...v)})(h.addEventListener),h.removeEventListener=(g=>(...v)=>{if(v[0]==="processorerror"){const y=p.get(v[1]);y!==void 0&&(p.delete(v[1]),v[1]=y)}return g.call(h,"error",v[1],v[2]),g.call(h,v[0],v[1],v[2])})(h.removeEventListener),u.numberOfOutputs!==0){const g=n(s,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return h.connect(g).connect(s.destination),i(h,()=>g.disconnect(),()=>g.connect(s.destination))}return h}catch(h){throw h.code===11?r():h}if(l===void 0)throw r();return YJ(u),e(s,o,l,u)},RP=(t,e)=>t===null?512:Math.max(512,Math.min(16384,Math.pow(2,Math.round(Math.log2(t*e))))),JJ=t=>new Promise((e,n)=>{const{port1:r,port2:i}=new MessageChannel;r.onmessage=({data:s})=>{r.close(),i.close(),e(s)},r.onmessageerror=({data:s})=>{r.close(),i.close(),n(s)},i.postMessage(t)}),QJ=async(t,e)=>{const n=await JJ(e);return new t(n)},eQ=(t,e,n,r)=>{let i=tw.get(t);i===void 0&&(i=new WeakMap,tw.set(t,i));const s=QJ(n,r);return i.set(e,s),s},tQ=(t,e,n,r,i,s,o,a,c,l,u,h,p)=>(m,g,v,y)=>{if(y.numberOfInputs===0&&y.numberOfOutputs===0)throw c();const _=Array.isArray(y.outputChannelCount)?y.outputChannelCount:Array.from(y.outputChannelCount);if(_.some(ie=>ie<1))throw c();if(_.length!==y.numberOfOutputs)throw e();if(y.channelCountMode!=="explicit")throw c();const S=y.channelCount*y.numberOfInputs,E=_.reduce((ie,te)=>ie+te,0),b=v.parameterDescriptors===void 0?0:v.parameterDescriptors.length;if(S+b>6||E>6)throw c();const N=new MessageChannel,R=[],M=[];for(let ie=0;ieie===void 0?0:ie},maxValue:{get:()=>te===void 0?Ui:te},minValue:{get:()=>X===void 0?ns:X}}),O.push(ne)}const C=r(m,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,S+b)}),I=RP(g,m.sampleRate),U=a(m,I,S+b,Math.max(1,E)),L=i(m,{channelCount:Math.max(1,E),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,E)}),P=[];for(let ie=0;ie{const X=O[te];return X.connect(C,0,S+te),X.start(0),[ie,X.offset]}));C.connect(U);let H=y.channelInterpretation,V=null;const B=y.numberOfOutputs===0?[U]:P,z={get bufferSize(){return I},get channelCount(){return y.channelCount},set channelCount(ie){throw n()},get channelCountMode(){return y.channelCountMode},set channelCountMode(ie){throw n()},get channelInterpretation(){return H},set channelInterpretation(ie){for(const te of R)te.channelInterpretation=ie;H=ie},get context(){return U.context},get inputs(){return R},get numberOfInputs(){return y.numberOfInputs},get numberOfOutputs(){return y.numberOfOutputs},get onprocessorerror(){return V},set onprocessorerror(ie){typeof V=="function"&&z.removeEventListener("processorerror",V),V=typeof ie=="function"?ie:null,typeof V=="function"&&z.addEventListener("processorerror",V)},get parameters(){return T},get port(){return N.port2},addEventListener(...ie){return U.addEventListener(ie[0],ie[1],ie[2])},connect:t.bind(null,B),disconnect:l.bind(null,B),dispatchEvent(...ie){return U.dispatchEvent(ie[0])},removeEventListener(...ie){return U.removeEventListener(ie[0],ie[1],ie[2])}},W=new Map;N.port1.addEventListener=(ie=>(...te)=>{if(te[0]==="message"){const X=typeof te[1]=="function"?te[1]:typeof te[1]=="object"&&te[1]!==null&&typeof te[1].handleEvent=="function"?te[1].handleEvent:null;if(X!==null){const $=W.get(te[1]);$!==void 0?te[1]=$:(te[1]=ne=>{u(m.currentTime,m.sampleRate,()=>X(ne))},W.set(X,te[1]))}}return ie.call(N.port1,te[0],te[1],te[2])})(N.port1.addEventListener),N.port1.removeEventListener=(ie=>(...te)=>{if(te[0]==="message"){const X=W.get(te[1]);X!==void 0&&(W.delete(te[1]),te[1]=X)}return ie.call(N.port1,te[0],te[1],te[2])})(N.port1.removeEventListener);let K=null;Object.defineProperty(N.port1,"onmessage",{get:()=>K,set:ie=>{typeof K=="function"&&N.port1.removeEventListener("message",K),K=typeof ie=="function"?ie:null,typeof K=="function"&&(N.port1.addEventListener("message",K),N.port1.start())}}),v.prototype.port=N.port1;let j=null;eQ(m,z,v,y).then(ie=>j=ie);const ge=K_(y.numberOfInputs,y.channelCount),Q=K_(y.numberOfOutputs,_),re=v.parameterDescriptors===void 0?[]:v.parameterDescriptors.reduce((ie,{name:te})=>({...ie,[te]:new Float32Array(128)}),{});let we=!0;const Ae=()=>{y.numberOfOutputs>0&&U.disconnect(L);for(let ie=0,te=0;ie{if(j!==null){const X=h(z);for(let $=0;${X_(ie,re,ne,S+ae,$)});for(let ne=0;ne{if(X[D].size>0)return Ee.set(D,I/128),G;const he=Ee.get(D);return he===void 0?[]:(G.every(ce=>ce.every(_e=>_e===0))&&(he===1?Ee.delete(D):Ee.set(D,he-1)),G)});we=u(m.currentTime+$/m.sampleRate,m.sampleRate,()=>j.process(ne,Q,re));for(let G=0,D=0;GU.connect(He).connect(m.destination),it=()=>{U.disconnect(He),He.disconnect()},De=()=>{if(we){it(),y.numberOfOutputs>0&&U.connect(L);for(let ie=0,te=0;ie{we&&(qe(),Ae()),Le=!1};return qe(),p(z,De,A)},NP=(t,e)=>{const n=t.createBiquadFilter();return Gr(n,e),nr(n,e,"Q"),nr(n,e,"detune"),nr(n,e,"frequency"),nr(n,e,"gain"),Xn(n,e,"type"),n},nQ=(t,e)=>(n,r)=>{const i=n.createChannelMerger(r.numberOfInputs);return t!==null&&t.name==="webkitAudioContext"&&e(n,i),Gr(i,r),i},rQ=t=>{const e=t.numberOfOutputs;Object.defineProperty(t,"channelCount",{get:()=>e,set:n=>{if(n!==e)throw si()}}),Object.defineProperty(t,"channelCountMode",{get:()=>"explicit",set:n=>{if(n!=="explicit")throw si()}}),Object.defineProperty(t,"channelInterpretation",{get:()=>"discrete",set:n=>{if(n!=="discrete")throw si()}})},hm=(t,e)=>{const n=t.createChannelSplitter(e.numberOfOutputs);return Gr(n,e),rQ(n),n},iQ=(t,e,n,r,i)=>(s,o)=>{if(s.createConstantSource===void 0)return n(s,o);const a=s.createConstantSource();return Gr(a,o),nr(a,o,"offset"),e(r,()=>r(s))||lT(a),e(i,()=>i(s))||uT(a),t(s,a),a},dd=(t,e)=>(t.connect=e.connect.bind(e),t.disconnect=e.disconnect.bind(e),t),sQ=(t,e,n,r)=>(i,{offset:s,...o})=>{const a=i.createBuffer(1,2,44100),c=e(i,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),l=n(i,{...o,gain:s}),u=a.getChannelData(0);u[0]=1,u[1]=1,c.buffer=a,c.loop=!0;const h={get bufferSize(){},get channelCount(){return l.channelCount},set channelCount(g){l.channelCount=g},get channelCountMode(){return l.channelCountMode},set channelCountMode(g){l.channelCountMode=g},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(g){l.channelInterpretation=g},get context(){return l.context},get inputs(){return[]},get numberOfInputs(){return c.numberOfInputs},get numberOfOutputs(){return l.numberOfOutputs},get offset(){return l.gain},get onended(){return c.onended},set onended(g){c.onended=g},addEventListener(...g){return c.addEventListener(g[0],g[1],g[2])},dispatchEvent(...g){return c.dispatchEvent(g[0])},removeEventListener(...g){return c.removeEventListener(g[0],g[1],g[2])},start(g=0){c.start.call(c,g)},stop(g=0){c.stop.call(c,g)}},p=()=>c.connect(l),m=()=>c.disconnect(l);return t(i,c),r(dd(h,l),p,m)},oQ=(t,e)=>(n,r)=>{const i=n.createConvolver();if(Gr(i,r),r.disableNormalization===i.normalize&&(i.normalize=!r.disableNormalization),Xn(i,r,"buffer"),r.channelCount>2||(e(i,"channelCount",s=>()=>s.call(i),s=>o=>{if(o>2)throw t();return s.call(i,o)}),r.channelCountMode==="max"))throw t();return e(i,"channelCountMode",s=>()=>s.call(i),s=>o=>{if(o==="max")throw t();return s.call(i,o)}),i},kP=(t,e)=>{const n=t.createDelay(e.maxDelayTime);return Gr(n,e),nr(n,e,"delayTime"),n},aQ=t=>(e,n)=>{const r=e.createDynamicsCompressor();if(Gr(r,n),n.channelCount>2||n.channelCountMode==="max")throw t();return nr(r,n,"attack"),nr(r,n,"knee"),nr(r,n,"ratio"),nr(r,n,"release"),nr(r,n,"threshold"),r},ms=(t,e)=>{const n=t.createGain();return Gr(n,e),nr(n,e,"gain"),n},cQ=t=>(e,n,r)=>{if(e.createIIRFilter===void 0)return t(e,n,r);const i=e.createIIRFilter(r.feedforward,r.feedback);return Gr(i,r),i};function lQ(t,e){const n=e[0]*e[0]+e[1]*e[1];return[(t[0]*e[0]+t[1]*e[1])/n,(t[1]*e[0]-t[0]*e[1])/n]}function uQ(t,e){return[t[0]*e[0]-t[1]*e[1],t[0]*e[1]+t[1]*e[0]]}function hN(t,e){let n=[0,0];for(let r=t.length-1;r>=0;r-=1)n=uQ(n,e),n[0]+=t[r];return n}const hQ=(t,e,n,r)=>(i,s,{channelCount:o,channelCountMode:a,channelInterpretation:c,feedback:l,feedforward:u})=>{const h=RP(s,i.sampleRate),p=l instanceof Float64Array?l:new Float64Array(l),m=u instanceof Float64Array?u:new Float64Array(u),g=p.length,v=m.length,y=Math.min(g,v);if(g===0||g>20)throw r();if(p[0]===0)throw e();if(v===0||v>20)throw r();if(m[0]===0)throw e();if(p[0]!==1){for(let O=0;O{const C=O.inputBuffer,I=O.outputBuffer,U=C.numberOfChannels;for(let L=0;Lt.createMediaElementSource(e.mediaElement),dQ=(t,e)=>{const n=t.createMediaStreamDestination();return Gr(n,e),n.numberOfOutputs===1&&Object.defineProperty(n,"numberOfOutputs",{get:()=>0}),n},pQ=(t,{mediaStream:e})=>{const n=e.getAudioTracks();n.sort((s,o)=>s.ido.id?1:0);const r=n.slice(0,1),i=t.createMediaStreamSource(new MediaStream(r));return Object.defineProperty(i,"mediaStream",{value:e}),i},mQ=(t,e)=>(n,{mediaStreamTrack:r})=>{if(typeof n.createMediaStreamTrackSource=="function")return n.createMediaStreamTrackSource(r);const i=new MediaStream([r]),s=n.createMediaStreamSource(i);if(r.kind!=="audio")throw t();if(e(n))throw new TypeError;return s},gQ=t=>t===null?null:t.hasOwnProperty("OfflineAudioContext")?t.OfflineAudioContext:t.hasOwnProperty("webkitOfflineAudioContext")?t.webkitOfflineAudioContext:null,_Q=(t,e,n,r,i,s)=>(o,a)=>{const c=o.createOscillator();return Gr(c,a),nr(c,a,"detune"),nr(c,a,"frequency"),a.periodicWave!==void 0?c.setPeriodicWave(a.periodicWave):Xn(c,a,"type"),e(n,()=>n(o))||lT(c),e(r,()=>r(o))||s(c,o),e(i,()=>i(o))||uT(c),t(o,c),c},vQ=t=>(e,n)=>{const r=e.createPanner();return r.orientationX===void 0?t(e,n):(Gr(r,n),nr(r,n,"orientationX"),nr(r,n,"orientationY"),nr(r,n,"orientationZ"),nr(r,n,"positionX"),nr(r,n,"positionY"),nr(r,n,"positionZ"),Xn(r,n,"coneInnerAngle"),Xn(r,n,"coneOuterAngle"),Xn(r,n,"coneOuterGain"),Xn(r,n,"distanceModel"),Xn(r,n,"maxDistance"),Xn(r,n,"panningModel"),Xn(r,n,"refDistance"),Xn(r,n,"rolloffFactor"),r)},yQ=(t,e,n,r,i,s,o,a,c,l)=>(u,{coneInnerAngle:h,coneOuterAngle:p,coneOuterGain:m,distanceModel:g,maxDistance:v,orientationX:y,orientationY:_,orientationZ:S,panningModel:E,positionX:b,positionY:N,positionZ:R,refDistance:M,rolloffFactor:O,...C})=>{const I=u.createPanner();if(C.channelCount>2||C.channelCountMode==="max")throw o();Gr(I,C);const U={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},L=n(u,{...U,channelInterpretation:"speakers",numberOfInputs:6}),P=r(u,{...C,gain:1}),T=r(u,{...U,gain:1}),H=r(u,{...U,gain:0}),V=r(u,{...U,gain:0}),B=r(u,{...U,gain:0}),z=r(u,{...U,gain:0}),W=r(u,{...U,gain:0}),K=i(u,256,6,1),j=s(u,{...U,curve:new Float32Array([1,1]),oversample:"none"});let Y=[y,_,S],ge=[b,N,R];const Q=new Float32Array(1);K.onaudioprocess=({inputBuffer:Ee})=>{const Le=[c(Ee,Q,0),c(Ee,Q,1),c(Ee,Q,2)];Le.some((qe,it)=>qe!==Y[it])&&(I.setOrientation(...Le),Y=Le);const He=[c(Ee,Q,3),c(Ee,Q,4),c(Ee,Q,5)];He.some((qe,it)=>qe!==ge[it])&&(I.setPosition(...He),ge=He)},Object.defineProperty(H.gain,"defaultValue",{get:()=>0}),Object.defineProperty(V.gain,"defaultValue",{get:()=>0}),Object.defineProperty(B.gain,"defaultValue",{get:()=>0}),Object.defineProperty(z.gain,"defaultValue",{get:()=>0}),Object.defineProperty(W.gain,"defaultValue",{get:()=>0});const re={get bufferSize(){},get channelCount(){return I.channelCount},set channelCount(Ee){if(Ee>2)throw o();P.channelCount=Ee,I.channelCount=Ee},get channelCountMode(){return I.channelCountMode},set channelCountMode(Ee){if(Ee==="max")throw o();P.channelCountMode=Ee,I.channelCountMode=Ee},get channelInterpretation(){return I.channelInterpretation},set channelInterpretation(Ee){P.channelInterpretation=Ee,I.channelInterpretation=Ee},get coneInnerAngle(){return I.coneInnerAngle},set coneInnerAngle(Ee){I.coneInnerAngle=Ee},get coneOuterAngle(){return I.coneOuterAngle},set coneOuterAngle(Ee){I.coneOuterAngle=Ee},get coneOuterGain(){return I.coneOuterGain},set coneOuterGain(Ee){if(Ee<0||Ee>1)throw e();I.coneOuterGain=Ee},get context(){return I.context},get distanceModel(){return I.distanceModel},set distanceModel(Ee){I.distanceModel=Ee},get inputs(){return[P]},get maxDistance(){return I.maxDistance},set maxDistance(Ee){if(Ee<0)throw new RangeError;I.maxDistance=Ee},get numberOfInputs(){return I.numberOfInputs},get numberOfOutputs(){return I.numberOfOutputs},get orientationX(){return T.gain},get orientationY(){return H.gain},get orientationZ(){return V.gain},get panningModel(){return I.panningModel},set panningModel(Ee){I.panningModel=Ee},get positionX(){return B.gain},get positionY(){return z.gain},get positionZ(){return W.gain},get refDistance(){return I.refDistance},set refDistance(Ee){if(Ee<0)throw new RangeError;I.refDistance=Ee},get rolloffFactor(){return I.rolloffFactor},set rolloffFactor(Ee){if(Ee<0)throw new RangeError;I.rolloffFactor=Ee},addEventListener(...Ee){return P.addEventListener(Ee[0],Ee[1],Ee[2])},dispatchEvent(...Ee){return P.dispatchEvent(Ee[0])},removeEventListener(...Ee){return P.removeEventListener(Ee[0],Ee[1],Ee[2])}};h!==re.coneInnerAngle&&(re.coneInnerAngle=h),p!==re.coneOuterAngle&&(re.coneOuterAngle=p),m!==re.coneOuterGain&&(re.coneOuterGain=m),g!==re.distanceModel&&(re.distanceModel=g),v!==re.maxDistance&&(re.maxDistance=v),y!==re.orientationX.value&&(re.orientationX.value=y),_!==re.orientationY.value&&(re.orientationY.value=_),S!==re.orientationZ.value&&(re.orientationZ.value=S),E!==re.panningModel&&(re.panningModel=E),b!==re.positionX.value&&(re.positionX.value=b),N!==re.positionY.value&&(re.positionY.value=N),R!==re.positionZ.value&&(re.positionZ.value=R),M!==re.refDistance&&(re.refDistance=M),O!==re.rolloffFactor&&(re.rolloffFactor=O),(Y[0]!==1||Y[1]!==0||Y[2]!==0)&&I.setOrientation(...Y),(ge[0]!==0||ge[1]!==0||ge[2]!==0)&&I.setPosition(...ge);const we=()=>{P.connect(I),t(P,j,0,0),j.connect(T).connect(L,0,0),j.connect(H).connect(L,0,1),j.connect(V).connect(L,0,2),j.connect(B).connect(L,0,3),j.connect(z).connect(L,0,4),j.connect(W).connect(L,0,5),L.connect(K).connect(u.destination)},Ae=()=>{P.disconnect(I),a(P,j,0,0),j.disconnect(T),T.disconnect(L),j.disconnect(H),H.disconnect(L),j.disconnect(V),V.disconnect(L),j.disconnect(B),B.disconnect(L),j.disconnect(z),z.disconnect(L),j.disconnect(W),W.disconnect(L),L.disconnect(K),K.disconnect(u.destination)};return l(dd(re,I),we,Ae)},xQ=t=>(e,{disableNormalization:n,imag:r,real:i})=>{const s=r instanceof Float32Array?r:new Float32Array(r),o=i instanceof Float32Array?i:new Float32Array(i),a=e.createPeriodicWave(o,s,{disableNormalization:n});if(Array.from(r).length<2)throw t();return a},fm=(t,e,n,r)=>t.createScriptProcessor(e,n,r),SQ=(t,e)=>(n,r)=>{const i=r.channelCountMode;if(i==="clamped-max")throw e();if(n.createStereoPanner===void 0)return t(n,r);const s=n.createStereoPanner();return Gr(s,r),nr(s,r,"pan"),Object.defineProperty(s,"channelCountMode",{get:()=>i,set:o=>{if(o!==i)throw e()}}),s},EQ=(t,e,n,r,i,s)=>{const a=new Float32Array([1,1]),c=Math.PI/2,l={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},u={...l,oversample:"none"},h=(g,v,y,_)=>{const S=new Float32Array(16385),E=new Float32Array(16385);for(let C=0;C<16385;C+=1){const I=C/16384*c;S[C]=Math.cos(I),E[C]=Math.sin(I)}const b=n(g,{...l,gain:0}),N=r(g,{...u,curve:S}),R=r(g,{...u,curve:a}),M=n(g,{...l,gain:0}),O=r(g,{...u,curve:E});return{connectGraph(){v.connect(b),v.connect(R.inputs===void 0?R:R.inputs[0]),v.connect(M),R.connect(y),y.connect(N.inputs===void 0?N:N.inputs[0]),y.connect(O.inputs===void 0?O:O.inputs[0]),N.connect(b.gain),O.connect(M.gain),b.connect(_,0,0),M.connect(_,0,1)},disconnectGraph(){v.disconnect(b),v.disconnect(R.inputs===void 0?R:R.inputs[0]),v.disconnect(M),R.disconnect(y),y.disconnect(N.inputs===void 0?N:N.inputs[0]),y.disconnect(O.inputs===void 0?O:O.inputs[0]),N.disconnect(b.gain),O.disconnect(M.gain),b.disconnect(_,0,0),M.disconnect(_,0,1)}}},p=(g,v,y,_)=>{const S=new Float32Array(16385),E=new Float32Array(16385),b=new Float32Array(16385),N=new Float32Array(16385),R=Math.floor(16385/2);for(let B=0;B<16385;B+=1)if(B>R){const z=(B-R)/(16384-R)*c;S[B]=Math.cos(z),E[B]=Math.sin(z),b[B]=0,N[B]=1}else{const z=B/(16384-R)*c;S[B]=1,E[B]=0,b[B]=Math.cos(z),N[B]=Math.sin(z)}const M=e(g,{channelCount:2,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:2}),O=n(g,{...l,gain:0}),C=r(g,{...u,curve:S}),I=n(g,{...l,gain:0}),U=r(g,{...u,curve:E}),L=r(g,{...u,curve:a}),P=n(g,{...l,gain:0}),T=r(g,{...u,curve:b}),H=n(g,{...l,gain:0}),V=r(g,{...u,curve:N});return{connectGraph(){v.connect(M),v.connect(L.inputs===void 0?L:L.inputs[0]),M.connect(O,0),M.connect(I,0),M.connect(P,1),M.connect(H,1),L.connect(y),y.connect(C.inputs===void 0?C:C.inputs[0]),y.connect(U.inputs===void 0?U:U.inputs[0]),y.connect(T.inputs===void 0?T:T.inputs[0]),y.connect(V.inputs===void 0?V:V.inputs[0]),C.connect(O.gain),U.connect(I.gain),T.connect(P.gain),V.connect(H.gain),O.connect(_,0,0),P.connect(_,0,0),I.connect(_,0,1),H.connect(_,0,1)},disconnectGraph(){v.disconnect(M),v.disconnect(L.inputs===void 0?L:L.inputs[0]),M.disconnect(O,0),M.disconnect(I,0),M.disconnect(P,1),M.disconnect(H,1),L.disconnect(y),y.disconnect(C.inputs===void 0?C:C.inputs[0]),y.disconnect(U.inputs===void 0?U:U.inputs[0]),y.disconnect(T.inputs===void 0?T:T.inputs[0]),y.disconnect(V.inputs===void 0?V:V.inputs[0]),C.disconnect(O.gain),U.disconnect(I.gain),T.disconnect(P.gain),V.disconnect(H.gain),O.disconnect(_,0,0),P.disconnect(_,0,0),I.disconnect(_,0,1),H.disconnect(_,0,1)}}},m=(g,v,y,_,S)=>{if(v===1)return h(g,y,_,S);if(v===2)return p(g,y,_,S);throw i()};return(g,{channelCount:v,channelCountMode:y,pan:_,...S})=>{if(y==="max")throw i();const E=t(g,{...S,channelCount:1,channelCountMode:y,numberOfInputs:2}),b=n(g,{...S,channelCount:v,channelCountMode:y,gain:1}),N=n(g,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:_});let{connectGraph:R,disconnectGraph:M}=m(g,v,b,N,E);Object.defineProperty(N.gain,"defaultValue",{get:()=>0}),Object.defineProperty(N.gain,"maxValue",{get:()=>1}),Object.defineProperty(N.gain,"minValue",{get:()=>-1});const O={get bufferSize(){},get channelCount(){return b.channelCount},set channelCount(L){b.channelCount!==L&&(C&&M(),{connectGraph:R,disconnectGraph:M}=m(g,L,b,N,E),C&&R()),b.channelCount=L},get channelCountMode(){return b.channelCountMode},set channelCountMode(L){if(L==="clamped-max"||L==="max")throw i();b.channelCountMode=L},get channelInterpretation(){return b.channelInterpretation},set channelInterpretation(L){b.channelInterpretation=L},get context(){return b.context},get inputs(){return[b]},get numberOfInputs(){return b.numberOfInputs},get numberOfOutputs(){return b.numberOfOutputs},get pan(){return N.gain},addEventListener(...L){return b.addEventListener(L[0],L[1],L[2])},dispatchEvent(...L){return b.dispatchEvent(L[0])},removeEventListener(...L){return b.removeEventListener(L[0],L[1],L[2])}};let C=!1;const I=()=>{R(),C=!0},U=()=>{M(),C=!1};return s(dd(O,E),I,U)}},wQ=(t,e,n,r,i,s,o)=>(a,c)=>{const l=a.createWaveShaper();if(s!==null&&s.name==="webkitAudioContext"&&a.createGain().gain.automationRate===void 0)return n(a,c);Gr(l,c);const u=c.curve===null||c.curve instanceof Float32Array?c.curve:new Float32Array(c.curve);if(u!==null&&u.length<2)throw e();Xn(l,{curve:u},"curve"),Xn(l,c,"oversample");let h=null,p=!1;return o(l,"curve",v=>()=>v.call(l),v=>y=>(v.call(l,y),p&&(r(y)&&h===null?h=t(a,l):!r(y)&&h!==null&&(h(),h=null)),y)),i(l,()=>{p=!0,r(l.curve)&&(h=t(a,l))},()=>{p=!1,h!==null&&(h(),h=null)})},bQ=(t,e,n,r,i)=>(s,{curve:o,oversample:a,...c})=>{const l=s.createWaveShaper(),u=s.createWaveShaper();Gr(l,c),Gr(u,c);const h=n(s,{...c,gain:1}),p=n(s,{...c,gain:-1}),m=n(s,{...c,gain:1}),g=n(s,{...c,gain:-1});let v=null,y=!1,_=null;const S={get bufferSize(){},get channelCount(){return l.channelCount},set channelCount(N){h.channelCount=N,p.channelCount=N,l.channelCount=N,m.channelCount=N,u.channelCount=N,g.channelCount=N},get channelCountMode(){return l.channelCountMode},set channelCountMode(N){h.channelCountMode=N,p.channelCountMode=N,l.channelCountMode=N,m.channelCountMode=N,u.channelCountMode=N,g.channelCountMode=N},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(N){h.channelInterpretation=N,p.channelInterpretation=N,l.channelInterpretation=N,m.channelInterpretation=N,u.channelInterpretation=N,g.channelInterpretation=N},get context(){return l.context},get curve(){return _},set curve(N){if(N!==null&&N.length<2)throw e();if(N===null)l.curve=N,u.curve=N;else{const R=N.length,M=new Float32Array(R+2-R%2),O=new Float32Array(R+2-R%2);M[0]=N[0],O[0]=-N[R-1];const C=Math.ceil((R+1)/2),I=(R+1)/2-1;for(let U=1;U{h.connect(l).connect(m),h.connect(p).connect(u).connect(g).connect(m),y=!0,r(_)&&(v=t(s,h))},b=()=>{h.disconnect(l),l.disconnect(m),h.disconnect(p),p.disconnect(u),u.disconnect(g),g.disconnect(m),y=!1,v!==null&&(v(),v=null)};return i(dd(S,m),E,b)},Xi=()=>new DOMException("","NotSupportedError"),TQ={numberOfChannels:1},AQ=(t,e,n,r,i)=>class extends t{constructor(o,a,c){let l;if(typeof o=="number"&&a!==void 0&&c!==void 0)l={length:a,numberOfChannels:o,sampleRate:c};else if(typeof o=="object")l=o;else throw new Error("The given parameters are not valid.");const{length:u,numberOfChannels:h,sampleRate:p}={...TQ,...l},m=r(h,u,p);e(kp,()=>kp(m))||m.addEventListener("statechange",(()=>{let g=0;const v=y=>{this._state==="running"&&(g>0?(m.removeEventListener("statechange",v),y.stopImmediatePropagation(),this._waitForThePromiseToSettle(y)):g+=1)};return v})()),super(m,h),this._length=u,this._nativeOfflineAudioContext=m,this._state=null}get length(){return this._nativeOfflineAudioContext.length===void 0?this._length:this._nativeOfflineAudioContext.length}get state(){return this._state===null?this._nativeOfflineAudioContext.state:this._state}startRendering(){return this._state==="running"?Promise.reject(n()):(this._state="running",i(this.destination,this._nativeOfflineAudioContext).finally(()=>{this._state=null,EP(this)}))}_waitForThePromiseToSettle(o){this._state===null?this._nativeOfflineAudioContext.dispatchEvent(o):setTimeout(()=>this._waitForThePromiseToSettle(o))}},MQ={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:440,periodicWave:void 0,type:"sine"},CQ=(t,e,n,r,i,s,o)=>class extends t{constructor(c,l){const u=i(c),h={...MQ,...l},p=n(u,h),m=s(u),g=m?r():null,v=c.sampleRate/2;super(c,!1,p,g),this._detune=e(this,m,p.detune,153600,-153600),this._frequency=e(this,m,p.frequency,v,-v),this._nativeOscillatorNode=p,this._onended=null,this._oscillatorNodeRenderer=g,this._oscillatorNodeRenderer!==null&&h.periodicWave!==void 0&&(this._oscillatorNodeRenderer.periodicWave=h.periodicWave)}get detune(){return this._detune}get frequency(){return this._frequency}get onended(){return this._onended}set onended(c){const l=typeof c=="function"?o(this,c):null;this._nativeOscillatorNode.onended=l;const u=this._nativeOscillatorNode.onended;this._onended=u!==null&&u===l?c:u}get type(){return this._nativeOscillatorNode.type}set type(c){this._nativeOscillatorNode.type=c,this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.periodicWave=null)}setPeriodicWave(c){this._nativeOscillatorNode.setPeriodicWave(c),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.periodicWave=c)}start(c=0){if(this._nativeOscillatorNode.start(c),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.start=c),this.context.state!=="closed"){$f(this);const l=()=>{this._nativeOscillatorNode.removeEventListener("ended",l),wc(this)&&cm(this)};this._nativeOscillatorNode.addEventListener("ended",l)}}stop(c=0){this._nativeOscillatorNode.stop(c),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.stop=c)}},RQ=(t,e,n,r,i)=>()=>{const s=new WeakMap;let o=null,a=null,c=null;const l=async(u,h)=>{let p=n(u);const m=Ai(p,h);if(!m){const g={channelCount:p.channelCount,channelCountMode:p.channelCountMode,channelInterpretation:p.channelInterpretation,detune:p.detune.value,frequency:p.frequency.value,periodicWave:o===null?void 0:o,type:p.type};p=e(h,g),a!==null&&p.start(a),c!==null&&p.stop(c)}return s.set(h,p),m?(await t(h,u.detune,p.detune),await t(h,u.frequency,p.frequency)):(await r(h,u.detune,p.detune),await r(h,u.frequency,p.frequency)),await i(u,h,p),p};return{set periodicWave(u){o=u},set start(u){a=u},set stop(u){c=u},render(u,h){const p=s.get(h);return p!==void 0?Promise.resolve(p):l(u,h)}}},NQ={channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:1,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1},kQ=(t,e,n,r,i,s,o)=>class extends t{constructor(c,l){const u=i(c),h={...NQ,...l},p=n(u,h),m=s(u),g=m?r():null;super(c,!1,p,g),this._nativePannerNode=p,this._orientationX=e(this,m,p.orientationX,Ui,ns),this._orientationY=e(this,m,p.orientationY,Ui,ns),this._orientationZ=e(this,m,p.orientationZ,Ui,ns),this._positionX=e(this,m,p.positionX,Ui,ns),this._positionY=e(this,m,p.positionY,Ui,ns),this._positionZ=e(this,m,p.positionZ,Ui,ns),o(this,1)}get coneInnerAngle(){return this._nativePannerNode.coneInnerAngle}set coneInnerAngle(c){this._nativePannerNode.coneInnerAngle=c}get coneOuterAngle(){return this._nativePannerNode.coneOuterAngle}set coneOuterAngle(c){this._nativePannerNode.coneOuterAngle=c}get coneOuterGain(){return this._nativePannerNode.coneOuterGain}set coneOuterGain(c){this._nativePannerNode.coneOuterGain=c}get distanceModel(){return this._nativePannerNode.distanceModel}set distanceModel(c){this._nativePannerNode.distanceModel=c}get maxDistance(){return this._nativePannerNode.maxDistance}set maxDistance(c){this._nativePannerNode.maxDistance=c}get orientationX(){return this._orientationX}get orientationY(){return this._orientationY}get orientationZ(){return this._orientationZ}get panningModel(){return this._nativePannerNode.panningModel}set panningModel(c){this._nativePannerNode.panningModel=c}get positionX(){return this._positionX}get positionY(){return this._positionY}get positionZ(){return this._positionZ}get refDistance(){return this._nativePannerNode.refDistance}set refDistance(c){this._nativePannerNode.refDistance=c}get rolloffFactor(){return this._nativePannerNode.rolloffFactor}set rolloffFactor(c){this._nativePannerNode.rolloffFactor=c}},IQ=(t,e,n,r,i,s,o,a,c,l)=>()=>{const u=new WeakMap;let h=null;const p=async(m,g)=>{let v=null,y=s(m);const _={channelCount:y.channelCount,channelCountMode:y.channelCountMode,channelInterpretation:y.channelInterpretation},S={..._,coneInnerAngle:y.coneInnerAngle,coneOuterAngle:y.coneOuterAngle,coneOuterGain:y.coneOuterGain,distanceModel:y.distanceModel,maxDistance:y.maxDistance,panningModel:y.panningModel,refDistance:y.refDistance,rolloffFactor:y.rolloffFactor},E=Ai(y,g);if("bufferSize"in y)v=r(g,{..._,gain:1});else if(!E){const b={...S,orientationX:y.orientationX.value,orientationY:y.orientationY.value,orientationZ:y.orientationZ.value,positionX:y.positionX.value,positionY:y.positionY.value,positionZ:y.positionZ.value};y=i(g,b)}if(u.set(g,v===null?y:v),v!==null){if(h===null){if(o===null)throw new Error("Missing the native OfflineAudioContext constructor.");const U=new o(6,m.context.length,g.sampleRate),L=e(U,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6});L.connect(U.destination),h=(async()=>{const P=await Promise.all([m.orientationX,m.orientationY,m.orientationZ,m.positionX,m.positionY,m.positionZ].map(async(T,H)=>{const V=n(U,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:H===0?1:0});return await a(U,T,V.offset),V}));for(let T=0;T<6;T+=1)P[T].connect(L,0,T),P[T].start(0);return l(U)})()}const b=await h,N=r(g,{..._,gain:1});await c(m,g,N);const R=[];for(let U=0;UT!==M[H])||P.some((T,H)=>T!==O[H])){M=L,O=P;const T=U/g.sampleRate;C.gain.setValueAtTime(0,T),C=r(g,{..._,gain:0}),I=i(g,{...S,orientationX:M[0],orientationY:M[1],orientationZ:M[2],positionX:O[0],positionY:O[1],positionZ:O[2]}),C.gain.setValueAtTime(1,T),N.connect(C).connect(I.inputs[0]),I.connect(v)}}return v}return E?(await t(g,m.orientationX,y.orientationX),await t(g,m.orientationY,y.orientationY),await t(g,m.orientationZ,y.orientationZ),await t(g,m.positionX,y.positionX),await t(g,m.positionY,y.positionY),await t(g,m.positionZ,y.positionZ)):(await a(g,m.orientationX,y.orientationX),await a(g,m.orientationY,y.orientationY),await a(g,m.orientationZ,y.orientationZ),await a(g,m.positionX,y.positionX),await a(g,m.positionY,y.positionY),await a(g,m.positionZ,y.positionZ)),fd(y)?await c(m,g,y.inputs[0]):await c(m,g,y),y};return{render(m,g){const v=u.get(g);return v!==void 0?Promise.resolve(v):p(m,g)}}},OQ={disableNormalization:!1},LQ=(t,e,n,r)=>class IP{constructor(s,o){const a=e(s),c=r({...OQ,...o}),l=t(a,c);return n.add(l),l}static[Symbol.hasInstance](s){return s!==null&&typeof s=="object"&&Object.getPrototypeOf(s)===IP.prototype||n.has(s)}},PQ=(t,e)=>(n,r,i)=>(t(r).replay(i),e(r,n,i)),DQ=(t,e,n)=>async(r,i,s)=>{const o=t(r);await Promise.all(o.activeInputs.map((a,c)=>Array.from(a).map(async([l,u])=>{const p=await e(l).render(l,i),m=r.context.destination;!n(l)&&(r!==m||!n(r))&&p.connect(s,u,c)})).reduce((a,c)=>[...a,...c],[]))},UQ=(t,e,n)=>async(r,i,s)=>{const o=e(r);await Promise.all(Array.from(o.activeInputs).map(async([a,c])=>{const u=await t(a).render(a,i);n(a)||u.connect(s,c)}))},FQ=(t,e,n,r)=>i=>t(kp,()=>kp(i))?Promise.resolve(t(r,r)).then(s=>{if(!s){const o=n(i,512,0,1);i.oncomplete=()=>{o.onaudioprocess=null,o.disconnect()},o.onaudioprocess=()=>i.currentTime,o.connect(i.destination)}return i.startRendering()}):new Promise(s=>{const o=e(i,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});i.oncomplete=a=>{o.disconnect(),s(a.renderedBuffer)},o.connect(i.destination),i.startRendering()}),BQ=t=>(e,n)=>{t.set(e,n)},zQ=t=>(e,n)=>t.set(e,n),VQ=(t,e,n,r,i,s,o,a)=>(c,l)=>n(c).render(c,l).then(()=>Promise.all(Array.from(r(l)).map(u=>n(u).render(u,l)))).then(()=>i(l)).then(u=>(typeof u.copyFromChannel!="function"?(o(u),oT(u)):e(s,()=>s(u))||a(u),t.add(u),u)),HQ={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",pan:0},GQ=(t,e,n,r,i,s)=>class extends t{constructor(a,c){const l=i(a),u={...HQ,...c},h=n(l,u),p=s(l),m=p?r():null;super(a,!1,h,m),this._pan=e(this,p,h.pan)}get pan(){return this._pan}},WQ=(t,e,n,r,i)=>()=>{const s=new WeakMap,o=async(a,c)=>{let l=n(a);const u=Ai(l,c);if(!u){const h={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,pan:l.pan.value};l=e(c,h)}return s.set(c,l),u?await t(c,a.pan,l.pan):await r(c,a.pan,l.pan),fd(l)?await i(a,c,l.inputs[0]):await i(a,c,l),l};return{render(a,c){const l=s.get(c);return l!==void 0?Promise.resolve(l):o(a,c)}}},jQ=t=>()=>{if(t===null)return!1;try{new t({length:1,sampleRate:44100})}catch{return!1}return!0},$Q=(t,e)=>async()=>{if(t===null)return!0;if(e===null)return!1;const n=new Blob(['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),r=new e(1,128,44100),i=URL.createObjectURL(n);let s=!1,o=!1;try{await r.audioWorklet.addModule(i);const a=new t(r,"a",{numberOfOutputs:0}),c=r.createOscillator();a.port.onmessage=()=>s=!0,a.onprocessorerror=()=>o=!0,c.connect(a),c.start(0),await r.startRendering(),await new Promise(l=>setTimeout(l))}catch{}finally{URL.revokeObjectURL(i)}return s&&!o},qQ=(t,e)=>()=>{if(e===null)return Promise.resolve(!1);const n=new e(1,1,44100),r=t(n,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return new Promise(i=>{n.oncomplete=()=>{r.disconnect(),i(n.currentTime!==0)},n.startRendering()})},XQ=()=>new DOMException("","UnknownError"),KQ={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",curve:null,oversample:"none"},YQ=(t,e,n,r,i,s,o)=>class extends t{constructor(c,l){const u=i(c),h={...KQ,...l},p=n(u,h),g=s(u)?r():null;super(c,!0,p,g),this._isCurveNullified=!1,this._nativeWaveShaperNode=p,o(this,1)}get curve(){return this._isCurveNullified?null:this._nativeWaveShaperNode.curve}set curve(c){if(c===null)this._isCurveNullified=!0,this._nativeWaveShaperNode.curve=new Float32Array([0,0]);else{if(c.length<2)throw e();this._isCurveNullified=!1,this._nativeWaveShaperNode.curve=c}}get oversample(){return this._nativeWaveShaperNode.oversample}set oversample(c){this._nativeWaveShaperNode.oversample=c}},ZQ=(t,e,n)=>()=>{const r=new WeakMap,i=async(s,o)=>{let a=e(s);if(!Ai(a,o)){const l={channelCount:a.channelCount,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,curve:a.curve,oversample:a.oversample};a=t(o,l)}return r.set(o,a),fd(a)?await n(s,o,a.inputs[0]):await n(s,o,a),a};return{render(s,o){const a=r.get(o);return a!==void 0?Promise.resolve(a):i(s,o)}}},JQ=()=>typeof window>"u"?null:window,QQ=(t,e)=>n=>{n.copyFromChannel=(r,i,s=0)=>{const o=t(s),a=t(i);if(a>=n.numberOfChannels)throw e();const c=n.length,l=n.getChannelData(a),u=r.length;for(let h=o<0?-o:0;h+o{const o=t(s),a=t(i);if(a>=n.numberOfChannels)throw e();const c=n.length,l=n.getChannelData(a),u=r.length;for(let h=o<0?-o:0;h+oe=>{e.copyFromChannel=(n=>(r,i,s=0)=>{const o=t(s),a=t(i);if(o(r,i,s=0)=>{const o=t(s),a=t(i);if(o(e,n)=>{const r=n.createBuffer(1,1,44100);e.buffer===null&&(e.buffer=r),t(e,"buffer",i=>()=>{const s=i.call(e);return s===r?null:s},i=>s=>i.call(e,s===null?r:s))},nee=(t,e)=>(n,r)=>{r.channelCount=1,r.channelCountMode="explicit",Object.defineProperty(r,"channelCount",{get:()=>1,set:()=>{throw t()}}),Object.defineProperty(r,"channelCountMode",{get:()=>"explicit",set:()=>{throw t()}});const i=n.createBufferSource();e(r,()=>{const a=r.numberOfInputs;for(let c=0;ci.disconnect(r))},OP=(t,e,n)=>t.copyFromChannel===void 0?t.getChannelData(n)[0]:(t.copyFromChannel(e,n),e[0]),LP=t=>{if(t===null)return!1;const e=t.length;return e%2!==0?t[Math.floor(e/2)]!==0:t[e/2-1]+t[e/2]!==0},dm=(t,e,n,r)=>{let i=t;for(;!i.hasOwnProperty(e);)i=Object.getPrototypeOf(i);const{get:s,set:o}=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,{get:n(s),set:r(o)})},ree=t=>({...t,outputChannelCount:t.outputChannelCount!==void 0?t.outputChannelCount:t.numberOfInputs===1&&t.numberOfOutputs===1?[t.channelCount]:Array.from({length:t.numberOfOutputs},()=>1)}),iee=t=>({...t,channelCount:t.numberOfOutputs}),see=t=>{const{imag:e,real:n}=t;return e===void 0?n===void 0?{...t,imag:[0,0],real:[0,0]}:{...t,imag:Array.from(n,()=>0),real:n}:n===void 0?{...t,imag:e,real:Array.from(e,()=>0)}:{...t,imag:e,real:n}},PP=(t,e,n)=>{try{t.setValueAtTime(e,n)}catch(r){if(r.code!==9)throw r;PP(t,e,n+1e-7)}},oee=t=>{const e=t.createBufferSource();e.start();try{e.start()}catch{return!0}return!1},aee=t=>{const e=t.createBufferSource(),n=t.createBuffer(1,1,44100);e.buffer=n;try{e.start(0,1)}catch{return!1}return!0},cee=t=>{const e=t.createBufferSource();e.start();try{e.stop()}catch{return!1}return!0},hT=t=>{const e=t.createOscillator();try{e.start(-1)}catch(n){return n instanceof RangeError}return!1},DP=t=>{const e=t.createBuffer(1,1,44100),n=t.createBufferSource();n.buffer=e,n.start(),n.stop();try{return n.stop(),!0}catch{return!1}},fT=t=>{const e=t.createOscillator();try{e.stop(-1)}catch(n){return n instanceof RangeError}return!1},lee=t=>{const{port1:e,port2:n}=new MessageChannel;try{e.postMessage(t)}finally{e.close(),n.close()}},uee=t=>{t.start=(e=>(n=0,r=0,i)=>{const s=t.buffer,o=s===null?r:Math.min(s.duration,r);s!==null&&o>s.duration-.5/t.context.sampleRate?e.call(t,n,0,0):e.call(t,n,o,i)})(t.start)},UP=(t,e)=>{const n=e.createGain();t.connect(n);const r=(i=>()=>{i.call(t,n),t.removeEventListener("ended",r)})(t.disconnect);t.addEventListener("ended",r),dd(t,n),t.stop=(i=>{let s=!1;return(o=0)=>{if(s)try{i.call(t,o)}catch{n.gain.setValueAtTime(0,o)}else i.call(t,o),s=!0}})(t.stop)},pd=(t,e)=>n=>{const r={value:t};return Object.defineProperties(n,{currentTarget:r,target:r}),typeof e=="function"?e.call(t,n):e.handleEvent.call(t,n)},hee=kY(dh),fee=UY(dh),dee=KZ(ry),FP=new WeakMap,pee=dJ(FP),Vo=TZ(new Map,new WeakMap),Ta=JQ(),BP=GJ(Vo,Fa),dT=fJ(zi),di=DQ(zi,dT,Ku),mee=HY(BP,Gn,di),Un=gJ(ny),jc=gQ(Ta),Rn=OJ(jc),zP=new WeakMap,VP=sJ(pd),pm=qJ(Ta),pT=RJ(pm),mT=NJ(Ta),HP=kJ(Ta),Ip=KJ(Ta),yr=dZ(IY(mP),DY(hee,fee,j_,dee,$_,zi,pee,am,Gn,dh,wc,Ku,u_),Vo,bJ(QE,$_,zi,Gn,Np,wc),Fa,iy,Xi,jZ(j_,QE,zi,Gn,Np,Un,wc,Rn),JZ(zP,zi,Lo),VP,Un,pT,mT,HP,Rn,Ip),gee=VY(yr,mee,Fa,BP,Un,Rn),gT=new WeakSet,fN=WJ(Ta),GP=FZ(new Uint32Array(1)),_T=QQ(GP,Fa),vT=eee(GP),WP=WY(gT,Vo,Xi,fN,jc,jQ(fN),_T,vT),sy=FY(ms),jP=UQ(dT,lm,Ku),Ba=IZ(jP),md=$J(sy,Vo,oee,aee,cee,hT,DP,fT,uee,tee(dm),UP),za=PQ(pJ(lm),jP),_ee=qY(Ba,md,Gn,za,di),Ho=pZ(OY(gP),zP,sT,mZ,TY,AY,MY,CY,RY,YE,dP,pm,PP),vee=$Y(yr,_ee,Ho,si,md,Un,Rn,pd),yee=nZ(yr,rZ,Fa,si,XJ(ms,dm),Un,Rn,di),xee=bZ(Ba,NP,Gn,za,di),ph=zQ(FP),See=wZ(yr,Ho,xee,iy,NP,Un,Rn,ph),ql=VJ(dh,mT),Eee=nee(si,ql),Xl=nQ(pm,Eee),wee=CZ(Xl,Gn,di),bee=MZ(yr,wee,Xl,Un,Rn),Tee=kZ(hm,Gn,di),Aee=NZ(yr,Tee,hm,Un,Rn,iee),Mee=sQ(sy,md,ms,ql),gd=iQ(sy,Vo,Mee,hT,fT),Cee=UZ(Ba,gd,Gn,za,di),Ree=DZ(yr,Ho,Cee,gd,Un,Rn,pd),$P=oQ(Xi,dm),Nee=VZ($P,Gn,di),kee=zZ(yr,Nee,$P,Un,Rn,ph),Iee=XZ(Ba,kP,Gn,za,di),Oee=qZ(yr,Ho,Iee,kP,Un,Rn,ph),qP=aQ(Xi),Lee=nJ(Ba,qP,Gn,za,di),Pee=tJ(yr,Ho,Lee,qP,Xi,Un,Rn,ph),Dee=uJ(Ba,ms,Gn,za,di),Uee=lJ(yr,Ho,Dee,ms,Un,Rn),Fee=hQ(iy,si,fm,Xi),oy=FQ(Vo,ms,fm,qQ(ms,jc)),Bee=wJ(md,Gn,jc,di,oy),zee=cQ(Fee),Vee=SJ(yr,zee,Bee,Un,Rn,ph),Hee=iZ(Ho,Xl,gd,fm,Xi,OP,Rn,dm),XP=new WeakMap,Gee=zJ(yee,Hee,VP,Rn,XP,pd),KP=_Q(sy,Vo,hT,DP,fT,UP),Wee=RQ(Ba,KP,Gn,za,di),jee=CQ(yr,Ho,KP,Wee,Un,Rn,pd),YP=LZ(md),$ee=bQ(YP,si,ms,LP,ql),ay=wQ(YP,si,$ee,LP,ql,pm,dm),qee=yQ(j_,si,Xl,ms,fm,ay,Xi,$_,OP,ql),ZP=vQ(qee),Xee=IQ(Ba,Xl,gd,ms,ZP,Gn,jc,za,di,oy),Kee=kQ(yr,Ho,ZP,Xee,Un,Rn,ph),Yee=xQ(Fa),Zee=LQ(Yee,Un,new WeakSet,see),Jee=EQ(Xl,hm,ms,ay,Xi,ql),JP=SQ(Jee,Xi),Qee=WQ(Ba,JP,Gn,za,di),ete=GQ(yr,Ho,JP,Qee,Un,Rn),tte=ZQ(ay,Gn,di),nte=YQ(yr,si,ay,tte,Un,Rn,ph),QP=LJ(Ta),yT=oJ(Ta),eD=new WeakMap,rte=_J(eD,jc),ite=QP?PY(Vo,Xi,iJ(Ta),yT,aJ(NY),Un,rte,Rn,Ip,new WeakMap,new WeakMap,$Q(Ip,jc),Ta):void 0,ste=IJ(pT,Rn),ote=WZ(gT,Vo,GZ,rJ,new WeakSet,Un,ste,G_,kp,_T,vT),tD=SZ(ite,gee,WP,vee,See,bee,Aee,Ree,kee,ote,Oee,Pee,Uee,Vee,Gee,jee,Kee,Zee,ete,nte),ate=PJ(yr,fQ,Un,Rn),cte=UJ(yr,dQ,Un,Rn),lte=FJ(yr,pQ,Un,Rn),ute=mQ(si,Rn),hte=BJ(yr,ute,Un),fte=tZ(tD,si,Xi,XQ,ate,cte,lte,hte,pm),xT=vJ(XP),dte=BY(xT),nD=OZ(Fa),pte=YZ(xT),rD=QZ(Fa),iD=new WeakMap,mte=hJ(iD,Lo),gte=tQ(nD,Fa,si,Xl,hm,gd,ms,fm,Xi,rD,yT,mte,ql),_te=ZJ(si,gte,ms,Xi,ql),vte=xZ(Ba,nD,md,Xl,hm,gd,ms,pte,rD,yT,Gn,Ip,jc,za,di,oy),yte=mJ(eD),xte=BQ(iD),dN=QP?_Z(dte,yr,Ho,vte,_te,zi,yte,Un,Rn,Ip,ree,xte,lee,pd):void 0,Ste=HZ(Xi,jc),Ete=VQ(gT,Vo,dT,xT,oy,G_,_T,vT),wte=AQ(tD,Vo,si,Ste,Ete),bte=TJ(ny,pT),Tte=AJ(iT,mT),Ate=MJ(sT,HP),Mte=CJ(ny,Rn);function Ps(t){return t===void 0}function Wt(t){return t!==void 0}function Cte(t){return typeof t=="function"}function Po(t){return typeof t=="number"}function Al(t){return Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object}function sD(t){return typeof t=="boolean"}function us(t){return Array.isArray(t)}function Lc(t){return typeof t=="string"}function E0(t){return Lc(t)&&/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i.test(t)}function bt(t,e){if(!t)throw new Error(e)}function Aa(t,e,n=1/0){if(!(e<=t&&t<=n))throw new RangeError(`Value must be within [${e}, ${n}], got: ${t}`)}function oD(t){!t.isOffline&&t.state!=="running"&&cy('The AudioContext is "suspended". Invoke Tone.start() from a user action to start the audio.')}let aD=!1,pN=!1;function mN(t){aD=t}function Rte(t){Ps(t)&&aD&&!pN&&(pN=!0,cy("Events scheduled inside of scheduled callbacks should use the passed in scheduling time. See https://github.com/Tonejs/Tone.js/wiki/Accurate-Timing"))}let cD=console;function Nte(...t){cD.log(...t)}function cy(...t){cD.warn(...t)}function kte(t){return new fte(t)}function Ite(t,e,n){return new wte(t,e,n)}const Rs=typeof self=="object"?self:null,Ote=Rs&&(Rs.hasOwnProperty("AudioContext")||Rs.hasOwnProperty("webkitAudioContext"));function Lte(t,e,n){return bt(Wt(dN),"AudioWorkletNode only works in a secure context (https or localhost)"),new(t instanceof(Rs==null?void 0:Rs.BaseAudioContext)?Rs==null?void 0:Rs.AudioWorkletNode:dN)(t,e,n)}function Go(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function _r(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{l(r.next(u))}catch(h){o(h)}}function c(u){try{l(r.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((r=r.apply(t,e||[])).next())})}class Pte{constructor(e,n,r,i){this._callback=e,this._type=n,this._minimumUpdateInterval=Math.max(128/(i||44100),.001),this.updateInterval=r,this._createClock()}_createWorker(){const e=new Blob([` - // the initial timeout time - let timeoutTime = ${(this._updateInterval*1e3).toFixed(1)}; - // onmessage callback - self.onmessage = function(msg){ - timeoutTime = parseInt(msg.data); - }; - // the tick function which posts a message - // and schedules a new tick - function tick(){ - setTimeout(tick, timeoutTime); - self.postMessage('tick'); - } - // call tick initially - tick(); - `],{type:"text/javascript"}),n=URL.createObjectURL(e),r=new Worker(n);r.onmessage=this._callback.bind(this),this._worker=r}_createTimeout(){this._timeout=setTimeout(()=>{this._createTimeout(),this._callback()},this._updateInterval*1e3)}_createClock(){if(this._type==="worker")try{this._createWorker()}catch{this._type="timeout",this._createClock()}else this._type==="timeout"&&this._createTimeout()}_disposeClock(){this._timeout&&clearTimeout(this._timeout),this._worker&&(this._worker.terminate(),this._worker.onmessage=null)}get updateInterval(){return this._updateInterval}set updateInterval(e){var n;this._updateInterval=Math.max(e,this._minimumUpdateInterval),this._type==="worker"&&((n=this._worker)===null||n===void 0||n.postMessage(this._updateInterval*1e3))}get type(){return this._type}set type(e){this._disposeClock(),this._type=e,this._createClock()}dispose(){this._disposeClock()}}function Yu(t){return Ate(t)}function Ml(t){return Tte(t)}function h_(t){return Mte(t)}function cf(t){return bte(t)}function Dte(t){return t instanceof WP}function Ute(t,e){return t==="value"||Yu(e)||Ml(e)||Dte(e)}function Vu(t,...e){if(!e.length)return t;const n=e.shift();if(Al(t)&&Al(n))for(const r in n)Ute(r,n[r])?t[r]=n[r]:Al(n[r])?(t[r]||Object.assign(t,{[r]:{}}),Vu(t[r],n[r])):Object.assign(t,{[r]:n[r]});return Vu(t,...e)}function Fte(t,e){return t.length===e.length&&t.every((n,r)=>e[r]===n)}function ct(t,e,n=[],r){const i={},s=Array.from(e);if(Al(s[0])&&r&&!Reflect.has(s[0],r)&&(Object.keys(s[0]).some(a=>Reflect.has(t,a))||(Vu(i,{[r]:s[0]}),n.splice(n.indexOf(r),1),s.shift())),s.length===1&&Al(s[0]))Vu(i,s[0]);else for(let o=0;o{Reflect.has(t,n)&&delete t[n]}),t}/** - * Tone.js - * @author Yotam Mann - * @license http://opensource.org/licenses/MIT MIT License - * @copyright 2014-2024 Yotam Mann - */class $c{constructor(){this.debug=!1,this._wasDisposed=!1}static getDefaults(){return{}}log(...e){(this.debug||Rs&&this.toString()===Rs.TONE_DEBUG_CLASS)&&Nte(this,...e)}dispose(){return this._wasDisposed=!0,this}get disposed(){return this._wasDisposed}toString(){return this.name}}$c.version=fP;const ST=1e-6;function qf(t,e){return t>e+ST}function iw(t,e){return qf(t,e)||wo(t,e)}function Y_(t,e){return t+STthis.memory){const n=this.length-this.memory;this._timeline.splice(0,n)}return this}remove(e){const n=this._timeline.indexOf(e);return n!==-1&&this._timeline.splice(n,1),this}get(e,n="time"){const r=this._search(e,n);return r!==-1?this._timeline[r]:null}peek(){return this._timeline[0]}shift(){return this._timeline.shift()}getAfter(e,n="time"){const r=this._search(e,n);return r+10&&this._timeline[n-1].time=0?this._timeline[r-1]:null}cancel(e){if(this._timeline.length>1){let n=this._search(e);if(n>=0)if(wo(this._timeline[n].time,e)){for(let r=n;r>=0&&wo(this._timeline[r].time,e);r--)n=r;this._timeline=this._timeline.slice(0,n)}else this._timeline=this._timeline.slice(0,n+1);else this._timeline=[]}else this._timeline.length===1&&iw(this._timeline[0].time,e)&&(this._timeline=[]);return this}cancelBefore(e){const n=this._search(e);return n>=0&&(this._timeline=this._timeline.slice(n+1)),this}previousEvent(e){const n=this._timeline.indexOf(e);return n>0?this._timeline[n-1]:null}_search(e,n="time"){if(this._timeline.length===0)return-1;let r=0;const i=this._timeline.length;let s=i;if(i>0&&this._timeline[i-1][n]<=e)return i-1;for(;r=0&&this._timeline[r].time>=e;)r--;return this._iterate(n,r+1),this}forEachAtTime(e,n){const r=this._search(e);if(r!==-1&&wo(this._timeline[r].time,e)){let i=r;for(let s=r;s>=0&&wo(this._timeline[s].time,e);s--)i=s;this._iterate(s=>{n(s)},i,r)}return this}dispose(){return super.dispose(),this._timeline=[],this}}const lD=[];function ly(t){lD.push(t)}function Vte(t){lD.forEach(e=>e(t))}const uD=[];function uy(t){uD.push(t)}function Hte(t){uD.forEach(e=>e(t))}class mm extends $c{constructor(){super(...arguments),this.name="Emitter"}on(e,n){return e.split(/\W+/).forEach(i=>{Ps(this._events)&&(this._events={}),this._events.hasOwnProperty(i)||(this._events[i]=[]),this._events[i].push(n)}),this}once(e,n){const r=(...i)=>{n(...i),this.off(e,r)};return this.on(e,r),this}off(e,n){return e.split(/\W+/).forEach(i=>{if(Ps(this._events)&&(this._events={}),this._events.hasOwnProperty(i))if(Ps(n))this._events[i]=[];else{const s=this._events[i];for(let o=s.length-1;o>=0;o--)s[o]===n&&s.splice(o,1)}}),this}emit(e,...n){if(this._events&&this._events.hasOwnProperty(e)){const r=this._events[e].slice(0);for(let i=0,s=r.length;i{const r=Object.getOwnPropertyDescriptor(mm.prototype,n);Object.defineProperty(e.prototype,n,r)})}dispose(){return super.dispose(),this._events=void 0,this}}class hD extends mm{constructor(){super(...arguments),this.isOffline=!1}toJSON(){return{}}}class gm extends hD{constructor(){var e,n;super(),this.name="Context",this._constants=new Map,this._timeouts=new so,this._timeoutIds=0,this._initialized=!1,this._closeStarted=!1,this.isOffline=!1,this._workletPromise=null;const r=ct(gm.getDefaults(),arguments,["context"]);r.context?(this._context=r.context,this._latencyHint=((e=arguments[0])===null||e===void 0?void 0:e.latencyHint)||""):(this._context=kte({latencyHint:r.latencyHint}),this._latencyHint=r.latencyHint),this._ticker=new Pte(this.emit.bind(this,"tick"),r.clockSource,r.updateInterval,this._context.sampleRate),this.on("tick",this._timeoutLoop.bind(this)),this._context.onstatechange=()=>{this.emit("statechange",this.state)},this[!((n=arguments[0])===null||n===void 0)&&n.hasOwnProperty("updateInterval")?"_lookAhead":"lookAhead"]=r.lookAhead}static getDefaults(){return{clockSource:"worker",latencyHint:"interactive",lookAhead:.1,updateInterval:.05}}initialize(){return this._initialized||(Vte(this),this._initialized=!0),this}createAnalyser(){return this._context.createAnalyser()}createOscillator(){return this._context.createOscillator()}createBufferSource(){return this._context.createBufferSource()}createBiquadFilter(){return this._context.createBiquadFilter()}createBuffer(e,n,r){return this._context.createBuffer(e,n,r)}createChannelMerger(e){return this._context.createChannelMerger(e)}createChannelSplitter(e){return this._context.createChannelSplitter(e)}createConstantSource(){return this._context.createConstantSource()}createConvolver(){return this._context.createConvolver()}createDelay(e){return this._context.createDelay(e)}createDynamicsCompressor(){return this._context.createDynamicsCompressor()}createGain(){return this._context.createGain()}createIIRFilter(e,n){return this._context.createIIRFilter(e,n)}createPanner(){return this._context.createPanner()}createPeriodicWave(e,n,r){return this._context.createPeriodicWave(e,n,r)}createStereoPanner(){return this._context.createStereoPanner()}createWaveShaper(){return this._context.createWaveShaper()}createMediaStreamSource(e){return bt(cf(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamSource(e)}createMediaElementSource(e){return bt(cf(this._context),"Not available if OfflineAudioContext"),this._context.createMediaElementSource(e)}createMediaStreamDestination(){return bt(cf(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamDestination()}decodeAudioData(e){return this._context.decodeAudioData(e)}get currentTime(){return this._context.currentTime}get state(){return this._context.state}get sampleRate(){return this._context.sampleRate}get listener(){return this.initialize(),this._listener}set listener(e){bt(!this._initialized,"The listener cannot be set after initialization."),this._listener=e}get transport(){return this.initialize(),this._transport}set transport(e){bt(!this._initialized,"The transport cannot be set after initialization."),this._transport=e}get draw(){return this.initialize(),this._draw}set draw(e){bt(!this._initialized,"Draw cannot be set after initialization."),this._draw=e}get destination(){return this.initialize(),this._destination}set destination(e){bt(!this._initialized,"The destination cannot be set after initialization."),this._destination=e}createAudioWorkletNode(e,n){return Lte(this.rawContext,e,n)}addAudioWorkletModule(e){return _r(this,void 0,void 0,function*(){bt(Wt(this.rawContext.audioWorklet),"AudioWorkletNode is only available in a secure context (https or localhost)"),this._workletPromise||(this._workletPromise=this.rawContext.audioWorklet.addModule(e)),yield this._workletPromise})}workletsAreReady(){return _r(this,void 0,void 0,function*(){(yield this._workletPromise)?this._workletPromise:Promise.resolve()})}get updateInterval(){return this._ticker.updateInterval}set updateInterval(e){this._ticker.updateInterval=e}get clockSource(){return this._ticker.type}set clockSource(e){this._ticker.type=e}get lookAhead(){return this._lookAhead}set lookAhead(e){this._lookAhead=e,this.updateInterval=e?e/2:.01}get latencyHint(){return this._latencyHint}get rawContext(){return this._context}now(){return this._context.currentTime+this._lookAhead}immediate(){return this._context.currentTime}resume(){return cf(this._context)?this._context.resume():Promise.resolve()}close(){return _r(this,void 0,void 0,function*(){cf(this._context)&&this.state!=="closed"&&!this._closeStarted&&(this._closeStarted=!0,yield this._context.close()),this._initialized&&Hte(this)})}getConstant(e){if(this._constants.has(e))return this._constants.get(e);{const n=this._context.createBuffer(1,128,this._context.sampleRate),r=n.getChannelData(0);for(let s=0;sthis._constants[e].disconnect()),this.close(),this}_timeoutLoop(){const e=this.now();let n=this._timeouts.peek();for(;this._timeouts.length&&n&&n.time<=e;)n.callback(),this._timeouts.shift(),n=this._timeouts.peek()}setTimeout(e,n){this._timeoutIds++;const r=this.now();return this._timeouts.add({callback:e,id:this._timeoutIds,time:r+n}),this._timeoutIds}clearTimeout(e){return this._timeouts.forEach(n=>{n.id===e&&this._timeouts.remove(n)}),this}clearInterval(e){return this.clearTimeout(e)}setInterval(e,n){const r=++this._timeoutIds,i=()=>{const s=this.now();this._timeouts.add({callback:()=>{e(),i()},id:r,time:s+n})};return i(),r}}class Gte extends hD{constructor(){super(...arguments),this.lookAhead=0,this.latencyHint=0,this.isOffline=!1}createAnalyser(){return{}}createOscillator(){return{}}createBufferSource(){return{}}createBiquadFilter(){return{}}createBuffer(e,n,r){return{}}createChannelMerger(e){return{}}createChannelSplitter(e){return{}}createConstantSource(){return{}}createConvolver(){return{}}createDelay(e){return{}}createDynamicsCompressor(){return{}}createGain(){return{}}createIIRFilter(e,n){return{}}createPanner(){return{}}createPeriodicWave(e,n,r){return{}}createStereoPanner(){return{}}createWaveShaper(){return{}}createMediaStreamSource(e){return{}}createMediaElementSource(e){return{}}createMediaStreamDestination(){return{}}decodeAudioData(e){return Promise.resolve({})}createAudioWorkletNode(e,n){return{}}get rawContext(){return{}}addAudioWorkletModule(e){return _r(this,void 0,void 0,function*(){return Promise.resolve()})}resume(){return Promise.resolve()}setTimeout(e,n){return 0}clearTimeout(e){return this}setInterval(e,n){return 0}clearInterval(e){return this}getConstant(e){return{}}get currentTime(){return 0}get state(){return{}}get sampleRate(){return 0}get listener(){return{}}get transport(){return{}}get draw(){return{}}set draw(e){}get destination(){return{}}set destination(e){}now(){return 0}immediate(){return 0}}function Zt(t,e){us(e)?e.forEach(n=>Zt(t,n)):Object.defineProperty(t,e,{enumerable:!0,writable:!1})}function _m(t,e){us(e)?e.forEach(n=>_m(t,n)):Object.defineProperty(t,e,{writable:!0})}const En=()=>{};class An extends $c{constructor(){super(),this.name="ToneAudioBuffer",this.onload=En;const e=ct(An.getDefaults(),arguments,["url","onload","onerror"]);this.reverse=e.reverse,this.onload=e.onload,Lc(e.url)?this.load(e.url).catch(e.onerror):e.url&&this.set(e.url)}static getDefaults(){return{onerror:En,onload:En,reverse:!1}}get sampleRate(){return this._buffer?this._buffer.sampleRate:Vi().sampleRate}set(e){return e instanceof An?e.loaded?this._buffer=e.get():e.onload=()=>{this.set(e),this.onload(this)}:this._buffer=e,this._reversed&&this._reverse(),this}get(){return this._buffer}load(e){return _r(this,void 0,void 0,function*(){const n=An.load(e).then(r=>{this.set(r),this.onload(this)});An.downloads.push(n);try{yield n}finally{const r=An.downloads.indexOf(n);An.downloads.splice(r,1)}return this})}dispose(){return super.dispose(),this._buffer=void 0,this}fromArray(e){const n=us(e)&&e[0].length>0,r=n?e.length:1,i=n?e[0].length:e.length,s=Vi(),o=s.createBuffer(r,i,s.sampleRate),a=!n&&r===1?[e]:e;for(let c=0;ci/r),this.fromArray(n)}return this}toArray(e){if(Po(e))return this.getChannelData(e);if(this.numberOfChannels===1)return this.toArray(0);{const n=[];for(let r=0;r0}get duration(){return this._buffer?this._buffer.duration:0}get length(){return this._buffer?this._buffer.length:0}get numberOfChannels(){return this._buffer?this._buffer.numberOfChannels:0}get reverse(){return this._reversed}set reverse(e){this._reversed!==e&&(this._reversed=e,this._reverse())}static fromArray(e){return new An().fromArray(e)}static fromUrl(e){return _r(this,void 0,void 0,function*(){return yield new An().load(e)})}static load(e){return _r(this,void 0,void 0,function*(){const n=e.match(/\[([^\]\[]+\|.+)\]$/);if(n){const c=n[1].split("|");let l=c[0];for(const u of c)if(An.supportsType(u)){l=u;break}e=e.replace(n[0],l)}const r=An.baseUrl===""||An.baseUrl.endsWith("/")?An.baseUrl:An.baseUrl+"/",i=document.createElement("a");i.href=r+e,i.pathname=(i.pathname+i.hash).split("/").map(encodeURIComponent).join("/");const s=yield fetch(i.href);if(!s.ok)throw new Error(`could not load url: ${e}`);const o=yield s.arrayBuffer();return yield Vi().decodeAudioData(o)})}static supportsType(e){const n=e.split("."),r=n[n.length-1];return document.createElement("audio").canPlayType("audio/"+r)!==""}static loaded(){return _r(this,void 0,void 0,function*(){for(yield Promise.resolve();An.downloads.length;)yield An.downloads[0]})}}An.baseUrl="";An.downloads=[];class hy extends gm{constructor(){super({clockSource:"offline",context:h_(arguments[0])?arguments[0]:Ite(arguments[0],arguments[1]*arguments[2],arguments[2]),lookAhead:0,updateInterval:h_(arguments[0])?128/arguments[0].sampleRate:128/arguments[2]}),this.name="OfflineContext",this._currentTime=0,this.isOffline=!0,this._duration=h_(arguments[0])?arguments[0].length/arguments[0].sampleRate:arguments[1]}now(){return this._currentTime}get currentTime(){return this._currentTime}_renderClock(e){return _r(this,void 0,void 0,function*(){let n=0;for(;this._duration-this._currentTime>=0;){this.emit("tick"),this._currentTime+=128/this.sampleRate,n++;const r=Math.floor(this.sampleRate/128);e&&n%r===0&&(yield new Promise(i=>setTimeout(i,1)))}})}render(){return _r(this,arguments,void 0,function*(e=!0){yield this.workletsAreReady(),yield this._renderClock(e);const n=yield this._context.startRendering();return new An(n)})}close(){return Promise.resolve()}}const fD=new Gte;let Du=fD;function Vi(){return Du===fD&&Ote&&Wte(new gm),Du}function Wte(t,e=!1){e&&Du.dispose(),cf(t)?Du=new gm(t):h_(t)?Du=new hy(t):Du=t}function jte(){return Du.resume()}if(Rs&&!Rs.TONE_SILENCE_LOGGING){const e=` * Tone.js v${fP} * `;console.log(`%c${e}`,"background: #000; color: #fff")}function $te(t){return Math.pow(10,t/20)}function qte(t){return 20*(Math.log(t)/Math.LN10)}function dD(t){return Math.pow(2,t/12)}let fy=440;function Xte(){return fy}function Kte(t){fy=t}function Uu(t){return Math.round(pD(t))}function pD(t){return 69+12*Math.log2(t/fy)}function mD(t){return fy*Math.pow(2,(t-69)/12)}class ET extends $c{constructor(e,n,r){super(),this.defaultUnits="s",this._val=n,this._units=r,this.context=e,this._expressions=this._getExpressions()}_getExpressions(){return{hz:{method:e=>this._frequencyToUnits(parseFloat(e)),regexp:/^(\d+(?:\.\d+)?)hz$/i},i:{method:e=>this._ticksToUnits(parseInt(e,10)),regexp:/^(\d+)i$/i},m:{method:e=>this._beatsToUnits(parseInt(e,10)*this._getTimeSignature()),regexp:/^(\d+)m$/i},n:{method:(e,n)=>{const r=parseInt(e,10),i=n==="."?1.5:1;return r===1?this._beatsToUnits(this._getTimeSignature())*i:this._beatsToUnits(4/r)*i},regexp:/^(\d+)n(\.?)$/i},number:{method:e=>this._expressions[this.defaultUnits].method.call(this,e),regexp:/^(\d+(?:\.\d+)?)$/},s:{method:e=>this._secondsToUnits(parseFloat(e)),regexp:/^(\d+(?:\.\d+)?)s$/},samples:{method:e=>parseInt(e,10)/this.context.sampleRate,regexp:/^(\d+)samples$/},t:{method:e=>{const n=parseInt(e,10);return this._beatsToUnits(8/(Math.floor(n)*3))},regexp:/^(\d+)t$/i},tr:{method:(e,n,r)=>{let i=0;return e&&e!=="0"&&(i+=this._beatsToUnits(this._getTimeSignature()*parseFloat(e))),n&&n!=="0"&&(i+=this._beatsToUnits(parseFloat(n))),r&&r!=="0"&&(i+=this._beatsToUnits(parseFloat(r)/4)),i},regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?$/}}}valueOf(){if(this._val instanceof ET&&this.fromType(this._val),Ps(this._val))return this._noArg();if(Lc(this._val)&&Ps(this._units)){for(const e in this._expressions)if(this._expressions[e].regexp.test(this._val.trim())){this._units=e;break}}else if(Al(this._val)){let e=0;for(const n in this._val)if(Wt(this._val[n])){const r=this._val[n],i=new this.constructor(this.context,n).valueOf()*r;e+=i}return e}if(Wt(this._units)){const e=this._expressions[this._units],n=this._val.toString().trim().match(e.regexp);return n?e.method.apply(this,n.slice(1)):e.method.call(this,this._val)}else return Lc(this._val)?parseFloat(this._val):this._val}_frequencyToUnits(e){return 1/e}_beatsToUnits(e){return 60/this._getBpm()*e}_secondsToUnits(e){return e}_ticksToUnits(e){return e*this._beatsToUnits(1)/this._getPPQ()}_noArg(){return this._now()}_getBpm(){return this.context.transport.bpm.value}_getTimeSignature(){return this.context.transport.timeSignature}_getPPQ(){return this.context.transport.PPQ}fromType(e){switch(this._units=void 0,this.defaultUnits){case"s":this._val=e.toSeconds();break;case"i":this._val=e.toTicks();break;case"hz":this._val=e.toFrequency();break;case"midi":this._val=e.toMidi();break}return this}toFrequency(){return 1/this.toSeconds()}toSamples(){return this.toSeconds()*this.context.sampleRate}toMilliseconds(){return this.toSeconds()*1e3}}class no extends ET{constructor(){super(...arguments),this.name="TimeClass"}_getExpressions(){return Object.assign(super._getExpressions(),{now:{method:e=>this._now()+new this.constructor(this.context,e).valueOf(),regexp:/^\+(.+)/},quantize:{method:e=>{const n=new no(this.context,e).valueOf();return this._secondsToUnits(this.context.transport.nextSubdivision(n))},regexp:/^@(.+)/}})}quantize(e,n=1){const r=new this.constructor(this.context,e).valueOf(),i=this.valueOf(),a=Math.round(i/r)*r-i;return i+a*n}toNotation(){const e=this.toSeconds(),n=["1m"];for(let s=1;s<9;s++){const o=Math.pow(2,s);n.push(o+"n."),n.push(o+"n"),n.push(o+"t")}n.push("0");let r=n[0],i=new no(this.context,n[0]).toSeconds();return n.forEach(s=>{const o=new no(this.context,s).toSeconds();Math.abs(o-e)3&&(i=parseFloat(parseFloat(s).toFixed(3))),[r,n,i].join(":")}toTicks(){const e=this._beatsToUnits(1);return this.valueOf()/e*this._getPPQ()}toSeconds(){return this.valueOf()}toMidi(){return Uu(this.toFrequency())}_now(){return this.context.now()}}function Ir(t,e){return new no(Vi(),t,e)}class ss extends no{constructor(){super(...arguments),this.name="Frequency",this.defaultUnits="hz"}static get A4(){return Xte()}static set A4(e){Kte(e)}_getExpressions(){return Object.assign({},super._getExpressions(),{midi:{regexp:/^(\d+(?:\.\d+)?midi)/,method(e){return this.defaultUnits==="midi"?e:ss.mtof(e)}},note:{regexp:/^([a-g]{1}(?:b|#|##|x|bb|###|#x|x#|bbb)?)(-?[0-9]+)/i,method(e,n){const i=Yte[e.toLowerCase()]+(parseInt(n,10)+1)*12;return this.defaultUnits==="midi"?i:ss.mtof(i)}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method(e,n,r){let i=1;return e&&e!=="0"&&(i*=this._beatsToUnits(this._getTimeSignature()*parseFloat(e))),n&&n!=="0"&&(i*=this._beatsToUnits(parseFloat(n))),r&&r!=="0"&&(i*=this._beatsToUnits(parseFloat(r)/4)),i}}})}transpose(e){return new ss(this.context,this.valueOf()*dD(e))}harmonize(e){return e.map(n=>this.transpose(n))}toMidi(){return Uu(this.valueOf())}toNote(){const e=this.toFrequency(),n=Math.log2(e/ss.A4);let r=Math.round(12*n)+57;const i=Math.floor(r/12);return i<0&&(r+=-12*i),Zte[r%12]+i.toString()}toSeconds(){return 1/super.toSeconds()}toTicks(){const e=this._beatsToUnits(1),n=this.valueOf()/e;return Math.floor(n*this._getPPQ())}_noArg(){return 0}_frequencyToUnits(e){return e}_ticksToUnits(e){return 1/(e*60/(this._getBpm()*this._getPPQ()))}_beatsToUnits(e){return 1/super._beatsToUnits(e)}_secondsToUnits(e){return 1/e}static mtof(e){return mD(e)}static ftom(e){return Uu(e)}}const Yte={cbbb:-3,cbb:-2,cb:-1,c:0,"c#":1,cx:2,"c##":2,"c###":3,"cx#":3,"c#x":3,dbbb:-1,dbb:0,db:1,d:2,"d#":3,dx:4,"d##":4,"d###":5,"dx#":5,"d#x":5,ebbb:1,ebb:2,eb:3,e:4,"e#":5,ex:6,"e##":6,"e###":7,"ex#":7,"e#x":7,fbbb:2,fbb:3,fb:4,f:5,"f#":6,fx:7,"f##":7,"f###":8,"fx#":8,"f#x":8,gbbb:4,gbb:5,gb:6,g:7,"g#":8,gx:9,"g##":9,"g###":10,"gx#":10,"g#x":10,abbb:6,abb:7,ab:8,a:9,"a#":10,ax:11,"a##":11,"a###":12,"ax#":12,"a#x":12,bbbb:8,bbb:9,bb:10,b:11,"b#":12,bx:13,"b##":13,"b###":14,"bx#":14,"b#x":14},Zte=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function gN(t,e){return new ss(Vi(),t,e)}class Mf extends no{constructor(){super(...arguments),this.name="TransportTime"}_now(){return this.context.transport.seconds}}class Ei extends $c{constructor(){super();const e=ct(Ei.getDefaults(),arguments,["context"]);this.defaultContext?this.context=this.defaultContext:this.context=e.context}static getDefaults(){return{context:Vi()}}now(){return this.context.currentTime+this.context.lookAhead}immediate(){return this.context.currentTime}get sampleTime(){return 1/this.context.sampleRate}get blockTime(){return 128/this.context.sampleRate}toSeconds(e){return Rte(e),new no(this.context,e).toSeconds()}toFrequency(e){return new ss(this.context,e).toFrequency()}toTicks(e){return new Mf(this.context,e).toTicks()}_getPartialProperties(e){const n=this.get();return Object.keys(n).forEach(r=>{Ps(e[r])&&delete n[r]}),n}get(){const e=Bte(this);return Object.keys(e).forEach(n=>{if(Reflect.has(this,n)){const r=this[n];Wt(r)&&Wt(r.value)&&Wt(r.setValueAtTime)?e[n]=r.value:r instanceof Ei?e[n]=r._getPartialProperties(e[n]):us(r)||Po(r)||Lc(r)||sD(r)?e[n]=r:delete e[n]}}),e}set(e){return Object.keys(e).forEach(n=>{Reflect.has(this,n)&&Wt(this[n])&&(this[n]&&Wt(this[n].value)&&Wt(this[n].setValueAtTime)?this[n].value!==e[n]&&(this[n].value=e[n]):this[n]instanceof Ei?this[n].set(e[n]):this[n]=e[n])}),this}}class vm extends so{constructor(e="stopped"){super(),this.name="StateTimeline",this._initial=e,this.setStateAtTime(this._initial,0)}getValueAtTime(e){const n=this.get(e);return n!==null?n.state:this._initial}setStateAtTime(e,n,r){return Aa(n,0),this.add(Object.assign({},r,{state:e,time:n})),this}getLastState(e,n){const r=this._search(n);for(let i=r;i>=0;i--){const s=this._timeline[i];if(s.state===e)return s}}getNextState(e,n){const r=this._search(n);if(r!==-1)for(let i=r;i0,"timeConstant must be a number greater than 0");const s=this.toSeconds(n);return this._assertRange(i),bt(isFinite(i)&&isFinite(s),`Invalid argument(s) to setTargetAtTime: ${JSON.stringify(e)}, ${JSON.stringify(n)}`),this._events.add({constant:r,time:s,type:"setTargetAtTime",value:i}),this.log(this.units,"setTargetAtTime",e,s,r),this._param.setTargetAtTime(i,s,r),this}setValueCurveAtTime(e,n,r,i=1){r=this.toSeconds(r),n=this.toSeconds(n);const s=this._fromType(e[0])*i;this.setValueAtTime(this._toType(s),n);const o=r/(e.length-1);for(let a=1;a{i.type==="cancelScheduledValues"?e.cancelScheduledValues(i.time):i.type==="setTargetAtTime"?e.setTargetAtTime(i.value,i.time,i.constant):e[i.type](i.value,i.time)}),this}setParam(e){bt(this._swappable,"The Param must be assigned as 'swappable' in the constructor");const n=this.input;return n.disconnect(this._param),this.apply(e),this._param=e,n.connect(this._param),this}dispose(){return super.dispose(),this._events.dispose(),this}get defaultValue(){return this._toType(this._param.defaultValue)}_exponentialApproach(e,n,r,i,s){return r+(n-r)*Math.exp(-(s-e)/i)}_linearInterpolate(e,n,r,i,s){return n+(i-n)*((s-e)/(r-e))}_exponentialInterpolate(e,n,r,i,s){return n*Math.pow(i/n,(s-e)/(r-e))}}class ft extends Ei{constructor(){super(...arguments),this._internalChannels=[]}get numberOfInputs(){return Wt(this.input)?Yu(this.input)||this.input instanceof Xt?1:this.input.numberOfInputs:0}get numberOfOutputs(){return Wt(this.output)?this.output.numberOfOutputs:0}_isAudioNode(e){return Wt(e)&&(e instanceof ft||Ml(e))}_getInternalNodes(){const e=this._internalChannels.slice(0);return this._isAudioNode(this.input)&&e.push(this.input),this._isAudioNode(this.output)&&this.input!==this.output&&e.push(this.output),e}_setChannelProperties(e){this._getInternalNodes().forEach(r=>{r.channelCount=e.channelCount,r.channelCountMode=e.channelCountMode,r.channelInterpretation=e.channelInterpretation})}_getChannelProperties(){const e=this._getInternalNodes();bt(e.length>0,"ToneAudioNode does not have any internal nodes");const n=e[0];return{channelCount:n.channelCount,channelCountMode:n.channelCountMode,channelInterpretation:n.channelInterpretation}}get channelCount(){return this._getChannelProperties().channelCount}set channelCount(e){const n=this._getChannelProperties();this._setChannelProperties(Object.assign(n,{channelCount:e}))}get channelCountMode(){return this._getChannelProperties().channelCountMode}set channelCountMode(e){const n=this._getChannelProperties();this._setChannelProperties(Object.assign(n,{channelCountMode:e}))}get channelInterpretation(){return this._getChannelProperties().channelInterpretation}set channelInterpretation(e){const n=this._getChannelProperties();this._setChannelProperties(Object.assign(n,{channelInterpretation:e}))}connect(e,n=0,r=0){return Do(this,e,n,r),this}toDestination(){return this.connect(this.context.destination),this}toMaster(){return cy("toMaster() has been renamed toDestination()"),this.toDestination()}disconnect(e,n=0,r=0){return gD(this,e,n,r),this}chain(...e){return Zu(this,...e),this}fan(...e){return e.forEach(n=>this.connect(n)),this}dispose(){return super.dispose(),Wt(this.input)&&(this.input instanceof ft?this.input.dispose():Ml(this.input)&&this.input.disconnect()),Wt(this.output)&&(this.output instanceof ft?this.output.dispose():Ml(this.output)&&this.output.disconnect()),this._internalChannels=[],this}}function Zu(...t){const e=t.shift();t.reduce((n,r)=>(n instanceof ft?n.connect(r):Ml(n)&&Do(n,r),r),e)}function Do(t,e,n=0,r=0){for(bt(Wt(t),"Cannot connect from undefined node"),bt(Wt(e),"Cannot connect to undefined node"),(e instanceof ft||Ml(e))&&bt(e.numberOfInputs>0,"Cannot connect to node with no inputs"),bt(t.numberOfOutputs>0,"Cannot connect from node with no outputs");e instanceof ft||e instanceof Xt;)Wt(e.input)&&(e=e.input);for(;t instanceof ft;)Wt(t.output)&&(t=t.output);Yu(e)?t.connect(e,n):t.connect(e,n,r)}function gD(t,e,n=0,r=0){if(Wt(e))for(;e instanceof ft;)e=e.input;for(;!Ml(t);)Wt(t.output)&&(t=t.output);Yu(e)?t.disconnect(e,n):Ml(e)?t.disconnect(e,n,r):t.disconnect()}class jt extends ft{constructor(){const e=ct(jt.getDefaults(),arguments,["gain","units"]);super(e),this.name="Gain",this._gainNode=this.context.createGain(),this.input=this._gainNode,this.output=this._gainNode,this.gain=new Xt({context:this.context,convert:e.convert,param:this._gainNode.gain,units:e.units,value:e.gain,minValue:e.minValue,maxValue:e.maxValue}),Zt(this,"gain")}static getDefaults(){return Object.assign(ft.getDefaults(),{convert:!0,gain:1,units:"gain"})}dispose(){return super.dispose(),this._gainNode.disconnect(),this.gain.dispose(),this}}class Xf extends ft{constructor(e){super(e),this.onended=En,this._startTime=-1,this._stopTime=-1,this._timeout=-1,this.output=new jt({context:this.context,gain:0}),this._gainNode=this.output,this.getStateAtTime=function(n){const r=this.toSeconds(n);return this._startTime!==-1&&r>=this._startTime&&(this._stopTime===-1||r<=this._stopTime)?"started":"stopped"},this._fadeIn=e.fadeIn,this._fadeOut=e.fadeOut,this._curve=e.curve,this.onended=e.onended}static getDefaults(){return Object.assign(ft.getDefaults(),{curve:"linear",fadeIn:0,fadeOut:0,onended:En})}_startGain(e,n=1){bt(this._startTime===-1,"Source cannot be started more than once");const r=this.toSeconds(this._fadeIn);return this._startTime=e+r,this._startTime=Math.max(this._startTime,this.context.currentTime),r>0?(this._gainNode.gain.setValueAtTime(0,e),this._curve==="linear"?this._gainNode.gain.linearRampToValueAtTime(n,e+r):this._gainNode.gain.exponentialApproachValueAtTime(n,e,r)):this._gainNode.gain.setValueAtTime(n,e),this}stop(e){return this.log("stop",e),this._stopGain(this.toSeconds(e)),this}_stopGain(e){bt(this._startTime!==-1,"'start' must be called before 'stop'"),this.cancelStop();const n=this.toSeconds(this._fadeOut);return this._stopTime=this.toSeconds(e)+n,this._stopTime=Math.max(this._stopTime,this.now()),n>0?this._curve==="linear"?this._gainNode.gain.linearRampTo(0,n,e):this._gainNode.gain.targetRampTo(0,n,e):(this._gainNode.gain.cancelAndHoldAtTime(e),this._gainNode.gain.setValueAtTime(0,e)),this.context.clearTimeout(this._timeout),this._timeout=this.context.setTimeout(()=>{const r=this._curve==="exponential"?n*2:0;this._stopSource(this.now()+r),this._onended()},this._stopTime-this.context.currentTime),this}_onended(){if(this.onended!==En&&(this.onended(this),this.onended=En,!this.context.isOffline)){const e=()=>this.dispose();typeof window.requestIdleCallback<"u"?window.requestIdleCallback(e):setTimeout(e,1e3)}}get state(){return this.getStateAtTime(this.now())}cancelStop(){return this.log("cancelStop"),bt(this._startTime!==-1,"Source is not started"),this._gainNode.gain.cancelScheduledValues(this._startTime+this.sampleTime),this.context.clearTimeout(this._timeout),this._stopTime=-1,this}dispose(){return super.dispose(),this._gainNode.dispose(),this.onended=En,this}}class wT extends Xf{constructor(){const e=ct(wT.getDefaults(),arguments,["offset"]);super(e),this.name="ToneConstantSource",this._source=this.context.createConstantSource(),Do(this._source,this._gainNode),this.offset=new Xt({context:this.context,convert:e.convert,param:this._source.offset,units:e.units,value:e.offset,minValue:e.minValue,maxValue:e.maxValue})}static getDefaults(){return Object.assign(Xf.getDefaults(),{convert:!0,offset:1,units:"number"})}start(e){const n=this.toSeconds(e);return this.log("start",n),this._startGain(n),this._source.start(n),this}_stopSource(e){this._source.stop(e)}dispose(){return super.dispose(),this.state==="started"&&this.stop(),this._source.disconnect(),this.offset.dispose(),this}}class yn extends ft{constructor(){const e=ct(yn.getDefaults(),arguments,["value","units"]);super(e),this.name="Signal",this.override=!0,this.output=this._constantSource=new wT({context:this.context,convert:e.convert,offset:e.value,units:e.units,minValue:e.minValue,maxValue:e.maxValue}),this._constantSource.start(0),this.input=this._param=this._constantSource.offset}static getDefaults(){return Object.assign(ft.getDefaults(),{convert:!0,units:"number",value:0})}connect(e,n=0,r=0){return dy(this,e,n,r),this}dispose(){return super.dispose(),this._param.dispose(),this._constantSource.dispose(),this}setValueAtTime(e,n){return this._param.setValueAtTime(e,n),this}getValueAtTime(e){return this._param.getValueAtTime(e)}setRampPoint(e){return this._param.setRampPoint(e),this}linearRampToValueAtTime(e,n){return this._param.linearRampToValueAtTime(e,n),this}exponentialRampToValueAtTime(e,n){return this._param.exponentialRampToValueAtTime(e,n),this}exponentialRampTo(e,n,r){return this._param.exponentialRampTo(e,n,r),this}linearRampTo(e,n,r){return this._param.linearRampTo(e,n,r),this}targetRampTo(e,n,r){return this._param.targetRampTo(e,n,r),this}exponentialApproachValueAtTime(e,n,r){return this._param.exponentialApproachValueAtTime(e,n,r),this}setTargetAtTime(e,n,r){return this._param.setTargetAtTime(e,n,r),this}setValueCurveAtTime(e,n,r,i){return this._param.setValueCurveAtTime(e,n,r,i),this}cancelScheduledValues(e){return this._param.cancelScheduledValues(e),this}cancelAndHoldAtTime(e){return this._param.cancelAndHoldAtTime(e),this}rampTo(e,n,r){return this._param.rampTo(e,n,r),this}get value(){return this._param.value}set value(e){this._param.value=e}get convert(){return this._param.convert}set convert(e){this._param.convert=e}get units(){return this._param.units}get overridden(){return this._param.overridden}set overridden(e){this._param.overridden=e}get maxValue(){return this._param.maxValue}get minValue(){return this._param.minValue}apply(e){return this._param.apply(e),this}}function dy(t,e,n,r){(e instanceof Xt||Yu(e)||e instanceof yn&&e.override)&&(e.cancelScheduledValues(0),e.setValueAtTime(0,0),e instanceof yn&&(e.overridden=!0)),Do(t,e,n,r)}class bT extends Xt{constructor(){const e=ct(bT.getDefaults(),arguments,["value"]);super(e),this.name="TickParam",this._events=new so(1/0),this._multiplier=1,this._multiplier=e.multiplier,this._events.cancel(0),this._events.add({ticks:0,time:0,type:"setValueAtTime",value:this._fromType(e.value)}),this.setValueAtTime(e.value,0)}static getDefaults(){return Object.assign(Xt.getDefaults(),{multiplier:1,units:"hertz",value:1})}setTargetAtTime(e,n,r){n=this.toSeconds(n),this.setRampPoint(n);const i=this._fromType(e),s=this._events.get(n),o=Math.round(Math.max(1/r,1));for(let a=0;a<=o;a++){const c=r*a+n,l=this._exponentialApproach(s.time,s.value,i,r,c);this.linearRampToValueAtTime(this._toType(l),c)}return this}setValueAtTime(e,n){const r=this.toSeconds(n);super.setValueAtTime(e,n);const i=this._events.get(r),s=this._events.previousEvent(i),o=this._getTicksUntilEvent(s,r);return i.ticks=Math.max(o,0),this}linearRampToValueAtTime(e,n){const r=this.toSeconds(n);super.linearRampToValueAtTime(e,n);const i=this._events.get(r),s=this._events.previousEvent(i),o=this._getTicksUntilEvent(s,r);return i.ticks=Math.max(o,0),this}exponentialRampToValueAtTime(e,n){n=this.toSeconds(n);const r=this._fromType(e),i=this._events.get(n),s=Math.round(Math.max((n-i.time)*10,1)),o=(n-i.time)/s;for(let a=0;a<=s;a++){const c=o*a+i.time,l=this._exponentialInterpolate(i.time,i.value,n,r,c);this.linearRampToValueAtTime(this._toType(l),c)}return this}_getTicksUntilEvent(e,n){if(e===null)e={ticks:0,time:0,type:"setValueAtTime",value:0};else if(Ps(e.ticks)){const o=this._events.previousEvent(e);e.ticks=this._getTicksUntilEvent(o,e.time)}const r=this._fromType(this.getValueAtTime(e.time));let i=this._fromType(this.getValueAtTime(n));const s=this._events.get(n);return s&&s.time===n&&s.type==="setValueAtTime"&&(i=this._fromType(this.getValueAtTime(n-this.sampleTime))),.5*(n-e.time)*(r+i)+e.ticks}getTicksAtTime(e){const n=this.toSeconds(e),r=this._events.get(n);return Math.max(this._getTicksUntilEvent(r,n),0)}getDurationOfTicks(e,n){const r=this.toSeconds(n),i=this.getTicksAtTime(n);return this.getTimeOfTick(i+e)-r}getTimeOfTick(e){const n=this._events.get(e,"ticks"),r=this._events.getAfter(e,"ticks");if(n&&n.ticks===e)return n.time;if(n&&r&&r.type==="linearRampToValueAtTime"&&n.value!==r.value){const i=this._fromType(this.getValueAtTime(n.time)),o=(this._fromType(this.getValueAtTime(r.time))-i)/(r.time-n.time),a=Math.sqrt(Math.pow(i,2)-2*o*(n.ticks-e)),c=(-i+a)/o,l=(-i-a)/o;return(c>0?c:l)+n.time}else return n?n.value===0?1/0:n.time+(e-n.ticks)/n.value:e/this._initialValue}ticksToTime(e,n){return this.getDurationOfTicks(e,n)}timeToTicks(e,n){const r=this.toSeconds(n),i=this.toSeconds(e),s=this.getTicksAtTime(r);return this.getTicksAtTime(r+i)-s}_fromType(e){return this.units==="bpm"&&this.multiplier?1/(60/e/this.multiplier):super._fromType(e)}_toType(e){return this.units==="bpm"&&this.multiplier?e/this.multiplier*60:super._toType(e)}get multiplier(){return this._multiplier}set multiplier(e){const n=this.value;this._multiplier=e,this.cancelScheduledValues(0),this.setValueAtTime(n,0)}}class TT extends yn{constructor(){const e=ct(TT.getDefaults(),arguments,["value"]);super(e),this.name="TickSignal",this.input=this._param=new bT({context:this.context,convert:e.convert,multiplier:e.multiplier,param:this._constantSource.offset,units:e.units,value:e.value})}static getDefaults(){return Object.assign(yn.getDefaults(),{multiplier:1,units:"hertz",value:1})}ticksToTime(e,n){return this._param.ticksToTime(e,n)}timeToTicks(e,n){return this._param.timeToTicks(e,n)}getTimeOfTick(e){return this._param.getTimeOfTick(e)}getDurationOfTicks(e,n){return this._param.getDurationOfTicks(e,n)}getTicksAtTime(e){return this._param.getTicksAtTime(e)}get multiplier(){return this._param.multiplier}set multiplier(e){this._param.multiplier=e}dispose(){return super.dispose(),this._param.dispose(),this}}class AT extends Ei{constructor(){const e=ct(AT.getDefaults(),arguments,["frequency"]);super(e),this.name="TickSource",this._state=new vm,this._tickOffset=new so,this._ticksAtTime=new so,this._secondsAtTime=new so,this.frequency=new TT({context:this.context,units:e.units,value:e.frequency}),Zt(this,"frequency"),this._state.setStateAtTime("stopped",0),this.setTicksAtTime(0,0)}static getDefaults(){return Object.assign({frequency:1,units:"hertz"},Ei.getDefaults())}get state(){return this.getStateAtTime(this.now())}start(e,n){const r=this.toSeconds(e);return this._state.getValueAtTime(r)!=="started"&&(this._state.setStateAtTime("started",r),Wt(n)&&this.setTicksAtTime(n,r),this._ticksAtTime.cancel(r),this._secondsAtTime.cancel(r)),this}stop(e){const n=this.toSeconds(e);if(this._state.getValueAtTime(n)==="stopped"){const r=this._state.get(n);r&&r.time>0&&(this._tickOffset.cancel(r.time),this._state.cancel(r.time))}return this._state.cancel(n),this._state.setStateAtTime("stopped",n),this.setTicksAtTime(0,n),this._ticksAtTime.cancel(n),this._secondsAtTime.cancel(n),this}pause(e){const n=this.toSeconds(e);return this._state.getValueAtTime(n)==="started"&&(this._state.setStateAtTime("paused",n),this._ticksAtTime.cancel(n),this._secondsAtTime.cancel(n)),this}cancel(e){return e=this.toSeconds(e),this._state.cancel(e),this._tickOffset.cancel(e),this._ticksAtTime.cancel(e),this._secondsAtTime.cancel(e),this}getTicksAtTime(e){const n=this.toSeconds(e),r=this._state.getLastState("stopped",n),i=this._ticksAtTime.get(n),s={state:"paused",time:n};this._state.add(s);let o=i||r,a=i?i.ticks:0,c=null;return this._state.forEachBetween(o.time,n+this.sampleTime,l=>{let u=o.time;const h=this._tickOffset.get(l.time);h&&h.time>=o.time&&(a=h.ticks,u=h.time),o.state==="started"&&l.state!=="started"&&(a+=this.frequency.getTicksAtTime(l.time)-this.frequency.getTicksAtTime(u),l.time!==s.time&&(c={state:l.state,time:l.time,ticks:a})),o=l}),this._state.remove(s),c&&this._ticksAtTime.add(c),a}get ticks(){return this.getTicksAtTime(this.now())}set ticks(e){this.setTicksAtTime(e,this.now())}get seconds(){return this.getSecondsAtTime(this.now())}set seconds(e){const n=this.now(),r=this.frequency.timeToTicks(e,n);this.setTicksAtTime(r,n)}getSecondsAtTime(e){e=this.toSeconds(e);const n=this._state.getLastState("stopped",e),r={state:"paused",time:e};this._state.add(r);const i=this._secondsAtTime.get(e);let s=i||n,o=i?i.seconds:0,a=null;return this._state.forEachBetween(s.time,e+this.sampleTime,c=>{let l=s.time;const u=this._tickOffset.get(c.time);u&&u.time>=s.time&&(o=u.seconds,l=u.time),s.state==="started"&&c.state!=="started"&&(o+=c.time-l,c.time!==r.time&&(a={state:c.state,time:c.time,seconds:o})),s=c}),this._state.remove(r),a&&this._secondsAtTime.add(a),o}setTicksAtTime(e,n){return n=this.toSeconds(n),this._tickOffset.cancel(n),this._tickOffset.add({seconds:this.frequency.getDurationOfTicks(e,n),ticks:e,time:n}),this._ticksAtTime.cancel(n),this._secondsAtTime.cancel(n),this}getStateAtTime(e){return e=this.toSeconds(e),this._state.getValueAtTime(e)}getTimeOfTick(e,n=this.now()){const r=this._tickOffset.get(n),i=this._state.get(n),s=Math.max(r.time,i.time),o=this.frequency.getTicksAtTime(s)+e-r.ticks;return this.frequency.getTimeOfTick(o)}forEachTickBetween(e,n,r){let i=this._state.get(e);this._state.forEachBetween(e,n,o=>{i&&i.state==="started"&&o.state!=="started"&&this.forEachTickBetween(Math.max(i.time,e),o.time-this.sampleTime,r),i=o});let s=null;if(i&&i.state==="started"){const o=Math.max(i.time,e),a=this.frequency.getTicksAtTime(o),c=this.frequency.getTicksAtTime(i.time),l=a-c;let u=Math.ceil(l)-l;u=wo(u,1)?0:u;let h=this.frequency.getTimeOfTick(a+u);for(;h{switch(r.state){case"started":const i=this._tickSource.getTicksAtTime(r.time);this.emit("start",r.time,i);break;case"stopped":r.time!==0&&this.emit("stop",r.time);break;case"paused":this.emit("pause",r.time);break}}),this._tickSource.forEachTickBetween(e,n,(r,i)=>{this.callback(r,i)}))}getStateAtTime(e){const n=this.toSeconds(e);return this._state.getValueAtTime(n)}dispose(){return super.dispose(),this.context.off("tick",this._boundLoop),this._tickSource.dispose(),this._state.dispose(),this}}mm.mixin(py);class Kf extends ft{constructor(){const e=ct(Kf.getDefaults(),arguments,["delayTime","maxDelay"]);super(e),this.name="Delay";const n=this.toSeconds(e.maxDelay);this._maxDelay=Math.max(n,this.toSeconds(e.delayTime)),this._delayNode=this.input=this.output=this.context.createDelay(n),this.delayTime=new Xt({context:this.context,param:this._delayNode.delayTime,units:"time",value:e.delayTime,minValue:0,maxValue:this.maxDelay}),Zt(this,"delayTime")}static getDefaults(){return Object.assign(ft.getDefaults(),{delayTime:0,maxDelay:1})}get maxDelay(){return this._maxDelay}dispose(){return super.dispose(),this._delayNode.disconnect(),this.delayTime.dispose(),this}}class Ll extends ft{constructor(){const e=ct(Ll.getDefaults(),arguments,["volume"]);super(e),this.name="Volume",this.input=this.output=new jt({context:this.context,gain:e.volume,units:"decibels"}),this.volume=this.output.gain,Zt(this,"volume"),this._unmutedVolume=e.volume,this.mute=e.mute}static getDefaults(){return Object.assign(ft.getDefaults(),{mute:!1,volume:0})}get mute(){return this.volume.value===-1/0}set mute(e){!this.mute&&e?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!e&&(this.volume.value=this._unmutedVolume)}dispose(){return super.dispose(),this.input.dispose(),this.volume.dispose(),this}}class MT extends ft{constructor(){const e=ct(MT.getDefaults(),arguments);super(e),this.name="Destination",this.input=new Ll({context:this.context}),this.output=new jt({context:this.context}),this.volume=this.input.volume,Zu(this.input,this.output,this.context.rawContext.destination),this.mute=e.mute,this._internalChannels=[this.input,this.context.rawContext.destination,this.output]}static getDefaults(){return Object.assign(ft.getDefaults(),{mute:!1,volume:0})}get mute(){return this.input.mute}set mute(e){this.input.mute=e}chain(...e){return this.input.disconnect(),e.unshift(this.input),e.push(this.output),Zu(...e),this}get maxChannelCount(){return this.context.rawContext.destination.maxChannelCount}dispose(){return super.dispose(),this.volume.dispose(),this}}ly(t=>{t.destination=new MT({context:t})});uy(t=>{t.destination.dispose()});class Jte extends ft{constructor(){super(...arguments),this.name="Listener",this.positionX=new Xt({context:this.context,param:this.context.rawContext.listener.positionX}),this.positionY=new Xt({context:this.context,param:this.context.rawContext.listener.positionY}),this.positionZ=new Xt({context:this.context,param:this.context.rawContext.listener.positionZ}),this.forwardX=new Xt({context:this.context,param:this.context.rawContext.listener.forwardX}),this.forwardY=new Xt({context:this.context,param:this.context.rawContext.listener.forwardY}),this.forwardZ=new Xt({context:this.context,param:this.context.rawContext.listener.forwardZ}),this.upX=new Xt({context:this.context,param:this.context.rawContext.listener.upX}),this.upY=new Xt({context:this.context,param:this.context.rawContext.listener.upY}),this.upZ=new Xt({context:this.context,param:this.context.rawContext.listener.upZ})}static getDefaults(){return Object.assign(ft.getDefaults(),{positionX:0,positionY:0,positionZ:0,forwardX:0,forwardY:0,forwardZ:-1,upX:0,upY:1,upZ:0})}dispose(){return super.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this.forwardX.dispose(),this.forwardY.dispose(),this.forwardZ.dispose(),this.upX.dispose(),this.upY.dispose(),this.upZ.dispose(),this}}ly(t=>{t.listener=new Jte({context:t})});uy(t=>{t.listener.dispose()});class CT extends $c{constructor(){super(),this.name="ToneAudioBuffers",this._buffers=new Map,this._loadingCount=0;const e=ct(CT.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");this.baseUrl=e.baseUrl,Object.keys(e.urls).forEach(n=>{this._loadingCount++;const r=e.urls[n];this.add(n,r,this._bufferLoaded.bind(this,e.onload),e.onerror)})}static getDefaults(){return{baseUrl:"",onerror:En,onload:En,urls:{}}}has(e){return this._buffers.has(e.toString())}get(e){return bt(this.has(e),`ToneAudioBuffers has no buffer named: ${e}`),this._buffers.get(e.toString())}_bufferLoaded(e){this._loadingCount--,this._loadingCount===0&&e&&e()}get loaded(){return Array.from(this._buffers).every(([e,n])=>n.loaded)}add(e,n,r=En,i=En){return Lc(n)?(this.baseUrl&&n.trim().substring(0,11).toLowerCase()==="data:audio/"&&(this.baseUrl=""),this._buffers.set(e.toString(),new An(this.baseUrl+n,r,i))):this._buffers.set(e.toString(),new An(n,r,i)),this}dispose(){return super.dispose(),this._buffers.forEach(e=>e.dispose()),this._buffers.clear(),this}}class Z_ extends ss{constructor(){super(...arguments),this.name="MidiClass",this.defaultUnits="midi"}_frequencyToUnits(e){return Uu(super._frequencyToUnits(e))}_ticksToUnits(e){return Uu(super._ticksToUnits(e))}_beatsToUnits(e){return Uu(super._beatsToUnits(e))}_secondsToUnits(e){return Uu(super._secondsToUnits(e))}toMidi(){return this.valueOf()}toFrequency(){return mD(this.toMidi())}transpose(e){return new Z_(this.context,this.toMidi()+e)}}class Dr extends Mf{constructor(){super(...arguments),this.name="Ticks",this.defaultUnits="i"}_now(){return this.context.transport.ticks}_beatsToUnits(e){return this._getPPQ()*e}_secondsToUnits(e){return Math.floor(e/(60/this._getBpm())*this._getPPQ())}_ticksToUnits(e){return e}toTicks(){return this.valueOf()}toSeconds(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())}}class Qte extends Ei{constructor(){super(...arguments),this.name="Draw",this.expiration=.25,this.anticipation=.008,this._events=new so,this._boundDrawLoop=this._drawLoop.bind(this),this._animationFrame=-1}schedule(e,n){return this._events.add({callback:e,time:this.toSeconds(n)}),this._events.length===1&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop)),this}cancel(e){return this._events.cancel(this.toSeconds(e)),this}_drawLoop(){const e=this.context.currentTime;for(;this._events.length&&this._events.peek().time-this.anticipation<=e;){const n=this._events.shift();n&&e-n.time<=this.expiration&&n.callback()}this._events.length>0&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop))}dispose(){return super.dispose(),this._events.dispose(),cancelAnimationFrame(this._animationFrame),this}}ly(t=>{t.draw=new Qte({context:t})});uy(t=>{t.draw.dispose()});class ene extends $c{constructor(){super(...arguments),this.name="IntervalTimeline",this._root=null,this._length=0}add(e){bt(Wt(e.time),"Events must have a time property"),bt(Wt(e.duration),"Events must have a duration parameter"),e.time=e.time.valueOf();let n=new tne(e.time,e.time+e.duration,e);for(this._root===null?this._root=n:this._root.insert(n),this._length++;n!==null;)n.updateHeight(),n.updateMax(),this._rebalance(n),n=n.parent;return this}remove(e){if(this._root!==null){const n=[];this._root.search(e.time,n);for(const r of n)if(r.event===e){this._removeNode(r),this._length--;break}}return this}get length(){return this._length}cancel(e){return this.forEachFrom(e,n=>this.remove(n)),this}_setRoot(e){this._root=e,this._root!==null&&(this._root.parent=null)}_replaceNodeInParent(e,n){e.parent!==null?(e.isLeftChild()?e.parent.left=n:e.parent.right=n,this._rebalance(e.parent)):this._setRoot(n)}_removeNode(e){if(e.left===null&&e.right===null)this._replaceNodeInParent(e,null);else if(e.right===null)this._replaceNodeInParent(e,e.left);else if(e.left===null)this._replaceNodeInParent(e,e.right);else{const n=e.getBalance();let r,i=null;if(n>0)if(e.left.right===null)r=e.left,r.right=e.right,i=r;else{for(r=e.left.right;r.right!==null;)r=r.right;r.parent&&(r.parent.right=r.left,i=r.parent,r.left=e.left,r.right=e.right)}else if(e.right.left===null)r=e.right,r.left=e.left,i=r;else{for(r=e.right.left;r.left!==null;)r=r.left;r.parent&&(r.parent.left=r.right,i=r.parent,r.left=e.left,r.right=e.right)}e.parent!==null?e.isLeftChild()?e.parent.left=r:e.parent.right=r:this._setRoot(r),i&&this._rebalance(i)}e.dispose()}_rotateLeft(e){const n=e.parent,r=e.isLeftChild(),i=e.right;i&&(e.right=i.left,i.left=e),n!==null?r?n.left=i:n.right=i:this._setRoot(i)}_rotateRight(e){const n=e.parent,r=e.isLeftChild(),i=e.left;i&&(e.left=i.right,i.right=e),n!==null?r?n.left=i:n.right=i:this._setRoot(i)}_rebalance(e){const n=e.getBalance();n>1&&e.left?e.left.getBalance()<0?this._rotateLeft(e.left):this._rotateRight(e):n<-1&&e.right&&(e.right.getBalance()>0?this._rotateRight(e.right):this._rotateLeft(e))}get(e){if(this._root!==null){const n=[];if(this._root.search(e,n),n.length>0){let r=n[0];for(let i=1;ir.low&&(r=n[i]);return r.event}}return null}forEach(e){if(this._root!==null){const n=[];this._root.traverse(r=>n.push(r)),n.forEach(r=>{r.event&&e(r.event)})}return this}forEachAtTime(e,n){if(this._root!==null){const r=[];this._root.search(e,r),r.forEach(i=>{i.event&&n(i.event)})}return this}forEachFrom(e,n){if(this._root!==null){const r=[];this._root.searchAfter(e,r),r.forEach(i=>{i.event&&n(i.event)})}return this}dispose(){return super.dispose(),this._root!==null&&this._root.traverse(e=>e.dispose()),this._root=null,this}}class tne{constructor(e,n,r){this._left=null,this._right=null,this.parent=null,this.height=0,this.event=r,this.low=e,this.high=n,this.max=this.high}insert(e){e.low<=this.low?this.left===null?this.left=e:this.left.insert(e):this.right===null?this.right=e:this.right.insert(e)}search(e,n){e>this.max||(this.left!==null&&this.left.search(e,n),this.low<=e&&this.high>e&&n.push(this),!(this.low>e)&&this.right!==null&&this.right.search(e,n))}searchAfter(e,n){this.low>=e&&(n.push(this),this.left!==null&&this.left.searchAfter(e,n)),this.right!==null&&this.right.searchAfter(e,n)}traverse(e){e(this),this.left!==null&&this.left.traverse(e),this.right!==null&&this.right.traverse(e)}updateHeight(){this.left!==null&&this.right!==null?this.height=Math.max(this.left.height,this.right.height)+1:this.right!==null?this.height=this.right.height+1:this.left!==null?this.height=this.left.height+1:this.height=0}updateMax(){this.max=this.high,this.left!==null&&(this.max=Math.max(this.max,this.left.max)),this.right!==null&&(this.max=Math.max(this.max,this.right.max))}getBalance(){let e=0;return this.left!==null&&this.right!==null?e=this.left.height-this.right.height:this.left!==null?e=this.left.height+1:this.right!==null&&(e=-(this.right.height+1)),e}isLeftChild(){return this.parent!==null&&this.parent.left===this}get left(){return this._left}set left(e){this._left=e,e!==null&&(e.parent=this),this.updateHeight(),this.updateMax()}get right(){return this._right}set right(e){this._right=e,e!==null&&(e.parent=this),this.updateHeight(),this.updateMax()}dispose(){this.parent=null,this._left=null,this._right=null,this.event=null}}class nne extends $c{constructor(e){super(),this.name="TimelineValue",this._timeline=new so({memory:10}),this._initialValue=e}set(e,n){return this._timeline.add({value:e,time:n}),this}get(e){const n=this._timeline.get(e);return n?n.value:this._initialValue}}class Ma extends ft{constructor(){super(ct(Ma.getDefaults(),arguments,["context"]))}connect(e,n=0,r=0){return dy(this,e,n,r),this}}class mh extends Ma{constructor(){const e=ct(mh.getDefaults(),arguments,["mapping","length"]);super(e),this.name="WaveShaper",this._shaper=this.context.createWaveShaper(),this.input=this._shaper,this.output=this._shaper,us(e.mapping)||e.mapping instanceof Float32Array?this.curve=Float32Array.from(e.mapping):Cte(e.mapping)&&this.setMap(e.mapping,e.length)}static getDefaults(){return Object.assign(yn.getDefaults(),{length:1024})}setMap(e,n=1024){const r=new Float32Array(n);for(let i=0,s=n;ir.includes(e));bt(n,"oversampling must be either 'none', '2x', or '4x'"),this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.disconnect(),this}}class RT extends Ma{constructor(){const e=ct(RT.getDefaults(),arguments,["value"]);super(e),this.name="Pow",this._exponentScaler=this.input=this.output=new mh({context:this.context,mapping:this._expFunc(e.value),length:8192}),this._exponent=e.value}static getDefaults(){return Object.assign(Ma.getDefaults(),{value:1})}_expFunc(e){return n=>Math.pow(Math.abs(n),e)}get value(){return this._exponent}set value(e){this._exponent=e,this._exponentScaler.setMap(this._expFunc(this._exponent))}dispose(){return super.dispose(),this._exponentScaler.dispose(),this}}class Pl{constructor(e,n){this.id=Pl._eventId++,this._remainderTime=0;const r=Object.assign(Pl.getDefaults(),n);this.transport=e,this.callback=r.callback,this._once=r.once,this.time=Math.floor(r.time),this._remainderTime=r.time-this.time}static getDefaults(){return{callback:En,once:!1,time:0}}get floatTime(){return this.time+this._remainderTime}invoke(e){if(this.callback){const n=this.transport.bpm.getDurationOfTicks(1,e);this.callback(e+this._remainderTime*n),this._once&&this.transport.clear(this.id)}}dispose(){return this.callback=void 0,this}}Pl._eventId=0;class NT extends Pl{constructor(e,n){super(e,n),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this);const r=Object.assign(NT.getDefaults(),n);this.duration=r.duration,this._interval=r.interval,this._nextTick=r.time,this.transport.on("start",this._boundRestart),this.transport.on("loopStart",this._boundRestart),this.transport.on("ticks",this._boundRestart),this.context=this.transport.context,this._restart()}static getDefaults(){return Object.assign({},Pl.getDefaults(),{duration:1/0,interval:1,once:!1})}invoke(e){this._createEvents(e),super.invoke(e)}_createEvent(){return Y_(this._nextTick,this.floatTime+this.duration)?this.transport.scheduleOnce(this.invoke.bind(this),new Dr(this.context,this._nextTick).toSeconds()):-1}_createEvents(e){Y_(this._nextTick+this._interval,this.floatTime+this.duration)&&(this._nextTick+=this._interval,this._currentId=this._nextId,this._nextId=this.transport.scheduleOnce(this.invoke.bind(this),new Dr(this.context,this._nextTick).toSeconds()))}_restart(e){this.transport.clear(this._currentId),this.transport.clear(this._nextId),this._nextTick=this.floatTime;const n=this.transport.getTicksAtTime(e);qf(n,this.time)&&(this._nextTick=this.floatTime+Math.ceil((n-this.floatTime)/this._interval)*this._interval),this._currentId=this._createEvent(),this._nextTick+=this._interval,this._nextId=this._createEvent()}dispose(){return super.dispose(),this.transport.clear(this._currentId),this.transport.clear(this._nextId),this.transport.off("start",this._boundRestart),this.transport.off("loopStart",this._boundRestart),this.transport.off("ticks",this._boundRestart),this}}class my extends Ei{constructor(){const e=ct(my.getDefaults(),arguments);super(e),this.name="Transport",this._loop=new nne(!1),this._loopStart=0,this._loopEnd=0,this._scheduledEvents={},this._timeline=new so,this._repeatedEvents=new ene,this._syncedSignals=[],this._swingAmount=0,this._ppq=e.ppq,this._clock=new py({callback:this._processTick.bind(this),context:this.context,frequency:0,units:"bpm"}),this._bindClockEvents(),this.bpm=this._clock.frequency,this._clock.frequency.multiplier=e.ppq,this.bpm.setValueAtTime(e.bpm,0),Zt(this,"bpm"),this._timeSignature=e.timeSignature,this._swingTicks=e.ppq/2}static getDefaults(){return Object.assign(Ei.getDefaults(),{bpm:120,loopEnd:"4m",loopStart:0,ppq:192,swing:0,swingSubdivision:"8n",timeSignature:4})}_processTick(e,n){if(this._loop.get(e)&&n>=this._loopEnd&&(this.emit("loopEnd",e),this._clock.setTicksAtTime(this._loopStart,e),n=this._loopStart,this.emit("loopStart",e,this._clock.getSecondsAtTime(e)),this.emit("loop",e)),this._swingAmount>0&&n%this._ppq!==0&&n%(this._swingTicks*2)!==0){const r=n%(this._swingTicks*2)/(this._swingTicks*2),i=Math.sin(r*Math.PI)*this._swingAmount;e+=new Dr(this.context,this._swingTicks*2/3).toSeconds()*i}mN(!0),this._timeline.forEachAtTime(n,r=>r.invoke(e)),mN(!1)}schedule(e,n){const r=new Pl(this,{callback:e,time:new Mf(this.context,n).toTicks()});return this._addEvent(r,this._timeline)}scheduleRepeat(e,n,r,i=1/0){const s=new NT(this,{callback:e,duration:new no(this.context,i).toTicks(),interval:new no(this.context,n).toTicks(),time:new Mf(this.context,r).toTicks()});return this._addEvent(s,this._repeatedEvents)}scheduleOnce(e,n){const r=new Pl(this,{callback:e,once:!0,time:new Mf(this.context,n).toTicks()});return this._addEvent(r,this._timeline)}clear(e){if(this._scheduledEvents.hasOwnProperty(e)){const n=this._scheduledEvents[e.toString()];n.timeline.remove(n.event),n.event.dispose(),delete this._scheduledEvents[e.toString()]}return this}_addEvent(e,n){return this._scheduledEvents[e.id.toString()]={event:e,timeline:n},n.add(e),e.id}cancel(e=0){const n=this.toTicks(e);return this._timeline.forEachFrom(n,r=>this.clear(r.id)),this._repeatedEvents.forEachFrom(n,r=>this.clear(r.id)),this}_bindClockEvents(){this._clock.on("start",(e,n)=>{n=new Dr(this.context,n).toSeconds(),this.emit("start",e,n)}),this._clock.on("stop",e=>{this.emit("stop",e)}),this._clock.on("pause",e=>{this.emit("pause",e)})}get state(){return this._clock.getStateAtTime(this.now())}start(e,n){this.context.resume();let r;return Wt(n)&&(r=this.toTicks(n)),this._clock.start(e,r),this}stop(e){return this._clock.stop(e),this}pause(e){return this._clock.pause(e),this}toggle(e){return e=this.toSeconds(e),this._clock.getStateAtTime(e)!=="started"?this.start(e):this.stop(e),this}get timeSignature(){return this._timeSignature}set timeSignature(e){us(e)&&(e=e[0]/e[1]*4),this._timeSignature=e}get loopStart(){return new no(this.context,this._loopStart,"i").toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e)}get loopEnd(){return new no(this.context,this._loopEnd,"i").toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e)}get loop(){return this._loop.get(this.now())}set loop(e){this._loop.set(e,this.now())}setLoopPoints(e,n){return this.loopStart=e,this.loopEnd=n,this}get swing(){return this._swingAmount}set swing(e){this._swingAmount=e}get swingSubdivision(){return new Dr(this.context,this._swingTicks).toNotation()}set swingSubdivision(e){this._swingTicks=this.toTicks(e)}get position(){const e=this.now(),n=this._clock.getTicksAtTime(e);return new Dr(this.context,n).toBarsBeatsSixteenths()}set position(e){const n=this.toTicks(e);this.ticks=n}get seconds(){return this._clock.seconds}set seconds(e){const n=this.now(),r=this._clock.frequency.timeToTicks(e,n);this.ticks=r}get progress(){if(this.loop){const e=this.now();return(this._clock.getTicksAtTime(e)-this._loopStart)/(this._loopEnd-this._loopStart)}else return 0}get ticks(){return this._clock.ticks}set ticks(e){if(this._clock.ticks!==e){const n=this.now();if(this.state==="started"){const r=this._clock.getTicksAtTime(n),i=this._clock.frequency.getDurationOfTicks(Math.ceil(r)-r,n),s=n+i;this.emit("stop",s),this._clock.setTicksAtTime(e,s),this.emit("start",s,this._clock.getSecondsAtTime(s))}else this.emit("ticks",n),this._clock.setTicksAtTime(e,n)}}getTicksAtTime(e){return this._clock.getTicksAtTime(e)}getSecondsAtTime(e){return this._clock.getSecondsAtTime(e)}get PPQ(){return this._clock.frequency.multiplier}set PPQ(e){this._clock.frequency.multiplier=e}nextSubdivision(e){if(e=this.toTicks(e),this.state!=="started")return 0;{const n=this.now(),r=this.getTicksAtTime(n),i=e-r%e;return this._clock.nextTickTime(i,n)}}syncSignal(e,n){const r=this.now();let i=this.bpm,s=1/(60/i.getValueAtTime(r)/this.PPQ),o=[];if(e.units==="time"){const c=.015625/s,l=new jt(c),u=new RT(-1),h=new jt(c);i.chain(l,u,h),i=h,s=1/s,o=[l,u,h]}n||(e.getValueAtTime(r)!==0?n=e.getValueAtTime(r)/s:n=0);const a=new jt(n);return i.connect(a),a.connect(e._param),o.push(a),this._syncedSignals.push({initial:e.value,nodes:o,signal:e}),e.value=0,this}unsyncSignal(e){for(let n=this._syncedSignals.length-1;n>=0;n--){const r=this._syncedSignals[n];r.signal===e&&(r.nodes.forEach(i=>i.dispose()),r.signal.value=r.initial,this._syncedSignals.splice(n,1))}return this}dispose(){return super.dispose(),this._clock.dispose(),_m(this,"bpm"),this._timeline.dispose(),this._repeatedEvents.dispose(),this}}mm.mixin(my);ly(t=>{t.transport=new my({context:t})});uy(t=>{t.transport.dispose()});class Ti extends ft{constructor(e){super(e),this.input=void 0,this._state=new vm("stopped"),this._synced=!1,this._scheduled=[],this._syncedStart=En,this._syncedStop=En,this._state.memory=100,this._state.increasing=!0,this._volume=this.output=new Ll({context:this.context,mute:e.mute,volume:e.volume}),this.volume=this._volume.volume,Zt(this,"volume"),this.onstop=e.onstop}static getDefaults(){return Object.assign(ft.getDefaults(),{mute:!1,onstop:En,volume:0})}get state(){return this._synced?this.context.transport.state==="started"?this._state.getValueAtTime(this.context.transport.seconds):"stopped":this._state.getValueAtTime(this.now())}get mute(){return this._volume.mute}set mute(e){this._volume.mute=e}_clampToCurrentTime(e){return this._synced?e:Math.max(e,this.context.currentTime)}start(e,n,r){let i=Ps(e)&&this._synced?this.context.transport.seconds:this.toSeconds(e);if(i=this._clampToCurrentTime(i),!this._synced&&this._state.getValueAtTime(i)==="started")bt(qf(i,this._state.get(i).time),"Start time must be strictly greater than previous start time"),this._state.cancel(i),this._state.setStateAtTime("started",i),this.log("restart",i),this.restart(i,n,r);else if(this.log("start",i),this._state.setStateAtTime("started",i),this._synced){const s=this._state.get(i);s&&(s.offset=this.toSeconds(Sa(n,0)),s.duration=r?this.toSeconds(r):void 0);const o=this.context.transport.schedule(a=>{this._start(a,n,r)},i);this._scheduled.push(o),this.context.transport.state==="started"&&this.context.transport.getSecondsAtTime(this.immediate())>i&&this._syncedStart(this.now(),this.context.transport.seconds)}else oD(this.context),this._start(i,n,r);return this}stop(e){let n=Ps(e)&&this._synced?this.context.transport.seconds:this.toSeconds(e);if(n=this._clampToCurrentTime(n),this._state.getValueAtTime(n)==="started"||Wt(this._state.getNextState("started",n))){if(this.log("stop",n),!this._synced)this._stop(n);else{const r=this.context.transport.schedule(this._stop.bind(this),n);this._scheduled.push(r)}this._state.cancel(n),this._state.setStateAtTime("stopped",n)}return this}restart(e,n,r){return e=this.toSeconds(e),this._state.getValueAtTime(e)==="started"&&(this._state.cancel(e),this._restart(e,n,r)),this}sync(){return this._synced||(this._synced=!0,this._syncedStart=(e,n)=>{if(qf(n,0)){const r=this._state.get(n);if(r&&r.state==="started"&&r.time!==n){const i=n-this.toSeconds(r.time);let s;r.duration&&(s=this.toSeconds(r.duration)-i),this._start(e,this.toSeconds(r.offset)+i,s)}}},this._syncedStop=e=>{const n=this.context.transport.getSecondsAtTime(Math.max(e-this.sampleTime,0));this._state.getValueAtTime(n)==="started"&&this._stop(e)},this.context.transport.on("start",this._syncedStart),this.context.transport.on("loopStart",this._syncedStart),this.context.transport.on("stop",this._syncedStop),this.context.transport.on("pause",this._syncedStop),this.context.transport.on("loopEnd",this._syncedStop)),this}unsync(){return this._synced&&(this.context.transport.off("stop",this._syncedStop),this.context.transport.off("pause",this._syncedStop),this.context.transport.off("loopEnd",this._syncedStop),this.context.transport.off("start",this._syncedStart),this.context.transport.off("loopStart",this._syncedStart)),this._synced=!1,this._scheduled.forEach(e=>this.context.transport.clear(e)),this._scheduled=[],this._state.cancel(0),this._stop(0),this}dispose(){return super.dispose(),this.onstop=En,this.unsync(),this._volume.dispose(),this._state.dispose(),this}}class ym extends Xf{constructor(){const e=ct(ym.getDefaults(),arguments,["url","onload"]);super(e),this.name="ToneBufferSource",this._source=this.context.createBufferSource(),this._internalChannels=[this._source],this._sourceStarted=!1,this._sourceStopped=!1,Do(this._source,this._gainNode),this._source.onended=()=>this._stopSource(),this.playbackRate=new Xt({context:this.context,param:this._source.playbackRate,units:"positive",value:e.playbackRate}),this.loop=e.loop,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this._buffer=new An(e.url,e.onload,e.onerror),this._internalChannels.push(this._source)}static getDefaults(){return Object.assign(Xf.getDefaults(),{url:new An,loop:!1,loopEnd:0,loopStart:0,onload:En,onerror:En,playbackRate:1})}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e}get curve(){return this._curve}set curve(e){this._curve=e}start(e,n,r,i=1){bt(this.buffer.loaded,"buffer is either not set or not loaded");const s=this.toSeconds(e);this._startGain(s,i),this.loop?n=Sa(n,this.loopStart):n=Sa(n,0);let o=Math.max(this.toSeconds(n),0);if(this.loop){const a=this.toSeconds(this.loopEnd)||this.buffer.duration,c=this.toSeconds(this.loopStart),l=a-c;iw(o,a)&&(o=(o-c)%l+c),wo(o,this.buffer.duration)&&(o=0)}if(this._source.buffer=this.buffer.get(),this._source.loopEnd=this.toSeconds(this.loopEnd)||this.buffer.duration,Y_(o,this.buffer.duration)&&(this._sourceStarted=!0,this._source.start(s,o)),Wt(r)){let a=this.toSeconds(r);a=Math.max(a,0),this.stop(s+a)}return this}_stopSource(e){!this._sourceStopped&&this._sourceStarted&&(this._sourceStopped=!0,this._source.stop(this.toSeconds(e)),this._onended())}get loopStart(){return this._source.loopStart}set loopStart(e){this._source.loopStart=this.toSeconds(e)}get loopEnd(){return this._source.loopEnd}set loopEnd(e){this._source.loopEnd=this.toSeconds(e)}get buffer(){return this._buffer}set buffer(e){this._buffer.set(e)}get loop(){return this._source.loop}set loop(e){this._source.loop=e,this._sourceStarted&&this.cancelStop()}dispose(){return super.dispose(),this._source.onended=null,this._source.disconnect(),this._buffer.dispose(),this.playbackRate.dispose(),this}}class Yf extends Ti{constructor(){const e=ct(Yf.getDefaults(),arguments,["type"]);super(e),this.name="Noise",this._source=null,this._playbackRate=e.playbackRate,this.type=e.type,this._fadeIn=e.fadeIn,this._fadeOut=e.fadeOut}static getDefaults(){return Object.assign(Ti.getDefaults(),{fadeIn:0,fadeOut:0,playbackRate:1,type:"white"})}get type(){return this._type}set type(e){if(bt(e in _N,"Noise: invalid type: "+e),this._type!==e&&(this._type=e,this.state==="started")){const n=this.now();this._stop(n),this._start(n)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._source&&(this._source.playbackRate.value=e)}_start(e){const n=_N[this._type];this._source=new ym({url:n,context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,loop:!0,onended:()=>this.onstop(this),playbackRate:this._playbackRate}).connect(this.output),this._source.start(this.toSeconds(e),Math.random()*(n.duration-.001))}_stop(e){this._source&&(this._source.stop(this.toSeconds(e)),this._source=null)}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e,this._source&&(this._source.fadeIn=this._fadeIn)}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e,this._source&&(this._source.fadeOut=this._fadeOut)}_restart(e){this._stop(e),this._start(e)}dispose(){return super.dispose(),this._source&&this._source.disconnect(),this}}const Jh=44100*5,eS=2,ic={brown:null,pink:null,white:null},_N={get brown(){if(!ic.brown){const t=[];for(let e=0;ethis.onstop(this)});this._oscillator=r,this._wave?this._oscillator.setPeriodicWave(this._wave):this._oscillator.type=this._type,this._oscillator.connect(this.output),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.start(n)}_stop(e){const n=this.toSeconds(e);this._oscillator&&this._oscillator.stop(n)}_restart(e){const n=this.toSeconds(e);return this.log("restart",n),this._oscillator&&this._oscillator.cancelStop(),this._state.cancel(n),this}syncFrequency(){return this.context.transport.syncSignal(this.frequency),this}unsyncFrequency(){return this.context.transport.unsyncSignal(this.frequency),this}_getCachedPeriodicWave(){if(this._type==="custom")return rr._periodicWaveCache.find(n=>n.phase===this._phase&&Fte(n.partials,this._partials));{const e=rr._periodicWaveCache.find(n=>n.type===this._type&&n.phase===this._phase);return this._partialCount=e?e.partialCount:this._partialCount,e}}get type(){return this._type}set type(e){this._type=e;const n=["sine","square","sawtooth","triangle"].indexOf(e)!==-1;if(this._phase===0&&n)this._wave=void 0,this._partialCount=0,this._oscillator!==null&&(this._oscillator.type=e);else{const r=this._getCachedPeriodicWave();if(Wt(r)){const{partials:i,wave:s}=r;this._wave=s,this._partials=i,this._oscillator!==null&&this._oscillator.setPeriodicWave(this._wave)}else{const[i,s]=this._getRealImaginary(e,this._phase),o=this.context.createPeriodicWave(i,s);this._wave=o,this._oscillator!==null&&this._oscillator.setPeriodicWave(this._wave),rr._periodicWaveCache.push({imag:s,partialCount:this._partialCount,partials:this._partials,phase:this._phase,real:i,type:this._type,wave:this._wave}),rr._periodicWaveCache.length>100&&rr._periodicWaveCache.shift()}}}get baseType(){return this._type.replace(this.partialCount.toString(),"")}set baseType(e){this.partialCount&&this._type!=="custom"&&e!=="custom"?this.type=e+this.partialCount:this.type=e}get partialCount(){return this._partialCount}set partialCount(e){Aa(e,0);let n=this._type;const r=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(this._type);if(r&&(n=r[1]),this._type!=="custom")e===0?this.type=n:this.type=n+e.toString();else{const i=new Float32Array(e);this._partials.forEach((s,o)=>i[o]=s),this._partials=Array.from(i),this.type=this._type}}_getRealImaginary(e,n){let i=2048;const s=new Float32Array(i),o=new Float32Array(i);let a=1;if(e==="custom"){if(a=this._partials.length+1,this._partialCount=this._partials.length,i=a,this._partials.length===0)return[s,o]}else{const c=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(e);c?(a=parseInt(c[2],10)+1,this._partialCount=parseInt(c[2],10),e=c[1],a=Math.max(a,2),i=a):this._partialCount=0,this._partials=[]}for(let c=1;c>1&1?-1:1):u=0,this._partials[c-1]=u;break;case"custom":u=this._partials[c-1];break;default:throw new TypeError("Oscillator: invalid type: "+e)}u!==0?(s[c]=-u*Math.sin(n*c),o[c]=u*Math.cos(n*c)):(s[c]=0,o[c]=0)}return[s,o]}_inverseFFT(e,n,r){let i=0;const s=e.length;for(let o=0;o(e+1)/2}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class Ju extends yn{constructor(){const e=ct(Ju.getDefaults(),arguments,["value"]);super(e),this.name="Multiply",this.override=!1,this._mult=this.input=this.output=new jt({context:this.context,minValue:e.minValue,maxValue:e.maxValue}),this.factor=this._param=this._mult.gain,this.factor.setValueAtTime(e.value,0)}static getDefaults(){return Object.assign(yn.getDefaults(),{value:0})}dispose(){return super.dispose(),this._mult.dispose(),this}}class gy extends Ti{constructor(){const e=ct(gy.getDefaults(),arguments,["frequency","type","modulationType"]);super(e),this.name="AMOscillator",this._modulationScale=new _D({context:this.context}),this._modulationNode=new jt({context:this.context}),this._carrier=new rr({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase,type:e.type}),this.frequency=this._carrier.frequency,this.detune=this._carrier.detune,this._modulator=new rr({context:this.context,phase:e.phase,type:e.modulationType}),this.harmonicity=new Ju({context:this.context,units:"positive",value:e.harmonicity}),this.frequency.chain(this.harmonicity,this._modulator.frequency),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output),Zt(this,["frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(rr.getDefaults(),{harmonicity:1,modulationType:"square"})}_start(e){this._modulator.start(e),this._carrier.start(e)}_stop(e){this._modulator.stop(e),this._carrier.stop(e)}_restart(e){this._modulator.restart(e),this._carrier.restart(e)}get type(){return this._carrier.type}set type(e){this._carrier.type=e}get baseType(){return this._carrier.baseType}set baseType(e){this._carrier.baseType=e}get partialCount(){return this._carrier.partialCount}set partialCount(e){this._carrier.partialCount=e}get modulationType(){return this._modulator.type}set modulationType(e){this._modulator.type=e}get phase(){return this._carrier.phase}set phase(e){this._carrier.phase=e,this._modulator.phase=e}get partials(){return this._carrier.partials}set partials(e){this._carrier.partials=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return gh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this._modulationScale.dispose(),this}}class _y extends Ti{constructor(){const e=ct(_y.getDefaults(),arguments,["frequency","type","modulationType"]);super(e),this.name="FMOscillator",this._modulationNode=new jt({context:this.context,gain:0}),this._carrier=new rr({context:this.context,detune:e.detune,frequency:0,onstop:()=>this.onstop(this),phase:e.phase,type:e.type}),this.detune=this._carrier.detune,this.frequency=new yn({context:this.context,units:"frequency",value:e.frequency}),this._modulator=new rr({context:this.context,phase:e.phase,type:e.modulationType}),this.harmonicity=new Ju({context:this.context,units:"positive",value:e.harmonicity}),this.modulationIndex=new Ju({context:this.context,units:"positive",value:e.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output),this.detune.connect(this._modulator.detune),Zt(this,["modulationIndex","frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(rr.getDefaults(),{harmonicity:1,modulationIndex:2,modulationType:"square"})}_start(e){this._modulator.start(e),this._carrier.start(e)}_stop(e){this._modulator.stop(e),this._carrier.stop(e)}_restart(e){return this._modulator.restart(e),this._carrier.restart(e),this}get type(){return this._carrier.type}set type(e){this._carrier.type=e}get baseType(){return this._carrier.baseType}set baseType(e){this._carrier.baseType=e}get partialCount(){return this._carrier.partialCount}set partialCount(e){this._carrier.partialCount=e}get modulationType(){return this._modulator.type}set modulationType(e){this._modulator.type=e}get phase(){return this._carrier.phase}set phase(e){this._carrier.phase=e,this._modulator.phase=e}get partials(){return this._carrier.partials}set partials(e){this._carrier.partials=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return gh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this.modulationIndex.dispose(),this}}class xm extends Ti{constructor(){const e=ct(xm.getDefaults(),arguments,["frequency","width"]);super(e),this.name="PulseOscillator",this._widthGate=new jt({context:this.context,gain:0}),this._thresh=new mh({context:this.context,mapping:n=>n<=0?-1:1}),this.width=new yn({context:this.context,units:"audioRange",value:e.width}),this._triangle=new rr({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase,type:"triangle"}),this.frequency=this._triangle.frequency,this.detune=this._triangle.detune,this._triangle.chain(this._thresh,this.output),this.width.chain(this._widthGate,this._thresh),Zt(this,["width","frequency","detune"])}static getDefaults(){return Object.assign(Ti.getDefaults(),{detune:0,frequency:440,phase:0,type:"pulse",width:.2})}_start(e){e=this.toSeconds(e),this._triangle.start(e),this._widthGate.gain.setValueAtTime(1,e)}_stop(e){e=this.toSeconds(e),this._triangle.stop(e),this._widthGate.gain.cancelScheduledValues(e),this._widthGate.gain.setValueAtTime(0,e)}_restart(e){this._triangle.restart(e),this._widthGate.gain.cancelScheduledValues(e),this._widthGate.gain.setValueAtTime(1,e)}get phase(){return this._triangle.phase}set phase(e){this._triangle.phase=e}get type(){return"pulse"}get baseType(){return"pulse"}get partials(){return[]}get partialCount(){return 0}set carrierType(e){this._triangle.type=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return gh(this,e)})}dispose(){return super.dispose(),this._triangle.dispose(),this.width.dispose(),this._widthGate.dispose(),this._thresh.dispose(),this}}class vy extends Ti{constructor(){const e=ct(vy.getDefaults(),arguments,["frequency","type","spread"]);super(e),this.name="FatOscillator",this._oscillators=[],this.frequency=new yn({context:this.context,units:"frequency",value:e.frequency}),this.detune=new yn({context:this.context,units:"cents",value:e.detune}),this._spread=e.spread,this._type=e.type,this._phase=e.phase,this._partials=e.partials,this._partialCount=e.partialCount,this.count=e.count,Zt(this,["frequency","detune"])}static getDefaults(){return Object.assign(rr.getDefaults(),{count:3,spread:20,type:"sawtooth"})}_start(e){e=this.toSeconds(e),this._forEach(n=>n.start(e))}_stop(e){e=this.toSeconds(e),this._forEach(n=>n.stop(e))}_restart(e){this._forEach(n=>n.restart(e))}_forEach(e){for(let n=0;nn.type=e)}get spread(){return this._spread}set spread(e){if(this._spread=e,this._oscillators.length>1){const n=-e/2,r=e/(this._oscillators.length-1);this._forEach((i,s)=>i.detune.value=n+r*s)}}get count(){return this._oscillators.length}set count(e){if(Aa(e,1),this._oscillators.length!==e){this._forEach(n=>n.dispose()),this._oscillators=[];for(let n=0;nthis.onstop(this):En});this.type==="custom"&&(r.partials=this._partials),this.frequency.connect(r.frequency),this.detune.connect(r.detune),r.detune.overridden=!1,r.connect(this.output),this._oscillators[n]=r}this.spread=this._spread,this.state==="started"&&this._forEach(n=>n.start())}}get phase(){return this._phase}set phase(e){this._phase=e,this._forEach((n,r)=>n.phase=this._phase+r/this.count*360)}get baseType(){return this._oscillators[0].baseType}set baseType(e){this._forEach(n=>n.baseType=e),this._type=this._oscillators[0].type}get partials(){return this._oscillators[0].partials}set partials(e){this._partials=e,this._partialCount=this._partials.length,e.length&&(this._type="custom",this._forEach(n=>n.partials=e))}get partialCount(){return this._oscillators[0].partialCount}set partialCount(e){this._partialCount=e,this._forEach(n=>n.partialCount=e),this._type=this._oscillators[0].type}asArray(){return _r(this,arguments,void 0,function*(e=1024){return gh(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this._forEach(e=>e.dispose()),this}}class yy extends Ti{constructor(){const e=ct(yy.getDefaults(),arguments,["frequency","modulationFrequency"]);super(e),this.name="PWMOscillator",this.sourceType="pwm",this._scale=new Ju({context:this.context,value:2}),this._pulse=new xm({context:this.context,frequency:e.modulationFrequency}),this._pulse.carrierType="sine",this.modulationFrequency=this._pulse.frequency,this._modulator=new rr({context:this.context,detune:e.detune,frequency:e.frequency,onstop:()=>this.onstop(this),phase:e.phase}),this.frequency=this._modulator.frequency,this.detune=this._modulator.detune,this._modulator.chain(this._scale,this._pulse.width),this._pulse.connect(this.output),Zt(this,["modulationFrequency","frequency","detune"])}static getDefaults(){return Object.assign(Ti.getDefaults(),{detune:0,frequency:440,modulationFrequency:.4,phase:0,type:"pwm"})}_start(e){e=this.toSeconds(e),this._modulator.start(e),this._pulse.start(e)}_stop(e){e=this.toSeconds(e),this._modulator.stop(e),this._pulse.stop(e)}_restart(e){this._modulator.restart(e),this._pulse.restart(e)}get type(){return"pwm"}get baseType(){return"pwm"}get partials(){return[]}get partialCount(){return 0}get phase(){return this._modulator.phase}set phase(e){this._modulator.phase=e}asArray(){return _r(this,arguments,void 0,function*(e=1024){return gh(this,e)})}dispose(){return super.dispose(),this._pulse.dispose(),this._scale.dispose(),this._modulator.dispose(),this}}const vN={am:gy,fat:vy,fm:_y,oscillator:rr,pulse:xm,pwm:yy};class J_ extends Ti{constructor(){const e=ct(J_.getDefaults(),arguments,["frequency","type"]);super(e),this.name="OmniOscillator",this.frequency=new yn({context:this.context,units:"frequency",value:e.frequency}),this.detune=new yn({context:this.context,units:"cents",value:e.detune}),Zt(this,["frequency","detune"]),this.set(e)}static getDefaults(){return Object.assign(rr.getDefaults(),_y.getDefaults(),gy.getDefaults(),vy.getDefaults(),xm.getDefaults(),yy.getDefaults())}_start(e){this._oscillator.start(e)}_stop(e){this._oscillator.stop(e)}_restart(e){return this._oscillator.restart(e),this}get type(){let e="";return["am","fm","fat"].some(n=>this._sourceType===n)&&(e=this._sourceType),e+this._oscillator.type}set type(e){e.substr(0,2)==="fm"?(this._createNewOscillator("fm"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(2)):e.substr(0,2)==="am"?(this._createNewOscillator("am"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(2)):e.substr(0,3)==="fat"?(this._createNewOscillator("fat"),this._oscillator=this._oscillator,this._oscillator.type=e.substr(3)):e==="pwm"?(this._createNewOscillator("pwm"),this._oscillator=this._oscillator):e==="pulse"?this._createNewOscillator("pulse"):(this._createNewOscillator("oscillator"),this._oscillator=this._oscillator,this._oscillator.type=e)}get partials(){return this._oscillator.partials}set partials(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&(this._oscillator.partials=e)}get partialCount(){return this._oscillator.partialCount}set partialCount(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&(this._oscillator.partialCount=e)}set(e){return Reflect.has(e,"type")&&e.type&&(this.type=e.type),super.set(e),this}_createNewOscillator(e){if(e!==this._sourceType){this._sourceType=e;const n=vN[e],r=this.now();if(this._oscillator){const i=this._oscillator;i.stop(r),this.context.setTimeout(()=>i.dispose(),this.blockTime)}this._oscillator=new n({context:this.context}),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.connect(this.output),this._oscillator.onstop=()=>this.onstop(this),this.state==="started"&&this._oscillator.start(r)}}get phase(){return this._oscillator.phase}set phase(e){this._oscillator.phase=e}get sourceType(){return this._sourceType}set sourceType(e){let n="sine";this._oscillator.type!=="pwm"&&this._oscillator.type!=="pulse"&&(n=this._oscillator.type),e==="fm"?this.type="fm"+n:e==="am"?this.type="am"+n:e==="fat"?this.type="fat"+n:e==="oscillator"?this.type=n:e==="pulse"?this.type="pulse":e==="pwm"&&(this.type="pwm")}_getOscType(e,n){return e instanceof vN[n]}get baseType(){return this._oscillator.baseType}set baseType(e){!this._getOscType(this._oscillator,"pulse")&&!this._getOscType(this._oscillator,"pwm")&&e!=="pulse"&&e!=="pwm"&&(this._oscillator.baseType=e)}get width(){if(this._getOscType(this._oscillator,"pulse"))return this._oscillator.width}get count(){if(this._getOscType(this._oscillator,"fat"))return this._oscillator.count}set count(e){this._getOscType(this._oscillator,"fat")&&Po(e)&&(this._oscillator.count=e)}get spread(){if(this._getOscType(this._oscillator,"fat"))return this._oscillator.spread}set spread(e){this._getOscType(this._oscillator,"fat")&&Po(e)&&(this._oscillator.spread=e)}get modulationType(){if(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))return this._oscillator.modulationType}set modulationType(e){(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))&&Lc(e)&&(this._oscillator.modulationType=e)}get modulationIndex(){if(this._getOscType(this._oscillator,"fm"))return this._oscillator.modulationIndex}get harmonicity(){if(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))return this._oscillator.harmonicity}get modulationFrequency(){if(this._getOscType(this._oscillator,"pwm"))return this._oscillator.modulationFrequency}asArray(){return _r(this,arguments,void 0,function*(e=1024){return gh(this,e)})}dispose(){return super.dispose(),this.detune.dispose(),this.frequency.dispose(),this._oscillator.dispose(),this}}class IT extends yn{constructor(){super(ct(IT.getDefaults(),arguments,["value"])),this.override=!1,this.name="Add",this._sum=new jt({context:this.context}),this.input=this._sum,this.output=this._sum,this.addend=this._param,Zu(this._constantSource,this._sum)}static getDefaults(){return Object.assign(yn.getDefaults(),{value:0})}dispose(){return super.dispose(),this._sum.dispose(),this}}class OT extends Ma{constructor(){const e=ct(OT.getDefaults(),arguments,["min","max"]);super(e),this.name="Scale",this._mult=this.input=new Ju({context:this.context,value:e.max-e.min}),this._add=this.output=new IT({context:this.context,value:e.min}),this._min=e.min,this._max=e.max,this.input.connect(this.output)}static getDefaults(){return Object.assign(Ma.getDefaults(),{max:1,min:0})}get min(){return this._min}set min(e){this._min=e,this._setRange()}get max(){return this._max}set max(e){this._max=e,this._setRange()}_setRange(){this._add.value=this._min,this._mult.value=this._max-this._min}dispose(){return super.dispose(),this._add.dispose(),this._mult.dispose(),this}}class LT extends Ma{constructor(){super(ct(LT.getDefaults(),arguments)),this.name="Zero",this._gain=new jt({context:this.context}),this.output=this._gain,this.input=void 0,Do(this.context.getConstant(0),this._gain)}dispose(){return super.dispose(),gD(this.context.getConstant(0),this._gain),this}}class Qu extends ft{constructor(){const e=ct(Qu.getDefaults(),arguments,["frequency","min","max"]);super(e),this.name="LFO",this._stoppedValue=0,this._units="number",this.convert=!0,this._fromType=Xt.prototype._fromType,this._toType=Xt.prototype._toType,this._is=Xt.prototype._is,this._clampValue=Xt.prototype._clampValue,this._oscillator=new rr(e),this.frequency=this._oscillator.frequency,this._amplitudeGain=new jt({context:this.context,gain:e.amplitude,units:"normalRange"}),this.amplitude=this._amplitudeGain.gain,this._stoppedSignal=new yn({context:this.context,units:"audioRange",value:0}),this._zeros=new LT({context:this.context}),this._a2g=new _D({context:this.context}),this._scaler=this.output=new OT({context:this.context,max:e.max,min:e.min}),this.units=e.units,this.min=e.min,this.max=e.max,this._oscillator.chain(this._amplitudeGain,this._a2g,this._scaler),this._zeros.connect(this._a2g),this._stoppedSignal.connect(this._a2g),Zt(this,["amplitude","frequency"]),this.phase=e.phase}static getDefaults(){return Object.assign(rr.getDefaults(),{amplitude:1,frequency:"4n",max:1,min:0,type:"sine",units:"number"})}start(e){return e=this.toSeconds(e),this._stoppedSignal.setValueAtTime(0,e),this._oscillator.start(e),this}stop(e){return e=this.toSeconds(e),this._stoppedSignal.setValueAtTime(this._stoppedValue,e),this._oscillator.stop(e),this}sync(){return this._oscillator.sync(),this._oscillator.syncFrequency(),this}unsync(){return this._oscillator.unsync(),this._oscillator.unsyncFrequency(),this}_setStoppedValue(){this._stoppedValue=this._oscillator.getInitialValue(),this._stoppedSignal.value=this._stoppedValue}get min(){return this._toType(this._scaler.min)}set min(e){e=this._fromType(e),this._scaler.min=e}get max(){return this._toType(this._scaler.max)}set max(e){e=this._fromType(e),this._scaler.max=e}get type(){return this._oscillator.type}set type(e){this._oscillator.type=e,this._setStoppedValue()}get partials(){return this._oscillator.partials}set partials(e){this._oscillator.partials=e,this._setStoppedValue()}get phase(){return this._oscillator.phase}set phase(e){this._oscillator.phase=e,this._setStoppedValue()}get units(){return this._units}set units(e){const n=this.min,r=this.max;this._units=e,this.min=n,this.max=r}get state(){return this._oscillator.state}connect(e,n,r){return(e instanceof Xt||e instanceof yn)&&(this.convert=e.convert,this.units=e.units),dy(this,e,n,r),this}dispose(){return super.dispose(),this._oscillator.dispose(),this._stoppedSignal.dispose(),this._zeros.dispose(),this._scaler.dispose(),this._a2g.dispose(),this._amplitudeGain.dispose(),this.amplitude.dispose(),this}}function vD(t,e=1/0){const n=new WeakMap;return function(r,i){Reflect.defineProperty(r,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(s){Aa(s,t,e),n.set(this,s)}})}}function qc(t,e=1/0){const n=new WeakMap;return function(r,i){Reflect.defineProperty(r,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(s){Aa(this.toSeconds(s),t,e),n.set(this,s)}})}}class Sm extends Ti{constructor(){const e=ct(Sm.getDefaults(),arguments,["url","onload"]);super(e),this.name="Player",this._activeSources=new Set,this._buffer=new An({onload:this._onload.bind(this,e.onload),onerror:e.onerror,reverse:e.reverse,url:e.url}),this.autostart=e.autostart,this._loop=e.loop,this._loopStart=e.loopStart,this._loopEnd=e.loopEnd,this._playbackRate=e.playbackRate,this.fadeIn=e.fadeIn,this.fadeOut=e.fadeOut}static getDefaults(){return Object.assign(Ti.getDefaults(),{autostart:!1,fadeIn:0,fadeOut:0,loop:!1,loopEnd:0,loopStart:0,onload:En,onerror:En,playbackRate:1,reverse:!1})}load(e){return _r(this,void 0,void 0,function*(){return yield this._buffer.load(e),this._onload(),this})}_onload(e=En){e(),this.autostart&&this.start()}_onSourceEnd(e){this.onstop(this),this._activeSources.delete(e),this._activeSources.size===0&&!this._synced&&this._state.getValueAtTime(this.now())==="started"&&(this._state.cancel(this.now()),this._state.setStateAtTime("stopped",this.now()))}start(e,n,r){return super.start(e,n,r),this}_start(e,n,r){this._loop?n=Sa(n,this._loopStart):n=Sa(n,0);const i=this.toSeconds(n),s=r;r=Sa(r,Math.max(this._buffer.duration-i,0));let o=this.toSeconds(r);o=o/this._playbackRate,e=this.toSeconds(e);const a=new ym({url:this._buffer,context:this.context,fadeIn:this.fadeIn,fadeOut:this.fadeOut,loop:this._loop,loopEnd:this._loopEnd,loopStart:this._loopStart,onended:this._onSourceEnd.bind(this),playbackRate:this._playbackRate}).connect(this.output);!this._loop&&!this._synced&&(this._state.cancel(e+o),this._state.setStateAtTime("stopped",e+o,{implicitEnd:!0})),this._activeSources.add(a),this._loop&&Ps(s)?a.start(e,i):a.start(e,i,o-this.toSeconds(this.fadeOut))}_stop(e){const n=this.toSeconds(e);this._activeSources.forEach(r=>r.stop(n))}restart(e,n,r){return super.restart(e,n,r),this}_restart(e,n,r){var i;(i=[...this._activeSources].pop())===null||i===void 0||i.stop(e),this._start(e,n,r)}seek(e,n){const r=this.toSeconds(n);if(this._state.getValueAtTime(r)==="started"){const i=this.toSeconds(e);this._stop(r),this._start(r,i)}return this}setLoopPoints(e,n){return this.loopStart=e,this.loopEnd=n,this}get loopStart(){return this._loopStart}set loopStart(e){this._loopStart=e,this.buffer.loaded&&Aa(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(n=>{n.loopStart=e})}get loopEnd(){return this._loopEnd}set loopEnd(e){this._loopEnd=e,this.buffer.loaded&&Aa(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(n=>{n.loopEnd=e})}get buffer(){return this._buffer}set buffer(e){this._buffer.set(e)}get loop(){return this._loop}set loop(e){if(this._loop!==e&&(this._loop=e,this._activeSources.forEach(n=>{n.loop=e}),e)){const n=this._state.getNextState("stopped",this.now());n&&this._state.cancel(n.time)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e;const n=this.now(),r=this._state.getNextState("stopped",n);r&&r.implicitEnd&&(this._state.cancel(r.time),this._activeSources.forEach(i=>i.cancelStop())),this._activeSources.forEach(i=>{i.playbackRate.setValueAtTime(e,n)})}get reverse(){return this._buffer.reverse}set reverse(e){this._buffer.reverse=e}get loaded(){return this._buffer.loaded}dispose(){return super.dispose(),this._activeSources.forEach(e=>e.dispose()),this._activeSources.clear(),this._buffer.dispose(),this}}Go([qc(0)],Sm.prototype,"fadeIn",void 0);Go([qc(0)],Sm.prototype,"fadeOut",void 0);class rne extends Ma{constructor(){super(...arguments),this.name="GainToAudio",this._norm=new mh({context:this.context,mapping:e=>Math.abs(e)*2-1}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class Xc extends ft{constructor(){const e=ct(Xc.getDefaults(),arguments,["attack","decay","sustain","release"]);super(e),this.name="Envelope",this._sig=new yn({context:this.context,value:0}),this.output=this._sig,this.input=void 0,this.attack=e.attack,this.decay=e.decay,this.sustain=e.sustain,this.release=e.release,this.attackCurve=e.attackCurve,this.releaseCurve=e.releaseCurve,this.decayCurve=e.decayCurve}static getDefaults(){return Object.assign(ft.getDefaults(),{attack:.01,attackCurve:"linear",decay:.1,decayCurve:"exponential",release:1,releaseCurve:"exponential",sustain:.5})}get value(){return this.getValueAtTime(this.now())}_getCurve(e,n){if(Lc(e))return e;{let r;for(r in w0)if(w0[r][n]===e)return r;return e}}_setCurve(e,n,r){if(Lc(r)&&Reflect.has(w0,r)){const i=w0[r];Al(i)?e!=="_decayCurve"&&(this[e]=i[n]):this[e]=i}else if(us(r)&&e!=="_decayCurve")this[e]=r;else throw new Error("Envelope: invalid curve: "+r)}get attackCurve(){return this._getCurve(this._attackCurve,"In")}set attackCurve(e){this._setCurve("_attackCurve","In",e)}get releaseCurve(){return this._getCurve(this._releaseCurve,"Out")}set releaseCurve(e){this._setCurve("_releaseCurve","Out",e)}get decayCurve(){return this._getCurve(this._decayCurve,"Out")}set decayCurve(e){this._setCurve("_decayCurve","Out",e)}triggerAttack(e,n=1){this.log("triggerAttack",e,n),e=this.toSeconds(e);let i=this.toSeconds(this.attack);const s=this.toSeconds(this.decay),o=this.getValueAtTime(e);if(o>0){const a=1/i;i=(1-o)/a}if(i0){const r=this.toSeconds(this.release);r{let e,n;const r=[];for(e=0;e<128;e++)r[e]=Math.sin(e/127*(Math.PI/2));const i=[],s=6.4;for(e=0;e<127;e++){n=e/127;const p=Math.sin(n*(Math.PI*2)*s-Math.PI/2)+1;i[e]=p/10+n*.83}i[127]=1;const o=[],a=5;for(e=0;e<128;e++)o[e]=Math.ceil(e/127*a)/a;const c=[];for(e=0;e<128;e++)n=e/127,c[e]=.5*(1-Math.cos(Math.PI*n));const l=[];for(e=0;e<128;e++){n=e/127;const p=Math.pow(n,3)*4+.2,m=Math.cos(p*Math.PI*2*n);l[e]=Math.abs(m*(1-n))}function u(p){const m=new Array(p.length);for(let g=0;gthis._original_triggerRelease(n),this._volume=this.output=new Ll({context:this.context,volume:e.volume}),this.volume=this._volume.volume,Zt(this,"volume")}static getDefaults(){return Object.assign(ft.getDefaults(),{volume:0})}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",0),this.context.transport.on("stop",this._syncedRelease),this.context.transport.on("pause",this._syncedRelease),this.context.transport.on("loopEnd",this._syncedRelease)),this}_syncState(){let e=!1;return this._synced||(this._synced=!0,e=!0),e}_syncMethod(e,n){const r=this["_original_"+e]=this[e];this[e]=(...i)=>{const s=i[n],o=this.context.transport.schedule(a=>{i[n]=a,r.apply(this,i)},s);this._scheduledEvents.push(o)}}unsync(){return this._scheduledEvents.forEach(e=>this.context.transport.clear(e)),this._scheduledEvents=[],this._synced&&(this._synced=!1,this.triggerAttack=this._original_triggerAttack,this.triggerRelease=this._original_triggerRelease,this.context.transport.off("stop",this._syncedRelease),this.context.transport.off("pause",this._syncedRelease),this.context.transport.off("loopEnd",this._syncedRelease)),this}triggerAttackRelease(e,n,r,i){const s=this.toSeconds(r),o=this.toSeconds(n);return this.triggerAttack(e,s,i),this.triggerRelease(s+o),this}dispose(){return super.dispose(),this._volume.dispose(),this.unsync(),this._scheduledEvents=[],this}}class eh extends Ca{constructor(){const e=ct(eh.getDefaults(),arguments);super(e),this.portamento=e.portamento,this.onsilence=e.onsilence}static getDefaults(){return Object.assign(Ca.getDefaults(),{detune:0,onsilence:En,portamento:0})}triggerAttack(e,n,r=1){this.log("triggerAttack",e,n,r);const i=this.toSeconds(n);return this._triggerEnvelopeAttack(i,r),this.setNote(e,i),this}triggerRelease(e){this.log("triggerRelease",e);const n=this.toSeconds(e);return this._triggerEnvelopeRelease(n),this}setNote(e,n){const r=this.toSeconds(n),i=e instanceof ss?e.toFrequency():e;if(this.portamento>0&&this.getLevelAtTime(r)>.05){const s=this.toSeconds(this.portamento);this.frequency.exponentialRampTo(i,s,r)}else this.frequency.setValueAtTime(i,r);return this}}Go([qc(0)],eh.prototype,"portamento",void 0);class xy extends Xc{constructor(){super(ct(xy.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="AmplitudeEnvelope",this._gainNode=new jt({context:this.context,gain:0}),this.output=this._gainNode,this.input=this._gainNode,this._sig.connect(this._gainNode.gain),this.output=this._gainNode,this.input=this._gainNode}dispose(){return super.dispose(),this._gainNode.dispose(),this}}class Li extends eh{constructor(){const e=ct(Li.getDefaults(),arguments);super(e),this.name="Synth",this.oscillator=new J_(Object.assign({context:this.context,detune:e.detune,onstop:()=>this.onsilence(this)},e.oscillator)),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.envelope=new xy(Object.assign({context:this.context},e.envelope)),this.oscillator.chain(this.envelope,this.output),Zt(this,["oscillator","frequency","detune","envelope"])}static getDefaults(){return Object.assign(eh.getDefaults(),{envelope:Object.assign(Op(Xc.getDefaults(),Object.keys(ft.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.3}),oscillator:Object.assign(Op(J_.getDefaults(),[...Object.keys(Ti.getDefaults()),"frequency","detune"]),{type:"triangle"})})}_triggerEnvelopeAttack(e,n){if(this.envelope.triggerAttack(e,n),this.oscillator.start(e),this.envelope.sustain===0){const r=this.toSeconds(this.envelope.attack),i=this.toSeconds(this.envelope.decay);this.oscillator.stop(e+r+i)}}_triggerEnvelopeRelease(e){this.envelope.triggerRelease(e),this.oscillator.stop(e+this.toSeconds(this.envelope.release))}getLevelAtTime(e){return e=this.toSeconds(e),this.envelope.getValueAtTime(e)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this}}class Q_ extends ft{constructor(){const e=ct(Q_.getDefaults(),arguments,["frequency","type"]);super(e),this.name="BiquadFilter",this._filter=this.context.createBiquadFilter(),this.input=this.output=this._filter,this.Q=new Xt({context:this.context,units:"number",value:e.Q,param:this._filter.Q}),this.frequency=new Xt({context:this.context,units:"frequency",value:e.frequency,param:this._filter.frequency}),this.detune=new Xt({context:this.context,units:"cents",value:e.detune,param:this._filter.detune}),this.gain=new Xt({context:this.context,units:"decibels",convert:!1,value:e.gain,param:this._filter.gain}),this.type=e.type}static getDefaults(){return Object.assign(ft.getDefaults(),{Q:1,type:"lowpass",frequency:350,detune:0,gain:0})}get type(){return this._filter.type}set type(e){bt(["lowpass","highpass","bandpass","lowshelf","highshelf","notch","allpass","peaking"].indexOf(e)!==-1,`Invalid filter type: ${e}`),this._filter.type=e}getFrequencyResponse(e=128){const n=new Float32Array(e);for(let o=0;or.type=e)}get rolloff(){return this._rolloff}set rolloff(e){const n=Po(e)?e:parseInt(e,10),r=[-12,-24,-48,-96];let i=r.indexOf(n);bt(i!==-1,`rolloff can only be ${r.join(", ")}`),i+=1,this._rolloff=n,this.input.disconnect(),this._filters.forEach(s=>s.disconnect()),this._filters=new Array(i);for(let s=0;s1);return this._filters.forEach(()=>{n.getFrequencyResponse(e).forEach((s,o)=>r[o]*=s)}),n.dispose(),r}dispose(){return super.dispose(),this._filters.forEach(e=>{e.dispose()}),_m(this,["detune","frequency","gain","Q"]),this.frequency.dispose(),this.Q.dispose(),this.detune.dispose(),this.gain.dispose(),this}}class Em extends Li{constructor(){const e=ct(Em.getDefaults(),arguments);super(e),this.name="MembraneSynth",this.portamento=0,this.pitchDecay=e.pitchDecay,this.octaves=e.octaves,Zt(this,["oscillator","envelope"])}static getDefaults(){return Vu(eh.getDefaults(),Li.getDefaults(),{envelope:{attack:.001,attackCurve:"exponential",decay:.4,release:1.4,sustain:.01},octaves:10,oscillator:{type:"sine"},pitchDecay:.05})}setNote(e,n){const r=this.toSeconds(n),i=this.toFrequency(e instanceof ss?e.toFrequency():e),s=i*this.octaves;return this.oscillator.frequency.setValueAtTime(s,r),this.oscillator.frequency.exponentialRampToValueAtTime(i,r+this.toSeconds(this.pitchDecay)),this}dispose(){return super.dispose(),this}}Go([vD(0)],Em.prototype,"octaves",void 0);Go([qc(0)],Em.prototype,"pitchDecay",void 0);class gf extends Ca{constructor(){const e=ct(gf.getDefaults(),arguments);super(e),this.name="NoiseSynth",this.noise=new Yf(Object.assign({context:this.context},e.noise)),this.envelope=new xy(Object.assign({context:this.context},e.envelope)),this.noise.chain(this.envelope,this.output)}static getDefaults(){return Object.assign(Ca.getDefaults(),{envelope:Object.assign(Op(Xc.getDefaults(),Object.keys(ft.getDefaults())),{decay:.1,sustain:0}),noise:Object.assign(Op(Yf.getDefaults(),Object.keys(Ti.getDefaults())),{type:"white"})})}triggerAttack(e,n=1){return e=this.toSeconds(e),this.envelope.triggerAttack(e,n),this.noise.start(e),this.envelope.sustain===0&&this.noise.stop(e+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay)),this}triggerRelease(e){return e=this.toSeconds(e),this.envelope.triggerRelease(e),this.noise.stop(e+this.toSeconds(this.envelope.release)),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",0),this._syncMethod("triggerRelease",0)),this}triggerAttackRelease(e,n,r=1){return n=this.toSeconds(n),e=this.toSeconds(e),this.triggerAttack(n,r),this.triggerRelease(n+e),this}dispose(){return super.dispose(),this.noise.dispose(),this.envelope.dispose(),this}}const yD=new Set;function PT(t){yD.add(t)}function xD(t,e){const n=`registerProcessor("${t}", ${e})`;yD.add(n)}const ine=` - /** - * The base AudioWorkletProcessor for use in Tone.js. Works with the {@link ToneAudioWorklet}. - */ - class ToneAudioWorkletProcessor extends AudioWorkletProcessor { - - constructor(options) { - - super(options); - /** - * If the processor was disposed or not. Keep alive until it's disposed. - */ - this.disposed = false; - /** - * The number of samples in the processing block - */ - this.blockSize = 128; - /** - * the sample rate - */ - this.sampleRate = sampleRate; - - this.port.onmessage = (event) => { - // when it receives a dispose - if (event.data === "dispose") { - this.disposed = true; - } - }; - } - } -`;PT(ine);const sne=` - /** - * Abstract class for a single input/output processor. - * has a 'generate' function which processes one sample at a time - */ - class SingleIOProcessor extends ToneAudioWorkletProcessor { - - constructor(options) { - super(Object.assign(options, { - numberOfInputs: 1, - numberOfOutputs: 1 - })); - /** - * Holds the name of the parameter and a single value of that - * parameter at the current sample - * @type { [name: string]: number } - */ - this.params = {} - } - - /** - * Generate an output sample from the input sample and parameters - * @abstract - * @param input number - * @param channel number - * @param parameters { [name: string]: number } - * @returns number - */ - generate(){} - - /** - * Update the private params object with the - * values of the parameters at the given index - * @param parameters { [name: string]: Float32Array }, - * @param index number - */ - updateParams(parameters, index) { - for (const paramName in parameters) { - const param = parameters[paramName]; - if (param.length > 1) { - this.params[paramName] = parameters[paramName][index]; - } else { - this.params[paramName] = parameters[paramName][0]; - } - } - } - - /** - * Process a single frame of the audio - * @param inputs Float32Array[][] - * @param outputs Float32Array[][] - */ - process(inputs, outputs, parameters) { - const input = inputs[0]; - const output = outputs[0]; - // get the parameter values - const channelCount = Math.max(input && input.length || 0, output.length); - for (let sample = 0; sample < this.blockSize; sample++) { - this.updateParams(parameters, sample); - for (let channel = 0; channel < channelCount; channel++) { - const inputSample = input && input.length ? input[channel][sample] : 0; - output[channel][sample] = this.generate(inputSample, channel, this.params); - } - } - return !this.disposed; - } - }; -`;PT(sne);const one=` - /** - * A multichannel buffer for use within an AudioWorkletProcessor as a delay line - */ - class DelayLine { - - constructor(size, channels) { - this.buffer = []; - this.writeHead = [] - this.size = size; - - // create the empty channels - for (let i = 0; i < channels; i++) { - this.buffer[i] = new Float32Array(this.size); - this.writeHead[i] = 0; - } - } - - /** - * Push a value onto the end - * @param channel number - * @param value number - */ - push(channel, value) { - this.writeHead[channel] += 1; - if (this.writeHead[channel] > this.size) { - this.writeHead[channel] = 0; - } - this.buffer[channel][this.writeHead[channel]] = value; - } - - /** - * Get the recorded value of the channel given the delay - * @param channel number - * @param delay number delay samples - */ - get(channel, delay) { - let readHead = this.writeHead[channel] - Math.floor(delay); - if (readHead < 0) { - readHead += this.size; - } - return this.buffer[channel][readHead]; - } - } -`;PT(one);const ane="feedback-comb-filter",cne=` - class FeedbackCombFilterWorklet extends SingleIOProcessor { - - constructor(options) { - super(options); - this.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2); - } - - static get parameterDescriptors() { - return [{ - name: "delayTime", - defaultValue: 0.1, - minValue: 0, - maxValue: 1, - automationRate: "k-rate" - }, { - name: "feedback", - defaultValue: 0.5, - minValue: 0, - maxValue: 0.9999, - automationRate: "k-rate" - }]; - } - - generate(input, channel, parameters) { - const delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate); - this.delayLine.push(channel, input + delayedSample * parameters.feedback); - return delayedSample; - } - } -`;xD(ane,cne);class ev extends Ca{constructor(){const e=ct(ev.getDefaults(),arguments,["voice","options"]);super(e),this.name="PolySynth",this._availableVoices=[],this._activeVoices=[],this._voices=[],this._gcTimeout=-1,this._averageActiveVoices=0,this._syncedRelease=i=>this.releaseAll(i),bt(!Po(e.voice),"DEPRECATED: The polyphony count is no longer the first argument.");const n=e.voice.getDefaults();this.options=Object.assign(n,e.options),this.voice=e.voice,this.maxPolyphony=e.maxPolyphony,this._dummyVoice=this._getNextAvailableVoice();const r=this._voices.indexOf(this._dummyVoice);this._voices.splice(r,1),this._gcTimeout=this.context.setInterval(this._collectGarbage.bind(this),1)}static getDefaults(){return Object.assign(Ca.getDefaults(),{maxPolyphony:32,options:{},voice:Li})}get activeVoices(){return this._activeVoices.length}_makeVoiceAvailable(e){this._availableVoices.push(e);const n=this._activeVoices.findIndex(r=>r.voice===e);this._activeVoices.splice(n,1)}_getNextAvailableVoice(){if(this._availableVoices.length)return this._availableVoices.shift();if(this._voices.lengthMath.ceil(this._averageActiveVoices+1)){const e=this._availableVoices.shift(),n=this._voices.indexOf(e);this._voices.splice(n,1),this.context.isOffline||e.dispose()}}_triggerAttack(e,n,r){e.forEach(i=>{const s=new Z_(this.context,i).toMidi(),o=this._getNextAvailableVoice();o&&(o.triggerAttack(i,n,r),this._activeVoices.push({midi:s,voice:o,released:!1}),this.log("triggerAttack",i,n))})}_triggerRelease(e,n){e.forEach(r=>{const i=new Z_(this.context,r).toMidi(),s=this._activeVoices.find(({midi:o,released:a})=>o===i&&!a);s&&(s.voice.triggerRelease(n),s.released=!0,this.log("triggerRelease",r,n))})}_scheduleEvent(e,n,r,i){bt(!this.disposed,"Synth was already disposed"),r<=this.now()?e==="attack"?this._triggerAttack(n,r,i):this._triggerRelease(n,r):this.context.setTimeout(()=>{this.disposed||this._scheduleEvent(e,n,r,i)},r-this.now())}triggerAttack(e,n,r){Array.isArray(e)||(e=[e]);const i=this.toSeconds(n);return this._scheduleEvent("attack",e,i,r),this}triggerRelease(e,n){Array.isArray(e)||(e=[e]);const r=this.toSeconds(n);return this._scheduleEvent("release",e,r),this}triggerAttackRelease(e,n,r,i){const s=this.toSeconds(r);if(this.triggerAttack(e,s,i),us(n)){bt(us(e),"If the duration is an array, the notes must also be an array"),e=e;for(let o=0;o0,"The duration must be greater than 0"),this.triggerRelease(e[o],s+c)}}else{const o=this.toSeconds(n);bt(o>0,"The duration must be greater than 0"),this.triggerRelease(e,s+o)}return this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1),this.context.transport.on("stop",this._syncedRelease),this.context.transport.on("pause",this._syncedRelease),this.context.transport.on("loopEnd",this._syncedRelease)),this}set(e){const n=Op(e,["onsilence","context"]);return this.options=Vu(this.options,n),this._voices.forEach(r=>r.set(n)),this._dummyVoice.set(n),this}get(){return this._dummyVoice.get()}releaseAll(e){const n=this.toSeconds(e);return this._activeVoices.forEach(({voice:r})=>{r.triggerRelease(n)}),this}dispose(){return super.dispose(),this._dummyVoice.dispose(),this._voices.forEach(e=>e.dispose()),this._activeVoices=[],this._availableVoices=[],this.context.clearInterval(this._gcTimeout),this}}class Sy extends Ca{constructor(){const e=ct(Sy.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");super(e),this.name="Sampler",this._activeSources=new Map;const n={};Object.keys(e.urls).forEach(r=>{const i=parseInt(r,10);if(bt(E0(r)||Po(i)&&isFinite(i),`url key is neither a note or midi pitch: ${r}`),E0(r)){const s=new ss(this.context,r).toMidi();n[s]=e.urls[r]}else Po(i)&&isFinite(i)&&(n[i]=e.urls[i])}),this._buffers=new CT({urls:n,onload:e.onload,baseUrl:e.baseUrl,onerror:e.onerror}),this.attack=e.attack,this.release=e.release,this.curve=e.curve,this._buffers.loaded&&Promise.resolve().then(e.onload)}static getDefaults(){return Object.assign(Ca.getDefaults(),{attack:0,baseUrl:"",curve:"exponential",onload:En,onerror:En,release:.1,urls:{}})}_findClosest(e){let r=0;for(;r<96;){if(this._buffers.has(e+r))return-r;if(this._buffers.has(e-r))return r;r++}throw new Error(`No available buffers for note: ${e}`)}triggerAttack(e,n,r=1){return this.log("triggerAttack",e,n,r),Array.isArray(e)||(e=[e]),e.forEach(i=>{const s=pD(new ss(this.context,i).toFrequency()),o=Math.round(s),a=s-o,c=this._findClosest(o),l=o-c,u=this._buffers.get(l),h=dD(c+a),p=new ym({url:u,context:this.context,curve:this.curve,fadeIn:this.attack,fadeOut:this.release,playbackRate:h}).connect(this.output);p.start(n,0,u.duration/h,r),us(this._activeSources.get(o))||this._activeSources.set(o,[]),this._activeSources.get(o).push(p),p.onended=()=>{if(this._activeSources&&this._activeSources.has(o)){const m=this._activeSources.get(o),g=m.indexOf(p);g!==-1&&m.splice(g,1)}}}),this}triggerRelease(e,n){return this.log("triggerRelease",e,n),Array.isArray(e)||(e=[e]),e.forEach(r=>{const i=new ss(this.context,r).toMidi();if(this._activeSources.has(i)&&this._activeSources.get(i).length){const s=this._activeSources.get(i);n=this.toSeconds(n),s.forEach(o=>{o.stop(n)}),this._activeSources.set(i,[])}}),this}releaseAll(e){const n=this.toSeconds(e);return this._activeSources.forEach(r=>{for(;r.length;)r.shift().stop(n)}),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1)),this}triggerAttackRelease(e,n,r,i=1){const s=this.toSeconds(r);return this.triggerAttack(e,s,i),us(n)?(bt(us(e),"notes must be an array when duration is array"),e.forEach((o,a)=>{const c=n[Math.min(a,n.length-1)];this.triggerRelease(o,s+this.toSeconds(c))})):this.triggerRelease(e,s+this.toSeconds(n)),this}add(e,n,r){if(bt(E0(e)||isFinite(e),`note must be a pitch or midi: ${e}`),E0(e)){const i=new ss(this.context,e).toMidi();this._buffers.add(i,n,r)}else this._buffers.add(e,n,r);return this}get loaded(){return this._buffers.loaded}dispose(){return super.dispose(),this._buffers.dispose(),this._activeSources.forEach(e=>{e.forEach(n=>n.dispose())}),this._activeSources.clear(),this}}Go([qc(0)],Sy.prototype,"attack",void 0);Go([qc(0)],Sy.prototype,"release",void 0);class _f extends Ei{constructor(){const e=ct(_f.getDefaults(),arguments,["callback","value"]);super(e),this.name="ToneEvent",this._state=new vm("stopped"),this._startOffset=0,this._loop=e.loop,this.callback=e.callback,this.value=e.value,this._loopStart=this.toTicks(e.loopStart),this._loopEnd=this.toTicks(e.loopEnd),this._playbackRate=e.playbackRate,this._probability=e.probability,this._humanize=e.humanize,this.mute=e.mute,this._playbackRate=e.playbackRate,this._state.increasing=!0,this._rescheduleEvents()}static getDefaults(){return Object.assign(Ei.getDefaults(),{callback:En,humanize:!1,loop:!1,loopEnd:"1m",loopStart:0,mute:!1,playbackRate:1,probability:1,value:null})}_rescheduleEvents(e=-1){this._state.forEachFrom(e,n=>{let r;if(n.state==="started"){n.id!==-1&&this.context.transport.clear(n.id);const i=n.time+Math.round(this.startOffset/this._playbackRate);if(this._loop===!0||Po(this._loop)&&this._loop>1){r=1/0,Po(this._loop)&&(r=this._loop*this._getLoopDuration());const s=this._state.getAfter(i);s!==null&&(r=Math.min(r,s.time-i)),r!==1/0&&(r=new Dr(this.context,r));const o=new Dr(this.context,this._getLoopDuration());n.id=this.context.transport.scheduleRepeat(this._tick.bind(this),o,new Dr(this.context,i),r)}else n.id=this.context.transport.schedule(this._tick.bind(this),new Dr(this.context,i))}})}get state(){return this._state.getValueAtTime(this.context.transport.ticks)}get startOffset(){return this._startOffset}set startOffset(e){this._startOffset=e}get probability(){return this._probability}set probability(e){this._probability=e}get humanize(){return this._humanize}set humanize(e){this._humanize=e}start(e){const n=this.toTicks(e);return this._state.getValueAtTime(n)==="stopped"&&(this._state.add({id:-1,state:"started",time:n}),this._rescheduleEvents(n)),this}stop(e){this.cancel(e);const n=this.toTicks(e);if(this._state.getValueAtTime(n)==="started"){this._state.setStateAtTime("stopped",n,{id:-1});const r=this._state.getBefore(n);let i=n;r!==null&&(i=r.time),this._rescheduleEvents(i)}return this}cancel(e){e=Sa(e,-1/0);const n=this.toTicks(e);return this._state.forEachFrom(n,r=>{this.context.transport.clear(r.id)}),this._state.cancel(n),this}_tick(e){const n=this.context.transport.getTicksAtTime(e);if(!this.mute&&this._state.getValueAtTime(n)==="started"){if(this.probability<1&&Math.random()>this.probability)return;if(this.humanize){let r=.02;sD(this.humanize)||(r=this.toSeconds(this.humanize)),e+=(Math.random()*2-1)*r}this.callback(e,this.value)}}_getLoopDuration(){return(this._loopEnd-this._loopStart)/this._playbackRate}get loop(){return this._loop}set loop(e){this._loop=e,this._rescheduleEvents()}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._rescheduleEvents()}get loopEnd(){return new Dr(this.context,this._loopEnd).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e),this._loop&&this._rescheduleEvents()}get loopStart(){return new Dr(this.context,this._loopStart).toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e),this._loop&&this._rescheduleEvents()}get progress(){if(this._loop){const e=this.context.transport.ticks,n=this._state.get(e);if(n!==null&&n.state==="started"){const r=this._getLoopDuration();return(e-n.time)%r/r}else return 0}else return 0}dispose(){return super.dispose(),this.cancel(),this._state.dispose(),this}}class tv extends _f{constructor(){const e=ct(tv.getDefaults(),arguments,["callback","events"]);super(e),this.name="Part",this._state=new vm("stopped"),this._events=new Set,this._state.increasing=!0,e.events.forEach(n=>{us(n)?this.add(n[0],n[1]):this.add(n)})}static getDefaults(){return Object.assign(_f.getDefaults(),{events:[]})}start(e,n){const r=this.toTicks(e);if(this._state.getValueAtTime(r)!=="started"){n=Sa(n,this._loop?this._loopStart:0),this._loop?n=Sa(n,this._loopStart):n=Sa(n,0);const i=this.toTicks(n);this._state.add({id:-1,offset:i,state:"started",time:r}),this._forEach(s=>{this._startNote(s,r,i)})}return this}_startNote(e,n,r){n-=r,this._loop?e.startOffset>=this._loopStart&&e.startOffset=r&&(e.loop=!1,e.start(new Dr(this.context,n))):e.startOffset>=r&&e.start(new Dr(this.context,n))}get startOffset(){return this._startOffset}set startOffset(e){this._startOffset=e,this._forEach(n=>{n.startOffset+=this._startOffset})}stop(e){const n=this.toTicks(e);return this._state.cancel(n),this._state.setStateAtTime("stopped",n),this._forEach(r=>{r.stop(e)}),this}at(e,n){const r=new Mf(this.context,e).toTicks(),i=new Dr(this.context,1).toSeconds(),s=this._events.values();let o=s.next();for(;!o.done;){const a=o.value;if(Math.abs(r-a.startOffset){n.state==="started"?this._startNote(e,n.time,n.offset):e.stop(new Dr(this.context,n.time))})}remove(e,n){return Al(e)&&e.hasOwnProperty("time")&&(n=e,e=n.time),e=this.toTicks(e),this._events.forEach(r=>{r.startOffset===e&&(Ps(n)||Wt(n)&&r.value===n)&&(this._events.delete(r),r.dispose())}),this}clear(){return this._forEach(e=>e.dispose()),this._events.clear(),this}cancel(e){return this._forEach(n=>n.cancel(e)),this._state.cancel(this.toTicks(e)),this}_forEach(e){return this._events&&this._events.forEach(n=>{n instanceof tv?n._forEach(e):e(n)}),this}_setAll(e,n){this._forEach(r=>{r[e]=n})}_tick(e,n){this.mute||this.callback(e,n)}_testLoopBoundries(e){this._loop&&(e.startOffset=this._loopEnd)?e.cancel(0):e.state==="stopped"&&this._restartEvent(e)}get probability(){return this._probability}set probability(e){this._probability=e,this._setAll("probability",e)}get humanize(){return this._humanize}set humanize(e){this._humanize=e,this._setAll("humanize",e)}get loop(){return this._loop}set loop(e){this._loop=e,this._forEach(n=>{n.loopStart=this.loopStart,n.loopEnd=this.loopEnd,n.loop=e,this._testLoopBoundries(n)})}get loopEnd(){return new Dr(this.context,this._loopEnd).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e),this._loop&&this._forEach(n=>{n.loopEnd=e,this._testLoopBoundries(n)})}get loopStart(){return new Dr(this.context,this._loopStart).toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e),this._loop&&this._forEach(n=>{n.loopStart=this.loopStart,this._testLoopBoundries(n)})}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this._setAll("playbackRate",e)}get length(){return this._events.size}dispose(){return super.dispose(),this.clear(),this}}class Ey extends ft{constructor(){const e=ct(Ey.getDefaults(),arguments,["fade"]);super(e),this.name="CrossFade",this._panner=this.context.createStereoPanner(),this._split=this.context.createChannelSplitter(2),this._g2a=new rne({context:this.context}),this.a=new jt({context:this.context,gain:0}),this.b=new jt({context:this.context,gain:0}),this.output=new jt({context:this.context}),this._internalChannels=[this.a,this.b],this.fade=new yn({context:this.context,units:"normalRange",value:e.fade}),Zt(this,"fade"),this.context.getConstant(1).connect(this._panner),this._panner.connect(this._split),this._panner.channelCount=1,this._panner.channelCountMode="explicit",Do(this._split,this.a.gain,0),Do(this._split,this.b.gain,1),this.fade.chain(this._g2a,this._panner.pan),this.a.connect(this.output),this.b.connect(this.output)}static getDefaults(){return Object.assign(ft.getDefaults(),{fade:.5})}dispose(){return super.dispose(),this.a.dispose(),this.b.dispose(),this.output.dispose(),this.fade.dispose(),this._g2a.dispose(),this._panner.disconnect(),this._split.disconnect(),this}}let Dl=class extends ft{constructor(e){super(e),this.name="Effect",this._dryWet=new Ey({context:this.context}),this.wet=this._dryWet.fade,this.effectSend=new jt({context:this.context}),this.effectReturn=new jt({context:this.context}),this.input=new jt({context:this.context}),this.output=this._dryWet,this.input.fan(this._dryWet.a,this.effectSend),this.effectReturn.connect(this._dryWet.b),this.wet.setValueAtTime(e.wet,0),this._internalChannels=[this.effectReturn,this.effectSend],Zt(this,"wet")}static getDefaults(){return Object.assign(ft.getDefaults(),{wet:1})}connectEffect(e){return this._internalChannels.push(e),this.effectSend.chain(e,this.effectReturn),this}dispose(){return super.dispose(),this._dryWet.dispose(),this.effectSend.dispose(),this.effectReturn.dispose(),this.wet.dispose(),this}};class DT extends ft{constructor(){const e=ct(DT.getDefaults(),arguments,["pan"]);super(e),this.name="Panner",this._panner=this.context.createStereoPanner(),this.input=this._panner,this.output=this._panner,this.pan=new Xt({context:this.context,param:this._panner.pan,value:e.pan,minValue:-1,maxValue:1}),this._panner.channelCount=e.channelCount,this._panner.channelCountMode="explicit",Zt(this,"pan")}static getDefaults(){return Object.assign(ft.getDefaults(),{pan:0,channelCount:1})}dispose(){return super.dispose(),this._panner.disconnect(),this.pan.dispose(),this}}const lne="bit-crusher",une=` - class BitCrusherWorklet extends SingleIOProcessor { - - static get parameterDescriptors() { - return [{ - name: "bits", - defaultValue: 12, - minValue: 1, - maxValue: 16, - automationRate: 'k-rate' - }]; - } - - generate(input, _channel, parameters) { - const step = Math.pow(0.5, parameters.bits - 1); - const val = step * Math.floor(input / step + 0.5); - return val; - } - } -`;xD(lne,une);class wy extends ft{constructor(){const e=ct(wy.getDefaults(),arguments,["channels"]);super(e),this.name="Split",this._splitter=this.input=this.output=this.context.createChannelSplitter(e.channels),this._internalChannels=[this._splitter]}static getDefaults(){return Object.assign(ft.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._splitter.disconnect(),this}}class wm extends ft{constructor(){const e=ct(wm.getDefaults(),arguments,["channels"]);super(e),this.name="Merge",this._merger=this.output=this.input=this.context.createChannelMerger(e.channels)}static getDefaults(){return Object.assign(ft.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._merger.disconnect(),this}}class nv extends ft{constructor(e){super(e),this.name="StereoEffect",this.input=new jt({context:this.context}),this.input.channelCount=2,this.input.channelCountMode="explicit",this._dryWet=this.output=new Ey({context:this.context,fade:e.wet}),this.wet=this._dryWet.fade,this._split=new wy({context:this.context,channels:2}),this._merge=new wm({context:this.context,channels:2}),this.input.connect(this._split),this.input.connect(this._dryWet.a),this._merge.connect(this._dryWet.b),Zt(this,["wet"])}connectEffectLeft(...e){this._split.connect(e[0],0,0),Zu(...e),Do(e[e.length-1],this._merge,0,0)}connectEffectRight(...e){this._split.connect(e[0],1,0),Zu(...e),Do(e[e.length-1],this._merge,0,1)}static getDefaults(){return Object.assign(ft.getDefaults(),{wet:1})}dispose(){return super.dispose(),this._dryWet.dispose(),this._split.dispose(),this._merge.dispose(),this}}class yN extends nv{constructor(e){super(e),this.feedback=new yn({context:this.context,value:e.feedback,units:"normalRange"}),this._feedbackL=new jt({context:this.context}),this._feedbackR=new jt({context:this.context}),this._feedbackSplit=new wy({context:this.context,channels:2}),this._feedbackMerge=new wm({context:this.context,channels:2}),this._merge.connect(this._feedbackSplit),this._feedbackMerge.connect(this._split),this._feedbackSplit.connect(this._feedbackL,0,0),this._feedbackL.connect(this._feedbackMerge,0,0),this._feedbackSplit.connect(this._feedbackR,1,0),this._feedbackR.connect(this._feedbackMerge,0,1),this.feedback.fan(this._feedbackL.gain,this._feedbackR.gain),Zt(this,["feedback"])}static getDefaults(){return Object.assign(nv.getDefaults(),{feedback:.5})}dispose(){return super.dispose(),this.feedback.dispose(),this._feedbackL.dispose(),this._feedbackR.dispose(),this._feedbackSplit.dispose(),this._feedbackMerge.dispose(),this}}class UT extends yN{constructor(){const e=ct(UT.getDefaults(),arguments,["frequency","delayTime","depth"]);super(e),this.name="Chorus",this._depth=e.depth,this._delayTime=e.delayTime/1e3,this._lfoL=new Qu({context:this.context,frequency:e.frequency,min:0,max:1}),this._lfoR=new Qu({context:this.context,frequency:e.frequency,min:0,max:1,phase:180}),this._delayNodeL=new Kf({context:this.context}),this._delayNodeR=new Kf({context:this.context}),this.frequency=this._lfoL.frequency,Zt(this,["frequency"]),this._lfoL.frequency.connect(this._lfoR.frequency),this.connectEffectLeft(this._delayNodeL),this.connectEffectRight(this._delayNodeR),this._lfoL.connect(this._delayNodeL.delayTime),this._lfoR.connect(this._delayNodeR.delayTime),this.depth=this._depth,this.type=e.type,this.spread=e.spread}static getDefaults(){return Object.assign(yN.getDefaults(),{frequency:1.5,delayTime:3.5,depth:.7,type:"sine",spread:180,feedback:0,wet:.5})}get depth(){return this._depth}set depth(e){this._depth=e;const n=this._delayTime*e;this._lfoL.min=Math.max(this._delayTime-n,0),this._lfoL.max=this._delayTime+n,this._lfoR.min=Math.max(this._delayTime-n,0),this._lfoR.max=this._delayTime+n}get delayTime(){return this._delayTime*1e3}set delayTime(e){this._delayTime=e/1e3,this.depth=this._depth}get type(){return this._lfoL.type}set type(e){this._lfoL.type=e,this._lfoR.type=e}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(e){this._lfoL.phase=90-e/2,this._lfoR.phase=e/2+90}start(e){return this._lfoL.start(e),this._lfoR.start(e),this}stop(e){return this._lfoL.stop(e),this._lfoR.stop(e),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._delayNodeL.dispose(),this._delayNodeR.dispose(),this.frequency.dispose(),this}}class Lp extends Dl{constructor(){const e=ct(Lp.getDefaults(),arguments,["distortion"]);super(e),this.name="Distortion",this._shaper=new mh({context:this.context,length:4096}),this._distortion=e.distortion,this.connectEffect(this._shaper),this.distortion=e.distortion,this.oversample=e.oversample}static getDefaults(){return Object.assign(Dl.getDefaults(),{distortion:.4,oversample:"none"})}get distortion(){return this._distortion}set distortion(e){this._distortion=e;const n=e*100,r=Math.PI/180;this._shaper.setMap(i=>Math.abs(i)<.001?0:(3+n)*i*20*r/(Math.PI+n*Math.abs(i)))}get oversample(){return this._shaper.oversample}set oversample(e){this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.dispose(),this}}class xN extends Dl{constructor(e){super(e),this.name="FeedbackEffect",this._feedbackGain=new jt({context:this.context,gain:e.feedback,units:"normalRange"}),this.feedback=this._feedbackGain.gain,Zt(this,"feedback"),this.effectReturn.chain(this._feedbackGain,this.effectSend)}static getDefaults(){return Object.assign(Dl.getDefaults(),{feedback:.125})}dispose(){return super.dispose(),this._feedbackGain.dispose(),this.feedback.dispose(),this}}class by extends xN{constructor(){const e=ct(by.getDefaults(),arguments,["delayTime","feedback"]);super(e),this.name="FeedbackDelay",this._delayNode=new Kf({context:this.context,delayTime:e.delayTime,maxDelay:e.maxDelay}),this.delayTime=this._delayNode.delayTime,this.connectEffect(this._delayNode),Zt(this,"delayTime")}static getDefaults(){return Object.assign(xN.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._delayNode.dispose(),this.delayTime.dispose(),this}}class FT extends nv{constructor(){const e=ct(FT.getDefaults(),arguments,["frequency","octaves","baseFrequency"]);super(e),this.name="Phaser",this._lfoL=new Qu({context:this.context,frequency:e.frequency,min:0,max:1}),this._lfoR=new Qu({context:this.context,frequency:e.frequency,min:0,max:1,phase:180}),this._baseFrequency=this.toFrequency(e.baseFrequency),this._octaves=e.octaves,this.Q=new yn({context:this.context,value:e.Q,units:"positive"}),this._filtersL=this._makeFilters(e.stages,this._lfoL),this._filtersR=this._makeFilters(e.stages,this._lfoR),this.frequency=this._lfoL.frequency,this.frequency.value=e.frequency,this.connectEffectLeft(...this._filtersL),this.connectEffectRight(...this._filtersR),this._lfoL.frequency.connect(this._lfoR.frequency),this.baseFrequency=e.baseFrequency,this.octaves=e.octaves,this._lfoL.start(),this._lfoR.start(),Zt(this,["frequency","Q"])}static getDefaults(){return Object.assign(nv.getDefaults(),{frequency:.5,octaves:3,stages:10,Q:10,baseFrequency:350})}_makeFilters(e,n){const r=[];for(let i=0;ie.disconnect()),this._filtersR.forEach(e=>e.disconnect()),this.frequency.dispose(),this}}class BT extends Dl{constructor(){const e=ct(BT.getDefaults(),arguments,["decay"]);super(e),this.name="Reverb",this._convolver=this.context.createConvolver(),this.ready=Promise.resolve(),this._decay=e.decay,this._preDelay=e.preDelay,this.generate(),this.connectEffect(this._convolver)}static getDefaults(){return Object.assign(Dl.getDefaults(),{decay:1.5,preDelay:.01})}get decay(){return this._decay}set decay(e){e=this.toSeconds(e),Aa(e,.001),this._decay=e,this.generate()}get preDelay(){return this._preDelay}set preDelay(e){e=this.toSeconds(e),Aa(e,0),this._preDelay=e,this.generate()}generate(){return _r(this,void 0,void 0,function*(){const e=this.ready,n=new hy(2,this._decay+this._preDelay,this.context.sampleRate),r=new Yf({context:n}),i=new Yf({context:n}),s=new wm({context:n});r.connect(s,0,0),i.connect(s,0,1);const o=new jt({context:n}).toDestination();s.connect(o),r.start(0),i.start(0),o.gain.setValueAtTime(0,0),o.gain.setValueAtTime(1,this._preDelay),o.gain.exponentialApproachValueAtTime(0,this._preDelay,this.decay);const a=n.render();return this.ready=a.then(En),yield e,this._convolver.buffer=(yield a).get(),this})}dispose(){return super.dispose(),this._convolver.disconnect(),this}}class zT extends Dl{constructor(){const e=ct(zT.getDefaults(),arguments,["frequency","depth"]);super(e),this.name="Vibrato",this._delayNode=new Kf({context:this.context,delayTime:0,maxDelay:e.maxDelay}),this._lfo=new Qu({context:this.context,type:e.type,min:0,max:e.maxDelay,frequency:e.frequency,phase:-90}).start().connect(this._delayNode.delayTime),this.frequency=this._lfo.frequency,this.depth=this._lfo.amplitude,this.depth.value=e.depth,Zt(this,["frequency","depth"]),this.effectSend.chain(this._delayNode,this.effectReturn)}static getDefaults(){return Object.assign(Dl.getDefaults(),{maxDelay:.005,frequency:5,depth:.1,type:"sine"})}get type(){return this._lfo.type}set type(e){this._lfo.type=e}dispose(){return super.dispose(),this._delayNode.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class Ar extends ft{constructor(){const e=ct(Ar.getDefaults(),arguments,["solo"]);super(e),this.name="Solo",this.input=this.output=new jt({context:this.context}),Ar._allSolos.has(this.context)||Ar._allSolos.set(this.context,new Set),Ar._allSolos.get(this.context).add(this),this.solo=e.solo}static getDefaults(){return Object.assign(ft.getDefaults(),{solo:!1})}get solo(){return this._isSoloed()}set solo(e){e?this._addSolo():this._removeSolo(),Ar._allSolos.get(this.context).forEach(n=>n._updateSolo())}get muted(){return this.input.gain.value===0}_addSolo(){Ar._soloed.has(this.context)||Ar._soloed.set(this.context,new Set),Ar._soloed.get(this.context).add(this)}_removeSolo(){Ar._soloed.has(this.context)&&Ar._soloed.get(this.context).delete(this)}_isSoloed(){return Ar._soloed.has(this.context)&&Ar._soloed.get(this.context).has(this)}_noSolos(){return!Ar._soloed.has(this.context)||Ar._soloed.has(this.context)&&Ar._soloed.get(this.context).size===0}_updateSolo(){this._isSoloed()?this.input.gain.value=1:this._noSolos()?this.input.gain.value=1:this.input.gain.value=0}dispose(){return super.dispose(),Ar._allSolos.get(this.context).delete(this),this._removeSolo(),this}}Ar._allSolos=new Map;Ar._soloed=new Map;class VT extends ft{constructor(){const e=ct(VT.getDefaults(),arguments,["pan","volume"]);super(e),this.name="PanVol",this._panner=this.input=new DT({context:this.context,pan:e.pan,channelCount:e.channelCount}),this.pan=this._panner.pan,this._volume=this.output=new Ll({context:this.context,volume:e.volume}),this.volume=this._volume.volume,this._panner.connect(this._volume),this.mute=e.mute,Zt(this,["pan","volume"])}static getDefaults(){return Object.assign(ft.getDefaults(),{mute:!1,pan:0,volume:0,channelCount:1})}get mute(){return this._volume.mute}set mute(e){this._volume.mute=e}dispose(){return super.dispose(),this._panner.dispose(),this.pan.dispose(),this._volume.dispose(),this.volume.dispose(),this}}class vf extends ft{constructor(){const e=ct(vf.getDefaults(),arguments,["volume","pan"]);super(e),this.name="Channel",this._solo=this.input=new Ar({solo:e.solo,context:this.context}),this._panVol=this.output=new VT({context:this.context,pan:e.pan,volume:e.volume,mute:e.mute,channelCount:e.channelCount}),this.pan=this._panVol.pan,this.volume=this._panVol.volume,this._solo.connect(this._panVol),Zt(this,["pan","volume"])}static getDefaults(){return Object.assign(ft.getDefaults(),{pan:0,volume:0,mute:!1,solo:!1,channelCount:1})}get solo(){return this._solo.solo}set solo(e){this._solo.solo=e}get muted(){return this._solo.muted||this.mute}get mute(){return this._panVol.mute}set mute(e){this._panVol.mute=e}_getBus(e){return vf.buses.has(e)||vf.buses.set(e,new jt({context:this.context})),vf.buses.get(e)}send(e,n=0){const r=this._getBus(e),i=new jt({context:this.context,units:"decibels",gain:n});return this.connect(i),i.connect(r),i}receive(e){return this._getBus(e).connect(this),this}dispose(){return super.dispose(),this._panVol.dispose(),this.pan.dispose(),this.volume.dispose(),this._solo.dispose(),this}}vf.buses=new Map;class HT extends ft{constructor(){const e=ct(HT.getDefaults(),arguments,["lowFrequency","highFrequency"]);super(e),this.name="MultibandSplit",this.input=new jt({context:this.context}),this.output=void 0,this.low=new Zs({context:this.context,frequency:0,type:"lowpass"}),this._lowMidFilter=new Zs({context:this.context,frequency:0,type:"highpass"}),this.mid=new Zs({context:this.context,frequency:0,type:"lowpass"}),this.high=new Zs({context:this.context,frequency:0,type:"highpass"}),this._internalChannels=[this.low,this.mid,this.high],this.lowFrequency=new yn({context:this.context,units:"frequency",value:e.lowFrequency}),this.highFrequency=new yn({context:this.context,units:"frequency",value:e.highFrequency}),this.Q=new yn({context:this.context,units:"positive",value:e.Q}),this.input.fan(this.low,this.high),this.input.chain(this._lowMidFilter,this.mid),this.lowFrequency.fan(this.low.frequency,this._lowMidFilter.frequency),this.highFrequency.fan(this.mid.frequency,this.high.frequency),this.Q.connect(this.low.Q),this.Q.connect(this._lowMidFilter.Q),this.Q.connect(this.mid.Q),this.Q.connect(this.high.Q),Zt(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(ft.getDefaults(),{Q:1,highFrequency:2500,lowFrequency:400})}dispose(){return super.dispose(),_m(this,["high","mid","low","highFrequency","lowFrequency"]),this.low.dispose(),this._lowMidFilter.dispose(),this.mid.dispose(),this.high.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this.Q.dispose(),this}}class GT extends ft{constructor(){const e=ct(GT.getDefaults(),arguments,["threshold","ratio"]);super(e),this.name="Compressor",this._compressor=this.context.createDynamicsCompressor(),this.input=this._compressor,this.output=this._compressor,this.threshold=new Xt({minValue:this._compressor.threshold.minValue,maxValue:this._compressor.threshold.maxValue,context:this.context,convert:!1,param:this._compressor.threshold,units:"decibels",value:e.threshold}),this.attack=new Xt({minValue:this._compressor.attack.minValue,maxValue:this._compressor.attack.maxValue,context:this.context,param:this._compressor.attack,units:"time",value:e.attack}),this.release=new Xt({minValue:this._compressor.release.minValue,maxValue:this._compressor.release.maxValue,context:this.context,param:this._compressor.release,units:"time",value:e.release}),this.knee=new Xt({minValue:this._compressor.knee.minValue,maxValue:this._compressor.knee.maxValue,context:this.context,convert:!1,param:this._compressor.knee,units:"decibels",value:e.knee}),this.ratio=new Xt({minValue:this._compressor.ratio.minValue,maxValue:this._compressor.ratio.maxValue,context:this.context,convert:!1,param:this._compressor.ratio,units:"positive",value:e.ratio}),Zt(this,["knee","release","attack","ratio","threshold"])}static getDefaults(){return Object.assign(ft.getDefaults(),{attack:.003,knee:30,ratio:12,release:.25,threshold:-24})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.disconnect(),this.attack.dispose(),this.release.dispose(),this.threshold.dispose(),this.ratio.dispose(),this.knee.dispose(),this}}class WT extends ft{constructor(){const e=ct(WT.getDefaults(),arguments,["low","mid","high"]);super(e),this.name="EQ3",this.output=new jt({context:this.context}),this._internalChannels=[],this.input=this._multibandSplit=new HT({context:this.context,highFrequency:e.highFrequency,lowFrequency:e.lowFrequency}),this._lowGain=new jt({context:this.context,gain:e.low,units:"decibels"}),this._midGain=new jt({context:this.context,gain:e.mid,units:"decibels"}),this._highGain=new jt({context:this.context,gain:e.high,units:"decibels"}),this.low=this._lowGain.gain,this.mid=this._midGain.gain,this.high=this._highGain.gain,this.Q=this._multibandSplit.Q,this.lowFrequency=this._multibandSplit.lowFrequency,this.highFrequency=this._multibandSplit.highFrequency,this._multibandSplit.low.chain(this._lowGain,this.output),this._multibandSplit.mid.chain(this._midGain,this.output),this._multibandSplit.high.chain(this._highGain,this.output),Zt(this,["low","mid","high","lowFrequency","highFrequency"]),this._internalChannels=[this._multibandSplit]}static getDefaults(){return Object.assign(ft.getDefaults(),{high:0,highFrequency:2500,low:0,lowFrequency:400,mid:0})}dispose(){return super.dispose(),_m(this,["low","mid","high","lowFrequency","highFrequency"]),this._multibandSplit.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this._lowGain.dispose(),this._midGain.dispose(),this._highGain.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.Q.dispose(),this}}Vi().transport;function jT(){return Vi().transport}Vi().destination;Vi().destination;function hne(){return Vi().destination}Vi().listener;Vi().draw;Vi();const sw=Ir("256n").toSeconds(),fne=Ir("8n").toSeconds();function dne(){const t=new BT;t.set({wet:0});const e=new by;e.set({wet:0,delayTime:sw,maxDelay:"1n",feedback:.666});const n=new UT;n.set({wet:0,depth:.999,frequency:7,feedback:.666});const r=new FT;r.set({wet:0,Q:10});const i=new Lp;i.set({wet:0,distortion:.9});const s=new zT;return s.set({wet:0,depth:.2}),{reverb:t,echo:e,chorus:n,phaser:r,distortion:i,vibrato:s}}const pne={a:1,b:2,c:3,d:4,e:5,f:6,g:7,x:8,"#":9,"!":10,y:13,t:14,s:15,i:16,q:17,h:18,w:19,3:20,".":21,"+":11,"-":12,0:22,1:23,2:24,p:25,4:26,5:27,6:29,7:28,8:30,9:31};let mne=0;function gne(t,e,n){let r=e,i=3,s="32n",o="",a="";const c=[];function l(){a="",o="",r+=Ir(s).toSeconds()}function u(){a===null?(c.push([r,[t,s,a]]),l()):mt(a)?(c.push([r,[t,s,a]]),l()):a!==""&&(c.push([r,[t,s,`${a}${o}${i}`]]),l())}for(let h=0;h{if(!f_){const t=jT();t.bpm.value=107,t.start(),ro("synth","audio is enabled!"),f_=!0}}).catch(()=>{})}function vne(){const t=hne(),e=new Ll(8);e.connect(t);const n=new GT({threshold:-24,ratio:4,attack:.003,release:.25,knee:30});n.connect(e);const r=new jt;r.connect(n);const i=new Ll(2);i.connect(n);const s=[sc(r),sc(r),sc(r),sc(r),sc(r),sc(r),sc(r),sc(r),sc(r)],o=new ev().connect(i);o.maxPolyphony=8,o.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"square"}});function a(De){o.triggerAttackRelease("C6","1i",De)}const c=new Li().connect(i);o.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"square"}});function l(De){const A=Ir("64n").toSeconds();c.triggerAttackRelease("C6","8n",De),c.frequency.exponentialRampToValueAtTime("C11",A+De)}const u=new Zs(350,"bandpass").connect(i),h=new jt().connect(u);h.gain.value=0;const p=new ev().connect(h);p.maxPolyphony=8,p.set({envelope:{attack:.001,decay:.01,sustain:.1,release:.1},oscillator:{type:"square"}});function m(De,A){const ie=Ir("64n").toSeconds()+Ir(De).toSeconds();h.gain.setValueAtTime(.5,A),h.gain.exponentialRampToValueAtTime(.01,ie+A),p.triggerAttackRelease([800,540],De,A)}const g=new WT(-10,10,-1).connect(i),v=new Zs(800,"highpass",-12);v.connect(g);const y=new gf;y.set({envelope:{attack:.01,decay:.1,sustain:.1,release:.1}}),y.connect(v);function _(De,A){y.triggerAttackRelease(De,A)}const S=new Lp().connect(i);S.set({distortion:.666});const E=new Li;E.set({envelope:{attack:0,decay:.1,sustain:0,release:1},oscillator:{type:"triangle"}}),E.connect(S);const b=new Zs;b.set({type:"highpass",frequency:1e4}),b.connect(S);const N=new gf;N.set({envelope:{attack:.01,decay:.1,sustain:0,release:.1}}),N.connect(b);function R(De,A){const ie=Ir("512n").toSeconds(),te=Ir("32n").toSeconds();E.triggerAttackRelease(1e4,De,A,1),E.frequency.exponentialRampToValueAtTime(300,A+ie),E.frequency.exponentialRampToValueAtTime(100,A+te),N.triggerAttackRelease("8n",A,.333),N.volume.setValueAtTime(1,A),N.volume.exponentialRampToValueAtTime(0,A+Ir("32n").toSeconds())}const M=new Zs;M.set({type:"bandpass",frequency:256,Q:.17}),M.connect(i);const O=new Li;O.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"sawtooth"}}),O.connect(M);const C=new Li;C.set({envelope:{attack:.001,decay:.1,sustain:.001,release:.1},oscillator:{type:"sine"}}),C.connect(M);function I(De,A){O.triggerAttackRelease(2e3,De,A),O.frequency.exponentialRampToValueAtTime(1e3,A+Ir("32n").toSeconds()),C.triggerAttackRelease(999,De,A),C.frequency.exponentialRampToValueAtTime(888,A+Ir("256n").toSeconds())}const U=new Lp().connect(i);U.set({distortion:.876});const L=new Li;L.set({envelope:{attack:0,decay:.1,sustain:0,release:1},oscillator:{type:"triangle"}}),L.connect(U);const P=new Zs;P.set({type:"highpass",frequency:1e4}),P.connect(U);const T=new gf;T.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1}}),T.connect(P);function H(De,A){const ie=Ir("512n").toSeconds(),te=Ir("32n").toSeconds();L.triggerAttackRelease(1e4,De,A,1),L.frequency.exponentialRampToValueAtTime(150,A+ie),L.frequency.exponentialRampToValueAtTime(100,A+te),T.triggerAttackRelease("8n",A,.25),T.volume.setValueAtTime(1,A),T.volume.exponentialRampToValueAtTime(0,A+Ir("32n").toSeconds())}const V=new Li().connect(i);V.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1},oscillator:{type:"sawtooth"}});const B=new Li().connect(i);V.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1},oscillator:{type:"triangle"}});const z=new gf().connect(i);z.set({envelope:{attack:.01,decay:.1,sustain:.001,release:.1}});function W(De,A){const ie=Ir("256n").toSeconds(),te=Ir(De).toSeconds()-ie;V.triggerAttackRelease("C4",te,A,1),V.frequency.exponentialRampToValueAtTime(gN("C0").toFrequency(),A+te),B.triggerAttackRelease("C5",te,A,.5),B.frequency.exponentialRampToValueAtTime(gN("C0").toFrequency(),A+te);const X=Ir("4n").toSeconds();z.triggerAttackRelease("8n",A),z.volume.setValueAtTime(1,A),z.volume.exponentialRampToValueAtTime(0,A+X)}const K=new Zs;K.set({type:"bandpass",frequency:256,Q:.17}),K.connect(i);const j=new Li;j.set({envelope:{attack:.001,decay:.001,sustain:.001,release:.1},oscillator:{type:"sawtooth"}}),j.connect(K);const Y=new Li;Y.set({envelope:{attack:.001,decay:.1,sustain:.001,release:.1},oscillator:{type:"sine"}}),Y.connect(K);function ge(De,A){j.triggerAttackRelease(2e3,De,A),j.frequency.exponentialRampToValueAtTime(100,A+Ir("32n").toSeconds()),Y.triggerAttackRelease(699,De,A),Y.frequency.exponentialRampToValueAtTime(399,A+Ir("256n").toSeconds())}const Q=new Em().connect(i);Q.set({octaves:8});function re(De){Q.triggerAttackRelease("C1","8n",De)}const we=new tv(Ae);function Ae(De,A){if(A===null)return;const[ie,te,X]=A;if(Kt(X)&&Z(s[ie])&&s[ie].source.triggerAttackRelease(X,te,De),mt(X))switch(X){case 0:a(De);break;case 1:l(De);break;case 2:m(te,De);break;case 3:_(te,De);break;case 4:R(te,De);break;case 5:I(te,De);break;case 6:H(te,De);break;case 7:W(te,De);break;case 8:ge(te,De);break;case 9:re(De);break;case-1:--He,He===0&&(Le=-1);break}}function Ee(De,A,ie){let te=A;const X=gne(De,A,ie),$=X[X.length-1];Z($)&&(te=Math.max(te,$[0]));for(let ne=0;ne{if(f_&&!Z(mu)&&(mu=vne()),!!Z(mu))switch(t.target){case"tts":Au("tts",async()=>{if(cn(t.data)){const[e,n]=t.data;await Ene(e||"en-US-GuyNeural",n)}});break;case"play":if(cn(t.data)){const[e,n]=t.data;n===""?mu.stopplay():mu.addplay(e,n)}break;case"voice":if(cn(t.data)){const[e,n,r]=t.data,i=mu.SOURCE[e];if(!Z(i)){Vn(oc.name(),t.target,`unknown voice ${e}`);return}switch(n){case"bpm":if(mt(r)){jT().bpm.value=r;return}break;case"vol":case"volume":if(mt(r)){i.source.volume.value=r;return}break;case"port":case"portamento":if(mt(r)){i.source.portamento=r;return}break;case"env":case"envelope":if(cn(r)){const[s,o,a,c]=r;i.source.set({envelope:{attack:s,decay:o,sustain:a,release:c}});return}break;default:if(Kt(n)){if(yne(n,r)){i.source.set({oscillator:{type:n}}),cn(r)&&i.source.set({oscillator:{partials:r}}),mt(r)&&i.source.set({oscillator:{partials:[r]}});return}const s=i.source.get().oscillator.type;switch(s){case"pwm":switch(n){case"modfreq":case"modulationfrequency":if(mt(r)){i.source.set({oscillator:{modulationFrequency:r}});return}break}break;case"pulse":switch(n){case"width":if(mt(r)){i.source.set({oscillator:{width:r}});return}break}break;case"custom":case"sine":case"square":case"triangle":case"sawtooth":switch(n){case"phase":if(mt(r)){i.source.set({oscillator:{phase:r}});return}break}break;case"amcustom":case"amsine":case"amsquare":case"amtriangle":case"amsawtooth":switch(n){case"harmonicity":if(mt(r)){i.source.set({oscillator:{harmonicity:r}});return}break;case"modtype":case"modulationtype":if(Kt(r)){i.source.set({oscillator:{modulationType:r}});return}break;case"modenv":case"modulationenvelope":if(cn(r)){const[o,a,c,l]=r;i.source.set({oscillator:{modulationEnvelope:{attack:o,decay:a,sustain:c,release:l}}});return}break}break;case"fmcustom":case"fmsine":case"fmsquare":case"fmtriangle":case"fmsawtooth":switch(n){case"harmonicity":if(mt(r)){i.source.set({oscillator:{harmonicity:r}});return}break;case"modindex":if(mt(r)){i.source.set({oscillator:{modulationIndex:r}});return}break;case"modtype":if(Kt(r)){i.source.set({oscillator:{modulationType:r}});return}break;case"modenv":if(cn(r)){const[o,a,c,l]=r;i.source.set({oscillator:{modulationEnvelope:{attack:o,decay:a,sustain:c,release:l}}});return}break}break;case"fatcustom":case"fatsine":case"fatsquare":case"fattriangle":case"fatsawtooth":switch(n){case"count":if(mt(r)){i.source.set({oscillator:{count:r}});return}break;case"phase":if(mt(r)){i.source.set({oscillator:{phase:r}});return}break;case"spread":if(mt(r)){i.source.set({oscillator:{spread:r}});return}break}break}Vn(oc.name(),t.target,`unknown ${s} config ${n}`)}break}}break;case"voicefx":if(cn(t.data)){const[e,n,r,i]=t.data,s=mu.SOURCE[e],o=s==null?void 0:s.fx[n];if(Z(o)){switch(r){case"on":o.wet.value=.2;break;case"off":o.wet.value=0;break;default:if(mt(r))o.wet.value=Cn(.01*r,0,1);else switch(n){case"vibrato":{switch(r){default:Vn(oc.name(),t.target,`unknown ${n} config ${r}`);break}break}case"chorus":{switch(r){default:Vn(oc.name(),t.target,`unknown ${n} config ${r}`);break}break}case"phaser":{const a=o;switch(r){case"q":mt(i)&&(a.Q.value=i);break;case"octaves":mt(i)&&(a.octaves=i);break;case"basefrequency":mt(i)&&(a.baseFrequency=i);break;default:Vn(oc.name(),t.target,`unknown ${n} config ${r}`);break}break}case"distortion":{const a=o;switch(r){case"distortion":mt(i)&&(a.distortion=i);break;case"oversample":switch(i){case"2x":case"4x":case"none":a.oversample=i;break}break;default:Vn(oc.name(),t.target,`unknown ${n} config ${r}`);break}break}case"echo":{const a=o;switch(r){case"delaytime":a.delayTime.value=i;break;default:Vn(oc.name(),t.target,`unknown ${n} config ${r}`);break}break}case"reverb":{const a=o;switch(r){case"decay":a.decay=i;break;case"predelay":a.preDelay=i;break;default:Vn(oc.name(),t.target,`unknown ${n} config ${r}`);break}break}}break}o instanceof by&&(o.wet.value===0?o.set({delayTime:sw}):o.get().delayTime===sw&&o.set({delayTime:fne}));return}Vn(oc.name(),t.target,`unknown fx ${n}`)}break}}),SN=t=>{let e;const n=new Set,r=(l,u)=>{const h=typeof l=="function"?l(e):l;if(!Object.is(h,e)){const p=e;e=u??(typeof h!="object"||h===null)?h:Object.assign({},e,h),n.forEach(m=>m(e,p))}},i=()=>e,a={setState:r,getState:i,getInitialState:()=>c,subscribe:l=>(n.add(l),()=>n.delete(l))},c=e=t(r,i,a);return a},$T=t=>t?SN(t):SN,wne=t=>t;function qT(t,e=wne){const n=Co.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return Co.useDebugValue(n),n}const EN=t=>{const e=$T(t),n=r=>qT(e,r);return Object.assign(n,e),n},bm=t=>t?EN(t):EN;function bne(t){const e=Ne.useRef();return n=>{const r=t(n);return(e.current===void 0||r===void 0?e.current===r:oL(e.current,r))?e.current:e.current=r}}const os=bm(()=>({desync:!1,gadget:{player:"",layers:[],panels:[],reset:!1,focus:""}}));function XT(){return os(t=>t.gadget.player)}function rv(){return os.getState().gadget.player}var d_=(t=>(t[t.OFF=0]="OFF",t[t.INFO=1]="INFO",t[t.DEBUG=2]="DEBUG",t))(d_||{});const wN=128;var Pi=(t=>(t[t.TOP=0]="TOP",t[t.BOTTOM=1]="BOTTOM",t[t.FULL=2]="FULL",t[t.SPLIT_Y=3]="SPLIT_Y",t[t.SPLIT_Y_ALT=4]="SPLIT_Y_ALT",t[t.MAX=5]="MAX",t))(Pi||{});const ts=bm(()=>({layout:1,terminal:{open:!1,level:1,logs:[]},editor:{open:!1,player:"",book:"",page:"",type:"",title:""}})),br=bm(()=>({scroll:0,xcursor:0,ycursor:0,xselect:void 0,yselect:void 0,bufferindex:0,buffer:[""]})),hr=bm(()=>({id:"",xscroll:0,yscroll:0,cursor:0,select:void 0}));/** - * postprocessing v6.36.4 build Tue Nov 05 2024 - * https://github.com/pmndrs/postprocessing - * Copyright 2015-2024 Raoul van Rüschen - * @license Zlib - */var tS=1/1e3,Tne=1e3,Ane=class{constructor(){this.startTime=performance.now(),this.previousTime=0,this.currentTime=0,this._delta=0,this._elapsed=0,this._fixedDelta=1e3/60,this.timescale=1,this.useFixedDelta=!1,this._autoReset=!1}get autoReset(){return this._autoReset}set autoReset(t){typeof document<"u"&&document.hidden!==void 0&&(t?document.addEventListener("visibilitychange",this):document.removeEventListener("visibilitychange",this),this._autoReset=t)}get delta(){return this._delta*tS}get fixedDelta(){return this._fixedDelta*tS}set fixedDelta(t){this._fixedDelta=t*Tne}get elapsed(){return this._elapsed*tS}update(t){this.useFixedDelta?this._delta=this.fixedDelta:(this.previousTime=this.currentTime,this.currentTime=(t!==void 0?t:performance.now())-this.startTime,this._delta=this.currentTime-this.previousTime),this._delta*=this.timescale,this._elapsed+=this._delta}reset(){this._delta=0,this._elapsed=0,this.currentTime=performance.now()-this.startTime}getDelta(){return this.delta}getElapsed(){return this.elapsed}handleEvent(t){document.hidden||(this.currentTime=performance.now()-this.startTime)}dispose(){this.autoReset=!1}},Mne=(()=>{const t=new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),e=new Float32Array([0,0,2,0,0,2]),n=new Bo;return n.setAttribute("position",new Jn(t,3)),n.setAttribute("uv",new Jn(e,2)),n})(),Wo=class ow{static get fullscreenGeometry(){return Mne}constructor(e="Pass",n=new L_,r=new Dv){this.name=e,this.renderer=null,this.scene=n,this.camera=r,this.screen=null,this.rtt=!0,this.needsSwap=!0,this.needsDepthTexture=!1,this.enabled=!0}get renderToScreen(){return!this.rtt}set renderToScreen(e){if(this.rtt===e){const n=this.fullscreenMaterial;n!==null&&(n.needsUpdate=!0),this.rtt=!e}}set mainScene(e){}set mainCamera(e){}setRenderer(e){this.renderer=e}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}get fullscreenMaterial(){return this.screen!==null?this.screen.material:null}set fullscreenMaterial(e){let n=this.screen;n!==null?n.material=e:(n=new Ao(ow.fullscreenGeometry,e),n.frustumCulled=!1,this.scene===null&&(this.scene=new L_),this.scene.add(n),this.screen=n)}getFullscreenMaterial(){return this.fullscreenMaterial}setFullscreenMaterial(e){this.fullscreenMaterial=e}getDepthTexture(){return null}setDepthTexture(e,n=ah){}render(e,n,r,i,s){throw new Error("Render method not implemented!")}setSize(e,n){}initialize(e,n,r){}dispose(){for(const e of Object.keys(this)){const n=this[e];(n instanceof Us||n instanceof Vc||n instanceof or||n instanceof ow)&&this[e].dispose()}this.fullscreenMaterial!==null&&this.fullscreenMaterial.dispose()}},Cne=class extends Wo{constructor(){super("ClearMaskPass",null,null),this.needsSwap=!1}render(t,e,n,r,i){const s=t.state.buffers.stencil;s.setLocked(!1),s.setTest(!1)}},Rne=`#include -#include -#ifdef FRAMEBUFFER_PRECISION_HIGH -uniform mediump sampler2D inputBuffer; -#else -uniform lowp sampler2D inputBuffer; -#endif -uniform float opacity;varying vec2 vUv;void main(){vec4 texel=texture2D(inputBuffer,vUv);gl_FragColor=opacity*texel; -#include -#include -}`,Nne="varying vec2 vUv;void main(){vUv=position.xy*0.5+0.5;gl_Position=vec4(position.xy,1.0,1.0);}",kne=class extends Gi{constructor(){super({name:"CopyMaterial",uniforms:{inputBuffer:new Mn(null),opacity:new Mn(1)},blending:Ro,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:Rne,vertexShader:Nne})}set inputBuffer(t){this.uniforms.inputBuffer.value=t}setInputBuffer(t){this.uniforms.inputBuffer.value=t}getOpacity(t){return this.uniforms.opacity.value}setOpacity(t){this.uniforms.opacity.value=t}},Ine=class extends Wo{constructor(t,e=!0){super("CopyPass"),this.fullscreenMaterial=new kne,this.needsSwap=!1,this.renderTarget=t,t===void 0&&(this.renderTarget=new Us(1,1,{minFilter:is,magFilter:is,stencilBuffer:!1,depthBuffer:!1}),this.renderTarget.texture.name="CopyPass.Target"),this.autoResize=e}get resize(){return this.autoResize}set resize(t){this.autoResize=t}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}setAutoResizeEnabled(t){this.autoResize=t}render(t,e,n,r,i){this.fullscreenMaterial.inputBuffer=e.texture,t.setRenderTarget(this.renderToScreen?null:this.renderTarget),t.render(this.scene,this.camera)}setSize(t,e){this.autoResize&&this.renderTarget.setSize(t,e)}initialize(t,e,n){n!==void 0&&(this.renderTarget.texture.type=n,n!==bi?this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1":t!==null&&t.outputColorSpace===pr&&(this.renderTarget.texture.colorSpace=pr))}},bN=new ln,SD=class extends Wo{constructor(t=!0,e=!0,n=!1){super("ClearPass",null,null),this.needsSwap=!1,this.color=t,this.depth=e,this.stencil=n,this.overrideClearColor=null,this.overrideClearAlpha=-1}setClearFlags(t,e,n){this.color=t,this.depth=e,this.stencil=n}getOverrideClearColor(){return this.overrideClearColor}setOverrideClearColor(t){this.overrideClearColor=t}getOverrideClearAlpha(){return this.overrideClearAlpha}setOverrideClearAlpha(t){this.overrideClearAlpha=t}render(t,e,n,r,i){const s=this.overrideClearColor,o=this.overrideClearAlpha,a=t.getClearAlpha(),c=s!==null,l=o>=0;c?(t.getClearColor(bN),t.setClearColor(s,l?o:a)):l&&t.setClearAlpha(o),t.setRenderTarget(this.renderToScreen?null:e),t.clear(this.color,this.depth,this.stencil),c?t.setClearColor(bN,a):l&&t.setClearAlpha(a)}},One=class extends Wo{constructor(t,e){super("MaskPass",t,e),this.needsSwap=!1,this.clearPass=new SD(!1,!1,!0),this.inverse=!1}set mainScene(t){this.scene=t}set mainCamera(t){this.camera=t}get inverted(){return this.inverse}set inverted(t){this.inverse=t}get clear(){return this.clearPass.enabled}set clear(t){this.clearPass.enabled=t}getClearPass(){return this.clearPass}isInverted(){return this.inverted}setInverted(t){this.inverted=t}render(t,e,n,r,i){const s=t.getContext(),o=t.state.buffers,a=this.scene,c=this.camera,l=this.clearPass,u=this.inverted?0:1,h=1-u;o.color.setMask(!1),o.depth.setMask(!1),o.color.setLocked(!0),o.depth.setLocked(!0),o.stencil.setTest(!0),o.stencil.setOp(s.REPLACE,s.REPLACE,s.REPLACE),o.stencil.setFunc(s.ALWAYS,u,4294967295),o.stencil.setClear(h),o.stencil.setLocked(!0),this.clearPass.enabled&&(this.renderToScreen?l.render(t,null):(l.render(t,e),l.render(t,n))),this.renderToScreen?(t.setRenderTarget(null),t.render(a,c)):(t.setRenderTarget(e),t.render(a,c),t.setRenderTarget(n),t.render(a,c)),o.color.setLocked(!1),o.depth.setLocked(!1),o.stencil.setLocked(!1),o.stencil.setFunc(s.EQUAL,1,4294967295),o.stencil.setOp(s.KEEP,s.KEEP,s.KEEP),o.stencil.setLocked(!0)}},Lne=class{constructor(e=null,{depthBuffer:n=!0,stencilBuffer:r=!1,multisampling:i=0,frameBufferType:s}={}){this.renderer=null,this.inputBuffer=this.createBuffer(n,r,s,i),this.outputBuffer=this.inputBuffer.clone(),this.copyPass=new Ine,this.depthTexture=null,this.passes=[],this.timer=new Ane,this.autoRenderToScreen=!0,this.setRenderer(e)}get multisampling(){return this.inputBuffer.samples||0}set multisampling(e){const n=this.inputBuffer,r=this.multisampling;r>0&&e>0?(this.inputBuffer.samples=e,this.outputBuffer.samples=e,this.inputBuffer.dispose(),this.outputBuffer.dispose()):r!==e&&(this.inputBuffer.dispose(),this.outputBuffer.dispose(),this.inputBuffer=this.createBuffer(n.depthBuffer,n.stencilBuffer,n.texture.type,e),this.inputBuffer.depthTexture=this.depthTexture,this.outputBuffer=this.inputBuffer.clone())}getTimer(){return this.timer}getRenderer(){return this.renderer}setRenderer(e){if(this.renderer=e,e!==null){const n=e.getSize(new St),r=e.getContext().getContextAttributes().alpha,i=this.inputBuffer.texture.type;i===bi&&e.outputColorSpace===pr&&(this.inputBuffer.texture.colorSpace=pr,this.outputBuffer.texture.colorSpace=pr,this.inputBuffer.dispose(),this.outputBuffer.dispose()),e.autoClear=!1,this.setSize(n.width,n.height);for(const s of this.passes)s.initialize(e,r,i)}}replaceRenderer(e,n=!0){const r=this.renderer,i=r.domElement.parentNode;return this.setRenderer(e),n&&i!==null&&(i.removeChild(r.domElement),i.appendChild(e.domElement)),r}createDepthTexture(){const e=this.depthTexture=new bb;return this.inputBuffer.depthTexture=e,this.inputBuffer.dispose(),this.inputBuffer.stencilBuffer?(e.format=$u,e.type=ju):e.type=Il,e}deleteDepthTexture(){if(this.depthTexture!==null){this.depthTexture.dispose(),this.depthTexture=null,this.inputBuffer.depthTexture=null,this.inputBuffer.dispose();for(const e of this.passes)e.setDepthTexture(null)}}createBuffer(e,n,r,i){const s=this.renderer,o=s===null?new St:s.getDrawingBufferSize(new St),a={minFilter:is,magFilter:is,stencilBuffer:n,depthBuffer:e,type:r},c=new Us(o.width,o.height,a);return i>0&&(c.ignoreDepthForMultisampleCopy=!1,c.samples=i),r===bi&&s!==null&&s.outputColorSpace===pr&&(c.texture.colorSpace=pr),c.texture.name="EffectComposer.Buffer",c.texture.generateMipmaps=!1,c}setMainScene(e){for(const n of this.passes)n.mainScene=e}setMainCamera(e){for(const n of this.passes)n.mainCamera=e}addPass(e,n){const r=this.passes,i=this.renderer,s=i.getDrawingBufferSize(new St),o=i.getContext().getContextAttributes().alpha,a=this.inputBuffer.texture.type;if(e.setRenderer(i),e.setSize(s.width,s.height),e.initialize(i,o,a),this.autoRenderToScreen&&(r.length>0&&(r[r.length-1].renderToScreen=!1),e.renderToScreen&&(this.autoRenderToScreen=!1)),n!==void 0?r.splice(n,0,e):r.push(e),this.autoRenderToScreen&&(r[r.length-1].renderToScreen=!0),e.needsDepthTexture||this.depthTexture!==null)if(this.depthTexture===null){const c=this.createDepthTexture();for(e of r)e.setDepthTexture(c)}else e.setDepthTexture(this.depthTexture)}removePass(e){const n=this.passes,r=n.indexOf(e);if(r!==-1&&n.splice(r,1).length>0){if(this.depthTexture!==null){const o=(c,l)=>c||l.needsDepthTexture;n.reduce(o,!1)||(e.getDepthTexture()===this.depthTexture&&e.setDepthTexture(null),this.deleteDepthTexture())}this.autoRenderToScreen&&r===n.length&&(e.renderToScreen=!1,n.length>0&&(n[n.length-1].renderToScreen=!0))}}removeAllPasses(){const e=this.passes;this.deleteDepthTexture(),e.length>0&&(this.autoRenderToScreen&&(e[e.length-1].renderToScreen=!1),this.passes=[])}render(e){const n=this.renderer,r=this.copyPass;let i=this.inputBuffer,s=this.outputBuffer,o=!1,a,c,l;e===void 0&&(this.timer.update(),e=this.timer.getDelta());for(const u of this.passes)u.enabled&&(u.render(n,i,s,e,o),u.needsSwap&&(o&&(r.renderToScreen=u.renderToScreen,a=n.getContext(),c=n.state.buffers.stencil,c.setFunc(a.NOTEQUAL,1,4294967295),r.render(n,i,s,e,o),c.setFunc(a.EQUAL,1,4294967295)),l=i,i=s,s=l),u instanceof One?o=!0:u instanceof Cne&&(o=!1))}setSize(e,n,r){const i=this.renderer,s=i.getSize(new St);(e===void 0||n===void 0)&&(e=s.width,n=s.height),(s.width!==e||s.height!==n)&&i.setSize(e,n,r);const o=i.getDrawingBufferSize(new St);this.inputBuffer.setSize(o.width,o.height),this.outputBuffer.setSize(o.width,o.height);for(const a of this.passes)a.setSize(o.width,o.height)}reset(){this.dispose(),this.autoRenderToScreen=!0}dispose(){for(const e of this.passes)e.dispose();this.passes=[],this.inputBuffer!==null&&this.inputBuffer.dispose(),this.outputBuffer!==null&&this.outputBuffer.dispose(),this.deleteDepthTexture(),this.copyPass.dispose(),this.timer.dispose(),Wo.fullscreenGeometry.dispose()}},Ea={NONE:0,DEPTH:1,CONVOLUTION:2},_n={FRAGMENT_HEAD:"FRAGMENT_HEAD",FRAGMENT_MAIN_UV:"FRAGMENT_MAIN_UV",FRAGMENT_MAIN_IMAGE:"FRAGMENT_MAIN_IMAGE",VERTEX_HEAD:"VERTEX_HEAD",VERTEX_MAIN_SUPPORT:"VERTEX_MAIN_SUPPORT"},Pne=class{constructor(){this.shaderParts=new Map([[_n.FRAGMENT_HEAD,null],[_n.FRAGMENT_MAIN_UV,null],[_n.FRAGMENT_MAIN_IMAGE,null],[_n.VERTEX_HEAD,null],[_n.VERTEX_MAIN_SUPPORT,null]]),this.defines=new Map,this.uniforms=new Map,this.blendModes=new Map,this.extensions=new Set,this.attributes=Ea.NONE,this.varyings=new Set,this.uvTransformation=!1,this.readDepth=!1,this.colorSpace=jl}},nS=!1,TN=class{constructor(t=null){this.originalMaterials=new Map,this.material=null,this.materials=null,this.materialsBackSide=null,this.materialsDoubleSide=null,this.materialsFlatShaded=null,this.materialsFlatShadedBackSide=null,this.materialsFlatShadedDoubleSide=null,this.setMaterial(t),this.meshCount=0,this.replaceMaterial=e=>{if(e.isMesh){let n;if(e.material.flatShading)switch(e.material.side){case Ns:n=this.materialsFlatShadedDoubleSide;break;case ri:n=this.materialsFlatShadedBackSide;break;default:n=this.materialsFlatShaded;break}else switch(e.material.side){case Ns:n=this.materialsDoubleSide;break;case ri:n=this.materialsBackSide;break;default:n=this.materials;break}this.originalMaterials.set(e,e.material),e.isSkinnedMesh?e.material=n[2]:e.isInstancedMesh?e.material=n[1]:e.material=n[0],++this.meshCount}}}cloneMaterial(t){if(!(t instanceof Gi))return t.clone();const e=t.uniforms,n=new Map;for(const i in e){const s=e[i].value;s.isRenderTargetTexture&&(e[i].value=null,n.set(i,s))}const r=t.clone();for(const i of n)e[i[0]].value=i[1],r.uniforms[i[0]].value=i[1];return r}setMaterial(t){if(this.disposeMaterials(),this.material=t,t!==null){const e=this.materials=[this.cloneMaterial(t),this.cloneMaterial(t),this.cloneMaterial(t)];for(const n of e)n.uniforms=Object.assign({},t.uniforms),n.side=Nc;e[2].skinning=!0,this.materialsBackSide=e.map(n=>{const r=this.cloneMaterial(n);return r.uniforms=Object.assign({},t.uniforms),r.side=ri,r}),this.materialsDoubleSide=e.map(n=>{const r=this.cloneMaterial(n);return r.uniforms=Object.assign({},t.uniforms),r.side=Ns,r}),this.materialsFlatShaded=e.map(n=>{const r=this.cloneMaterial(n);return r.uniforms=Object.assign({},t.uniforms),r.flatShading=!0,r}),this.materialsFlatShadedBackSide=e.map(n=>{const r=this.cloneMaterial(n);return r.uniforms=Object.assign({},t.uniforms),r.flatShading=!0,r.side=ri,r}),this.materialsFlatShadedDoubleSide=e.map(n=>{const r=this.cloneMaterial(n);return r.uniforms=Object.assign({},t.uniforms),r.flatShading=!0,r.side=Ns,r})}}render(t,e,n){const r=t.shadowMap.enabled;if(t.shadowMap.enabled=!1,nS){const i=this.originalMaterials;this.meshCount=0,e.traverse(this.replaceMaterial),t.render(e,n);for(const s of i)s[0].material=s[1];this.meshCount!==i.size&&i.clear()}else{const i=e.overrideMaterial;e.overrideMaterial=this.material,t.render(e,n),e.overrideMaterial=i}t.shadowMap.enabled=r}disposeMaterials(){if(this.material!==null){const t=this.materials.concat(this.materialsBackSide).concat(this.materialsDoubleSide).concat(this.materialsFlatShaded).concat(this.materialsFlatShadedBackSide).concat(this.materialsFlatShadedDoubleSide);for(const e of t)e.dispose()}}dispose(){this.originalMaterials.clear(),this.disposeMaterials()}static get workaroundEnabled(){return nS}static set workaroundEnabled(t){nS=t}},vl=-1,Cf=class extends zc{constructor(t,e=vl,n=vl,r=1){super(),this.resizable=t,this.baseSize=new St(1,1),this.preferredSize=new St(e,n),this.target=this.preferredSize,this.s=r,this.effectiveSize=new St,this.addEventListener("change",()=>this.updateEffectiveSize()),this.updateEffectiveSize()}updateEffectiveSize(){const t=this.baseSize,e=this.preferredSize,n=this.effectiveSize,r=this.scale;e.width!==vl?n.width=e.width:e.height!==vl?n.width=Math.round(e.height*(t.width/Math.max(t.height,1))):n.width=Math.round(t.width*r),e.height!==vl?n.height=e.height:e.width!==vl?n.height=Math.round(e.width/Math.max(t.width/Math.max(t.height,1),1)):n.height=Math.round(t.height*r)}get width(){return this.effectiveSize.width}set width(t){this.preferredWidth=t}get height(){return this.effectiveSize.height}set height(t){this.preferredHeight=t}getWidth(){return this.width}getHeight(){return this.height}get scale(){return this.s}set scale(t){this.s!==t&&(this.s=t,this.preferredSize.setScalar(vl),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getScale(){return this.scale}setScale(t){this.scale=t}get baseWidth(){return this.baseSize.width}set baseWidth(t){this.baseSize.width!==t&&(this.baseSize.width=t,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseWidth(){return this.baseWidth}setBaseWidth(t){this.baseWidth=t}get baseHeight(){return this.baseSize.height}set baseHeight(t){this.baseSize.height!==t&&(this.baseSize.height=t,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseHeight(){return this.baseHeight}setBaseHeight(t){this.baseHeight=t}setBaseSize(t,e){(this.baseSize.width!==t||this.baseSize.height!==e)&&(this.baseSize.set(t,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}get preferredWidth(){return this.preferredSize.width}set preferredWidth(t){this.preferredSize.width!==t&&(this.preferredSize.width=t,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredWidth(){return this.preferredWidth}setPreferredWidth(t){this.preferredWidth=t}get preferredHeight(){return this.preferredSize.height}set preferredHeight(t){this.preferredSize.height!==t&&(this.preferredSize.height=t,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredHeight(){return this.preferredHeight}setPreferredHeight(t){this.preferredHeight=t}setPreferredSize(t,e){(this.preferredSize.width!==t||this.preferredSize.height!==e)&&(this.preferredSize.set(t,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}copy(t){this.s=t.scale,this.baseSize.set(t.baseWidth,t.baseHeight),this.preferredSize.set(t.preferredWidth,t.preferredHeight),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height)}static get AUTO_SIZE(){return vl}},Qt={SKIP:9,SET:30,ADD:0,ALPHA:1,AVERAGE:2,COLOR:3,COLOR_BURN:4,COLOR_DODGE:5,DARKEN:6,DIFFERENCE:7,DIVIDE:8,DST:9,EXCLUSION:10,HARD_LIGHT:11,HARD_MIX:12,HUE:13,INVERT:14,INVERT_RGB:15,LIGHTEN:16,LINEAR_BURN:17,LINEAR_DODGE:18,LINEAR_LIGHT:19,LUMINOSITY:20,MULTIPLY:21,NEGATION:22,NORMAL:23,OVERLAY:24,PIN_LIGHT:25,REFLECT:26,SATURATION:27,SCREEN:28,SOFT_LIGHT:29,SRC:30,SUBTRACT:31,VIVID_LIGHT:32},Dne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x+y,opacity);}",Une="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y,min(y.a,opacity));}",Fne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,(x+y)*0.5,opacity);}",Bne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.rg,xHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",zne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(step(0.0,y)*(1.0-min(vec4(1.0),(1.0-x)/y)),vec4(1.0),step(1.0,x));return mix(x,z,opacity);}",Vne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=step(0.0,x)*mix(min(vec4(1.0),x/max(1.0-y,1e-9)),vec4(1.0),step(1.0,y));return mix(x,z,opacity);}",Hne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,min(x,y),opacity);}",Gne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,abs(x-y),opacity);}",Wne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x/max(y,1e-12),opacity);}",jne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,(x+y-2.0*x*y),opacity);}",$ne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 a=min(x,1.0),b=min(y,1.0);vec4 z=mix(2.0*a*b,1.0-2.0*(1.0-a)*(1.0-b),step(0.5,y));return mix(x,z,opacity);}",qne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,step(1.0,x+y),opacity);}",Xne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.r,xHSL.gb));return vec4(mix(x.rgb,z,opacity),y.a);}",Kne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,1.0-y,opacity);}",Yne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y*(1.0-x),opacity);}",Zne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,max(x,y),opacity);}",Jne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,clamp(y+x-1.0,0.0,1.0),opacity);}",Qne="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,min(x+y,1.0),opacity);}",ere="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,clamp(2.0*y+x-1.0,0.0,1.0),opacity);}",tre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.rg,yHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",nre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x*y,opacity);}",rre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,1.0-abs(1.0-x-y),opacity);}",ire="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y,opacity);}",sre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(2.0*y*x,1.0-2.0*(1.0-y)*(1.0-x),step(0.5,x));return mix(x,z,opacity);}",ore="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 y2=2.0*y;vec4 z=mix(mix(y2,x,step(0.5*x,y)),max(vec4(0.0),y2-1.0),step(x,(y2-1.0)));return mix(x,z,opacity);}",are="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(min(x*x/max(1.0-y,1e-12),1.0),y,step(1.0,y));return mix(x,z,opacity);}",cre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.r,yHSL.g,xHSL.b));return vec4(mix(x.rgb,z,opacity),y.a);}",lre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,x+y-min(x*y,1.0),opacity);}",ure="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 y2=2.0*y;vec4 w=step(0.5,y);vec4 z=mix(x-(1.0-y2)*x*(1.0-x),mix(x+(y2-1.0)*(sqrt(x)-x),x+(y2-1.0)*x*((16.0*x-12.0)*x+3.0),w*(1.0-step(0.25,x))),w);return mix(x,z,opacity);}",hre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return y;}",fre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,max(x+y-1.0,0.0),opacity);}",dre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec4 z=mix(max(1.0-min((1.0-x)/(2.0*y),1.0),0.0),min(x/(2.0*(1.0-y)),1.0),step(0.5,y));return mix(x,z,opacity);}",pre=new Map([[Qt.ADD,Dne],[Qt.ALPHA,Une],[Qt.AVERAGE,Fne],[Qt.COLOR,Bne],[Qt.COLOR_BURN,zne],[Qt.COLOR_DODGE,Vne],[Qt.DARKEN,Hne],[Qt.DIFFERENCE,Gne],[Qt.DIVIDE,Wne],[Qt.DST,null],[Qt.EXCLUSION,jne],[Qt.HARD_LIGHT,$ne],[Qt.HARD_MIX,qne],[Qt.HUE,Xne],[Qt.INVERT,Kne],[Qt.INVERT_RGB,Yne],[Qt.LIGHTEN,Zne],[Qt.LINEAR_BURN,Jne],[Qt.LINEAR_DODGE,Qne],[Qt.LINEAR_LIGHT,ere],[Qt.LUMINOSITY,tre],[Qt.MULTIPLY,nre],[Qt.NEGATION,rre],[Qt.NORMAL,ire],[Qt.OVERLAY,sre],[Qt.PIN_LIGHT,ore],[Qt.REFLECT,are],[Qt.SATURATION,cre],[Qt.SCREEN,lre],[Qt.SOFT_LIGHT,ure],[Qt.SRC,hre],[Qt.SUBTRACT,fre],[Qt.VIVID_LIGHT,dre]]),mre=class extends zc{constructor(t,e=1){super(),this._blendFunction=t,this.opacity=new Mn(e)}getOpacity(){return this.opacity.value}setOpacity(t){this.opacity.value=t}get blendFunction(){return this._blendFunction}set blendFunction(t){this._blendFunction=t,this.dispatchEvent({type:"change"})}getBlendFunction(){return this.blendFunction}setBlendFunction(t){this.blendFunction=t}getShaderCode(){return pre.get(this.blendFunction)}},aw=class extends zc{constructor(t,e,{attributes:n=Ea.NONE,blendFunction:r=Qt.NORMAL,defines:i=new Map,uniforms:s=new Map,extensions:o=null,vertexShader:a=null}={}){super(),this.name=t,this.renderer=null,this.attributes=n,this.fragmentShader=e,this.vertexShader=a,this.defines=i,this.uniforms=s,this.extensions=o,this.blendMode=new mre(r),this.blendMode.addEventListener("change",c=>this.setChanged()),this._inputColorSpace=jl,this._outputColorSpace=pa}get inputColorSpace(){return this._inputColorSpace}set inputColorSpace(t){this._inputColorSpace=t,this.setChanged()}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t,this.setChanged()}set mainScene(t){}set mainCamera(t){}getName(){return this.name}setRenderer(t){this.renderer=t}getDefines(){return this.defines}getUniforms(){return this.uniforms}getExtensions(){return this.extensions}getBlendMode(){return this.blendMode}getAttributes(){return this.attributes}setAttributes(t){this.attributes=t,this.setChanged()}getFragmentShader(){return this.fragmentShader}setFragmentShader(t){this.fragmentShader=t,this.setChanged()}getVertexShader(){return this.vertexShader}setVertexShader(t){this.vertexShader=t,this.setChanged()}setChanged(){this.dispatchEvent({type:"change"})}setDepthTexture(t,e=ah){}update(t,e,n){}setSize(t,e){}initialize(t,e,n){}dispose(){for(const t of Object.keys(this)){const e=this[t];(e instanceof Us||e instanceof Vc||e instanceof or||e instanceof Wo)&&this[t].dispose()}}},b0={RED:0,GREEN:1,BLUE:2,ALPHA:3},ED=class extends Wo{constructor(t,e,n=null){super("RenderPass",t,e),this.needsSwap=!1,this.clearPass=new SD,this.overrideMaterialManager=n===null?null:new TN(n),this.ignoreBackground=!1,this.skipShadowMapUpdate=!1,this.selection=null}set mainScene(t){this.scene=t}set mainCamera(t){this.camera=t}get renderToScreen(){return super.renderToScreen}set renderToScreen(t){super.renderToScreen=t,this.clearPass.renderToScreen=t}get overrideMaterial(){const t=this.overrideMaterialManager;return t!==null?t.material:null}set overrideMaterial(t){const e=this.overrideMaterialManager;t!==null?e!==null?e.setMaterial(t):this.overrideMaterialManager=new TN(t):e!==null&&(e.dispose(),this.overrideMaterialManager=null)}getOverrideMaterial(){return this.overrideMaterial}setOverrideMaterial(t){this.overrideMaterial=t}get clear(){return this.clearPass.enabled}set clear(t){this.clearPass.enabled=t}getSelection(){return this.selection}setSelection(t){this.selection=t}isBackgroundDisabled(){return this.ignoreBackground}setBackgroundDisabled(t){this.ignoreBackground=t}isShadowMapDisabled(){return this.skipShadowMapUpdate}setShadowMapDisabled(t){this.skipShadowMapUpdate=t}getClearPass(){return this.clearPass}render(t,e,n,r,i){const s=this.scene,o=this.camera,a=this.selection,c=o.layers.mask,l=s.background,u=t.shadowMap.autoUpdate,h=this.renderToScreen?null:e;a!==null&&o.layers.set(a.getLayer()),this.skipShadowMapUpdate&&(t.shadowMap.autoUpdate=!1),(this.ignoreBackground||this.clearPass.overrideClearColor!==null)&&(s.background=null),this.clearPass.enabled&&this.clearPass.render(t,e),t.setRenderTarget(h),this.overrideMaterialManager!==null?this.overrideMaterialManager.render(t,s,o):t.render(s,o),o.layers.mask=c,s.background=l,t.shadowMap.autoUpdate=u}},gre=`#include -#ifdef GL_FRAGMENT_PRECISION_HIGH -uniform highp sampler2D depthBuffer; -#else -uniform mediump sampler2D depthBuffer; -#endif -#ifdef DOWNSAMPLE_NORMALS -uniform lowp sampler2D normalBuffer; -#endif -varying vec2 vUv0;varying vec2 vUv1;varying vec2 vUv2;varying vec2 vUv3;float readDepth(const in vec2 uv){ -#if DEPTH_PACKING == 3201 -return unpackRGBAToDepth(texture2D(depthBuffer,uv)); -#else -return texture2D(depthBuffer,uv).r; -#endif -}int findBestDepth(const in float samples[4]){float c=(samples[0]+samples[1]+samples[2]+samples[3])*0.25;float distances[4];distances[0]=abs(c-samples[0]);distances[1]=abs(c-samples[1]);distances[2]=abs(c-samples[2]);distances[3]=abs(c-samples[3]);float maxDistance=max(max(distances[0],distances[1]),max(distances[2],distances[3]));int remaining[3];int rejected[3];int i,j,k;for(i=0,j=0,k=0;i<4;++i){if(distances[i]this.setSize(a.baseWidth,a.baseHeight))}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}setDepthTexture(t,e=ah){this.fullscreenMaterial.depthBuffer=t,this.fullscreenMaterial.depthPacking=e}render(t,e,n,r,i){t.setRenderTarget(this.renderToScreen?null:this.renderTarget),t.render(this.scene,this.camera)}setSize(t,e){const n=this.resolution;n.setBaseSize(t,e),this.renderTarget.setSize(n.width,n.height),this.fullscreenMaterial.setSize(t,e)}initialize(t,e,n){const r=t.getContext();if(!(r.getExtension("EXT_color_buffer_float")||r.getExtension("EXT_color_buffer_half_float")))throw new Error("Rendering to float texture is not supported.")}},xre=`#include -#include -#include -#define packFloatToRGBA(v) packDepthToRGBA(v) -#define unpackRGBAToFloat(v) unpackRGBAToDepth(v) -#ifdef FRAMEBUFFER_PRECISION_HIGH -uniform mediump sampler2D inputBuffer; -#else -uniform lowp sampler2D inputBuffer; -#endif -#if DEPTH_PACKING == 3201 -uniform lowp sampler2D depthBuffer; -#elif defined(GL_FRAGMENT_PRECISION_HIGH) -uniform highp sampler2D depthBuffer; -#else -uniform mediump sampler2D depthBuffer; -#endif -uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;vec4 sRGBToLinear(const in vec4 value){return vec4(mix(pow(value.rgb*0.9478672986+vec3(0.0521327014),vec3(2.4)),value.rgb*0.0773993808,vec3(lessThanEqual(value.rgb,vec3(0.04045)))),value.a);}float readDepth(const in vec2 uv){ -#if DEPTH_PACKING == 3201 -return unpackRGBAToDepth(texture2D(depthBuffer,uv)); -#else -return texture2D(depthBuffer,uv).r; -#endif -}float getViewZ(const in float depth){ -#ifdef PERSPECTIVE_CAMERA -return perspectiveDepthToViewZ(depth,cameraNear,cameraFar); -#else -return orthographicDepthToViewZ(depth,cameraNear,cameraFar); -#endif -}vec3 RGBToHCV(const in vec3 RGB){vec4 P=mix(vec4(RGB.bg,-1.0,2.0/3.0),vec4(RGB.gb,0.0,-1.0/3.0),step(RGB.b,RGB.g));vec4 Q=mix(vec4(P.xyw,RGB.r),vec4(RGB.r,P.yzx),step(P.x,RGB.r));float C=Q.x-min(Q.w,Q.y);float H=abs((Q.w-Q.y)/(6.0*C+EPSILON)+Q.z);return vec3(H,C,Q.x);}vec3 RGBToHSL(const in vec3 RGB){vec3 HCV=RGBToHCV(RGB);float L=HCV.z-HCV.y*0.5;float S=HCV.y/(1.0-abs(L*2.0-1.0)+EPSILON);return vec3(HCV.x,S,L);}vec3 HueToRGB(const in float H){float R=abs(H*6.0-3.0)-1.0;float G=2.0-abs(H*6.0-2.0);float B=2.0-abs(H*6.0-4.0);return clamp(vec3(R,G,B),0.0,1.0);}vec3 HSLToRGB(const in vec3 HSL){vec3 RGB=HueToRGB(HSL.x);float C=(1.0-abs(2.0*HSL.z-1.0))*HSL.y;return(RGB-0.5)*C+HSL.z;}FRAGMENT_HEAD void main(){FRAGMENT_MAIN_UV vec4 color0=texture2D(inputBuffer,UV);vec4 color1=vec4(0.0);FRAGMENT_MAIN_IMAGE color0.a=clamp(color0.a,0.0,1.0);gl_FragColor=color0; -#ifdef ENCODE_OUTPUT -#include -#endif -#include -}`,Sre="uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;VERTEX_HEAD void main(){vUv=position.xy*0.5+0.5;VERTEX_MAIN_SUPPORT gl_Position=vec4(position.xy,1.0,1.0);}",Ere=class extends Gi{constructor(t,e,n,r,i=!1){super({name:"EffectMaterial",defines:{THREE_REVISION:kv.replace(/\D+/g,""),DEPTH_PACKING:"0",ENCODE_OUTPUT:"1"},uniforms:{inputBuffer:new Mn(null),depthBuffer:new Mn(null),resolution:new Mn(new St),texelSize:new Mn(new St),cameraNear:new Mn(.3),cameraFar:new Mn(1e3),aspect:new Mn(1),time:new Mn(0)},blending:Ro,toneMapped:!1,depthWrite:!1,depthTest:!1,dithering:i}),t&&this.setShaderParts(t),e&&this.setDefines(e),n&&this.setUniforms(n),this.copyCameraSettings(r)}set inputBuffer(t){this.uniforms.inputBuffer.value=t}setInputBuffer(t){this.uniforms.inputBuffer.value=t}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(t){this.uniforms.depthBuffer.value=t}get depthPacking(){return Number(this.defines.DEPTH_PACKING)}set depthPacking(t){this.defines.DEPTH_PACKING=t.toFixed(0),this.needsUpdate=!0}setDepthBuffer(t,e=ah){this.depthBuffer=t,this.depthPacking=e}setShaderData(t){this.setShaderParts(t.shaderParts),this.setDefines(t.defines),this.setUniforms(t.uniforms),this.setExtensions(t.extensions)}setShaderParts(t){return this.fragmentShader=xre.replace(_n.FRAGMENT_HEAD,t.get(_n.FRAGMENT_HEAD)||"").replace(_n.FRAGMENT_MAIN_UV,t.get(_n.FRAGMENT_MAIN_UV)||"").replace(_n.FRAGMENT_MAIN_IMAGE,t.get(_n.FRAGMENT_MAIN_IMAGE)||""),this.vertexShader=Sre.replace(_n.VERTEX_HEAD,t.get(_n.VERTEX_HEAD)||"").replace(_n.VERTEX_MAIN_SUPPORT,t.get(_n.VERTEX_MAIN_SUPPORT)||""),this.needsUpdate=!0,this}setDefines(t){for(const e of t.entries())this.defines[e[0]]=e[1];return this.needsUpdate=!0,this}setUniforms(t){for(const e of t.entries())this.uniforms[e[0]]=e[1];return this}setExtensions(t){this.extensions={};for(const e of t)this.extensions[e]=!0;return this}get encodeOutput(){return this.defines.ENCODE_OUTPUT!==void 0}set encodeOutput(t){this.encodeOutput!==t&&(t?this.defines.ENCODE_OUTPUT="1":delete this.defines.ENCODE_OUTPUT,this.needsUpdate=!0)}isOutputEncodingEnabled(t){return this.encodeOutput}setOutputEncodingEnabled(t){this.encodeOutput=t}get time(){return this.uniforms.time.value}set time(t){this.uniforms.time.value=t}setDeltaTime(t){this.uniforms.time.value+=t}adoptCameraSettings(t){this.copyCameraSettings(t)}copyCameraSettings(t){t&&(this.uniforms.cameraNear.value=t.near,this.uniforms.cameraFar.value=t.far,t instanceof Ms?this.defines.PERSPECTIVE_CAMERA="1":delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0)}setSize(t,e){const n=this.uniforms;n.resolution.value.set(t,e),n.texelSize.value.set(1/t,1/e),n.aspect.value=t/e}static get Section(){return _n}};function AN(t,e,n){for(const r of e){const i="$1"+t+r.charAt(0).toUpperCase()+r.slice(1),s=new RegExp("([^\\.])(\\b"+r+"\\b)","g");for(const o of n.entries())o[1]!==null&&n.set(o[0],o[1].replace(s,i))}}function wre(t,e,n){let r=e.getFragmentShader(),i=e.getVertexShader();const s=r!==void 0&&/mainImage/.test(r),o=r!==void 0&&/mainUv/.test(r);if(n.attributes|=e.getAttributes(),r===void 0)throw new Error(`Missing fragment shader (${e.name})`);if(o&&n.attributes&Ea.CONVOLUTION)throw new Error(`Effects that transform UVs are incompatible with convolution effects (${e.name})`);if(!s&&!o)throw new Error(`Could not find mainImage or mainUv function (${e.name})`);{const a=/\w+\s+(\w+)\([\w\s,]*\)\s*{/g,c=n.shaderParts;let l=c.get(_n.FRAGMENT_HEAD)||"",u=c.get(_n.FRAGMENT_MAIN_UV)||"",h=c.get(_n.FRAGMENT_MAIN_IMAGE)||"",p=c.get(_n.VERTEX_HEAD)||"",m=c.get(_n.VERTEX_MAIN_SUPPORT)||"";const g=new Set,v=new Set;if(o&&(u+=` ${t}MainUv(UV); -`,n.uvTransformation=!0),i!==null&&/mainSupport/.test(i)){const S=/mainSupport *\([\w\s]*?uv\s*?\)/.test(i);m+=` ${t}MainSupport(`,m+=S?`vUv); -`:`); -`;for(const E of i.matchAll(/(?:varying\s+\w+\s+([\S\s]*?);)/g))for(const b of E[1].split(/\s*,\s*/))n.varyings.add(b),g.add(b),v.add(b);for(const E of i.matchAll(a))v.add(E[1])}for(const S of r.matchAll(a))v.add(S[1]);for(const S of e.defines.keys())v.add(S.replace(/\([\w\s,]*\)/g,""));for(const S of e.uniforms.keys())v.add(S);v.delete("while"),v.delete("for"),v.delete("if"),e.uniforms.forEach((S,E)=>n.uniforms.set(t+E.charAt(0).toUpperCase()+E.slice(1),S)),e.defines.forEach((S,E)=>n.defines.set(t+E.charAt(0).toUpperCase()+E.slice(1),S));const y=new Map([["fragment",r],["vertex",i]]);AN(t,v,n.defines),AN(t,v,y),r=y.get("fragment"),i=y.get("vertex");const _=e.blendMode;if(n.blendModes.set(_.blendFunction,_),s){e.inputColorSpace!==null&&e.inputColorSpace!==n.colorSpace&&(h+=e.inputColorSpace===pr?`color0 = sRGBTransferOETF(color0); - `:`color0 = sRGBToLinear(color0); - `),e.outputColorSpace!==pa?n.colorSpace=e.outputColorSpace:e.inputColorSpace!==null&&(n.colorSpace=e.inputColorSpace);const S=/MainImage *\([\w\s,]*?depth[\w\s,]*?\)/;h+=`${t}MainImage(color0, UV, `,n.attributes&Ea.DEPTH&&S.test(r)&&(h+="depth, ",n.readDepth=!0),h+=`color1); - `;const E=t+"BlendOpacity";n.uniforms.set(E,_.opacity),h+=`color0 = blend${_.blendFunction}(color0, color1, ${E}); - - `,l+=`uniform float ${E}; - -`}if(l+=r+` -`,i!==null&&(p+=i+` -`),c.set(_n.FRAGMENT_HEAD,l),c.set(_n.FRAGMENT_MAIN_UV,u),c.set(_n.FRAGMENT_MAIN_IMAGE,h),c.set(_n.VERTEX_HEAD,p),c.set(_n.VERTEX_MAIN_SUPPORT,m),e.extensions!==null)for(const S of e.extensions)n.extensions.add(S)}}var bre=class extends Wo{constructor(t,...e){super("EffectPass"),this.fullscreenMaterial=new Ere(null,null,null,t),this.listener=n=>this.handleEvent(n),this.effects=[],this.setEffects(e),this.skipRendering=!1,this.minTime=1,this.maxTime=Number.POSITIVE_INFINITY,this.timeScale=1}set mainScene(t){for(const e of this.effects)e.mainScene=t}set mainCamera(t){this.fullscreenMaterial.copyCameraSettings(t);for(const e of this.effects)e.mainCamera=t}get encodeOutput(){return this.fullscreenMaterial.encodeOutput}set encodeOutput(t){this.fullscreenMaterial.encodeOutput=t}get dithering(){return this.fullscreenMaterial.dithering}set dithering(t){const e=this.fullscreenMaterial;e.dithering=t,e.needsUpdate=!0}setEffects(t){for(const e of this.effects)e.removeEventListener("change",this.listener);this.effects=t.sort((e,n)=>n.attributes-e.attributes);for(const e of this.effects)e.addEventListener("change",this.listener)}updateMaterial(){const t=new Pne;let e=0;for(const o of this.effects)if(o.blendMode.blendFunction===Qt.DST)t.attributes|=o.getAttributes()&Ea.DEPTH;else{if(t.attributes&o.getAttributes()&Ea.CONVOLUTION)throw new Error(`Convolution effects cannot be merged (${o.name})`);wre("e"+e++,o,t)}let n=t.shaderParts.get(_n.FRAGMENT_HEAD),r=t.shaderParts.get(_n.FRAGMENT_MAIN_IMAGE),i=t.shaderParts.get(_n.FRAGMENT_MAIN_UV);const s=/\bblend\b/g;for(const o of t.blendModes.values())n+=o.getShaderCode().replace(s,`blend${o.blendFunction}`)+` -`;t.attributes&Ea.DEPTH?(t.readDepth&&(r=`float depth = readDepth(UV); - - `+r),this.needsDepthTexture=this.getDepthTexture()===null):this.needsDepthTexture=!1,t.colorSpace===pr&&(r+=`color0 = sRGBToLinear(color0); - `),t.uvTransformation?(i=`vec2 transformedUv = vUv; -`+i,t.defines.set("UV","transformedUv")):t.defines.set("UV","vUv"),t.shaderParts.set(_n.FRAGMENT_HEAD,n),t.shaderParts.set(_n.FRAGMENT_MAIN_IMAGE,r),t.shaderParts.set(_n.FRAGMENT_MAIN_UV,i);for(const[o,a]of t.shaderParts)a!==null&&t.shaderParts.set(o,a.trim().replace(/^#/,` -#`));this.skipRendering=e===0,this.needsSwap=!this.skipRendering,this.fullscreenMaterial.setShaderData(t)}recompile(){this.updateMaterial()}getDepthTexture(){return this.fullscreenMaterial.depthBuffer}setDepthTexture(t,e=ah){this.fullscreenMaterial.depthBuffer=t,this.fullscreenMaterial.depthPacking=e;for(const n of this.effects)n.setDepthTexture(t,e)}render(t,e,n,r,i){for(const s of this.effects)s.update(t,e,r);if(!this.skipRendering||this.renderToScreen){const s=this.fullscreenMaterial;s.inputBuffer=e.texture,s.time+=r*this.timeScale,t.setRenderTarget(this.renderToScreen?null:n),t.render(this.scene,this.camera)}}setSize(t,e){this.fullscreenMaterial.setSize(t,e);for(const n of this.effects)n.setSize(t,e)}initialize(t,e,n){this.renderer=t;for(const r of this.effects)r.initialize(t,e,n);this.updateMaterial(),n!==void 0&&n!==bi&&(this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1")}dispose(){super.dispose();for(const t of this.effects)t.removeEventListener("change",this.listener),t.dispose()}handleEvent(t){switch(t.type){case"change":this.recompile();break}}},Tre=class extends Wo{constructor(t,e,{renderTarget:n,resolutionScale:r=1,width:i=Cf.AUTO_SIZE,height:s=Cf.AUTO_SIZE,resolutionX:o=i,resolutionY:a=s}={}){super("NormalPass"),this.needsSwap=!1,this.renderPass=new ED(t,e,new FG);const c=this.renderPass;c.ignoreBackground=!0,c.skipShadowMapUpdate=!0;const l=c.getClearPass();l.overrideClearColor=new ln(7829503),l.overrideClearAlpha=1,this.renderTarget=n,this.renderTarget===void 0&&(this.renderTarget=new Us(1,1,{minFilter:vr,magFilter:vr}),this.renderTarget.texture.name="NormalPass.Target");const u=this.resolution=new Cf(this,o,a,r);u.addEventListener("change",h=>this.setSize(u.baseWidth,u.baseHeight))}set mainScene(t){this.renderPass.mainScene=t}set mainCamera(t){this.renderPass.mainCamera=t}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}getResolutionScale(){return this.resolution.scale}setResolutionScale(t){this.resolution.scale=t}render(t,e,n,r,i){const s=this.renderToScreen?null:this.renderTarget;this.renderPass.render(t,s,s)}setSize(t,e){const n=this.resolution;n.setBaseSize(t,e),this.renderTarget.setSize(n.width,n.height)}};let Xd;function Are(){var t;if(Xd!==void 0)return Xd;try{let e;const n=document.createElement("canvas");return Xd=!!(window.WebGL2RenderingContext&&(e=n.getContext("webgl2"))),e&&((t=e.getExtension("WEBGL_lose_context"))==null||t.loseContext()),Xd}catch{return Xd=!1}}const Mre=Ne.createContext(null),MN=t=>(t.getAttributes()&Ea.CONVOLUTION)===Ea.CONVOLUTION,Cre=Co.memo(Ne.forwardRef(({children:t,camera:e,scene:n,resolutionScale:r,enabled:i=!0,renderPriority:s=1,autoClear:o=!0,depthBuffer:a,enableNormalPass:c,stencilBuffer:l,multisampling:u=8,frameBufferType:h=ld},p)=>{const{gl:m,scene:g,camera:v,size:y}=va(),_=n||g,S=e||v,[E,b,N]=Ne.useMemo(()=>{const C=Are(),I=new Lne(m,{depthBuffer:a,stencilBuffer:l,multisampling:u>0&&C?u:0,frameBufferType:h});I.addPass(new ED(_,S));let U=null,L=null;return c&&(L=new Tre(_,S),L.enabled=!1,I.addPass(L),r!==void 0&&C&&(U=new yre({normalBuffer:L.texture,resolutionScale:r}),U.enabled=!1,I.addPass(U))),[I,L,U]},[S,m,a,l,u,h,_,c,r]);Ne.useEffect(()=>E==null?void 0:E.setSize(y.width,y.height),[E,y]),zv((C,I)=>{if(i){const U=m.autoClear;m.autoClear=o,l&&!o&&m.clearStencil(),E.render(I),m.autoClear=U}},i?s:0);const R=Ne.useRef(null),M=_W(R);Ne.useLayoutEffect(()=>{const C=[];if(R.current&&M.current&&E){const I=M.current.objects;for(let U=0;U{for(const I of C)E==null||E.removePass(I);b&&(b.enabled=!1),N&&(N.enabled=!1)}},[E,t,S,b,N,M]),Ne.useEffect(()=>{const C=m.toneMapping;return m.toneMapping=ya,()=>{m.toneMapping=C}},[]);const O=Ne.useMemo(()=>({composer:E,normalPass:b,downSamplingPass:N,resolutionScale:r,camera:S,scene:_}),[E,b,N,r,S,_]);return Ne.useImperativeHandle(p,()=>E,[E]),ve.jsx(Mre.Provider,{value:O,children:ve.jsx("group",{ref:R,children:t})})}));let Rre=0;const CN=new WeakMap,Nre=(t,e)=>Co.forwardRef(function({blendFunction:r=void 0,opacity:i=void 0,...s},o){let a=CN.get(t);if(!a){const u=`@react-three/postprocessing/${t.name}-${Rre++}`;Cb({[u]:t}),CN.set(t,a=u)}const c=va(u=>u.camera),l=Co.useMemo(()=>{var u,h;return[...(u=void 0)!=null?u:[],...(h=s.args)!=null?h:[{...e,...s}]]},[JSON.stringify(s)]);return ve.jsx(a,{camera:c,"blendMode-blendFunction":r,"blendMode-opacity-value":i,...s,ref:o,args:l})});function rS(t,e,n,r){return new(n||(n=Promise))(function(i,s){function o(l){try{c(r.next(l))}catch(u){s(u)}}function a(l){try{c(r.throw(l))}catch(u){s(u)}}function c(l){var u;l.done?i(l.value):(u=l.value,u instanceof n?u:new n(function(h){h(u)})).then(o,a)}c((r=r.apply(t,[])).next())})}const kre=["geforce 320m","geforce 8600","geforce 8600m gt","geforce 8800 gs","geforce 8800 gt","geforce 9400","geforce 9400m g","geforce 9400m","geforce 9600m gt","geforce 9600m","geforce fx go5200","geforce gt 120","geforce gt 130","geforce gt 330m","geforce gtx 285","google swiftshader","intel g41","intel g45","intel gma 4500mhd","intel gma x3100","intel hd 3000","intel q45","legacy","mali-2","mali-3","mali-4","quadro fx 1500","quadro fx 4","quadro fx 5","radeon hd 2400","radeon hd 2600","radeon hd 4670","radeon hd 4850","radeon hd 4870","radeon hd 5670","radeon hd 5750","radeon hd 6290","radeon hd 6300","radeon hd 6310","radeon hd 6320","radeon hd 6490m","radeon hd 6630m","radeon hd 6750m","radeon hd 6770m","radeon hd 6970m","sgx 543","sgx543"];function RN(t){return t=t.toLowerCase().replace(/.*angle ?\((.+)\)(?: on vulkan [0-9.]+)?$/i,"$1").replace(/\s(\d{1,2}gb|direct3d.+$)|\(r\)| \([^)]+\)$/g,"").replace(/(?:vulkan|opengl) \d+\.\d+(?:\.\d+)?(?: \((.*)\))?/,"$1")}const wD=typeof window>"u",la=(()=>{if(wD)return;const{userAgent:t,platform:e,maxTouchPoints:n}=window.navigator,r=/(iphone|ipod|ipad)/i.test(t),i=e==="iPad"||e==="MacIntel"&&n>0&&!window.MSStream;return{isIpad:i,isMobile:/android/i.test(t)||r||i,isSafari12:/Version\/12.+Safari/.test(t),isFirefox:/Firefox/.test(t)}})();function Ire(t,e,n){if(!n)return[e];const r=function(l){const u=` - precision highp float; - attribute vec3 aPosition; - varying float vvv; - void main() { - vvv = 0.31622776601683794; - gl_Position = vec4(aPosition, 1.0); - } - `,h=` - precision highp float; - varying float vvv; - void main() { - vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * vvv; - enc = fract(enc); - enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0); - gl_FragColor = enc; - } - `,p=l.createShader(35633),m=l.createShader(35632),g=l.createProgram();if(!(m&&p&&g))return;l.shaderSource(p,u),l.shaderSource(m,h),l.compileShader(p),l.compileShader(m),l.attachShader(g,p),l.attachShader(g,m),l.linkProgram(g),l.detachShader(g,p),l.detachShader(g,m),l.deleteShader(p),l.deleteShader(m),l.useProgram(g);const v=l.createBuffer();l.bindBuffer(34962,v),l.bufferData(34962,new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),35044);const y=l.getAttribLocation(g,"aPosition");l.vertexAttribPointer(y,3,5126,!1,0,0),l.enableVertexAttribArray(y),l.clearColor(1,1,1,1),l.clear(16384),l.viewport(0,0,1,1),l.drawArrays(4,0,3);const _=new Uint8Array(4);return l.readPixels(0,0,1,1,6408,5121,_),l.deleteProgram(g),l.deleteBuffer(v),_.join("")}(t),i="801621810",s="8016218135",o="80162181161",a=la!=null&&la.isIpad?[["a7",o,12],["a8",s,15],["a8x",s,15],["a9",s,15],["a9x",s,15],["a10",s,15],["a10x",s,15],["a12",i,15],["a12x",i,15],["a12z",i,15],["a14",i,15],["a15",i,15],["m1",i,15],["m2",i,15]]:[["a7",o,12],["a8",s,12],["a9",s,15],["a10",s,15],["a11",i,15],["a12",i,15],["a13",i,15],["a14",i,15],["a15",i,15],["a16",i,15],["a17",i,15]];let c;return r==="80162181255"?c=a.filter(([,,l])=>l>=14):(c=a.filter(([,l])=>l===r),c.length||(c=a)),c.map(([l])=>`apple ${l} gpu`)}class NN extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}const iS=[],kN=[];function Ore(t,e){if(t===e)return 0;const n=t;t.length>e.length&&(t=e,e=n);let r=t.length,i=e.length;for(;r>0&&t.charCodeAt(~-r)===e.charCodeAt(~-i);)r--,i--;let s,o=0;for(;ol?c>l?l+1:c:c>a?a+1:c;return l}function Lre(t){return t!=null}const Pre=({mobileTiers:t=[0,15,30,60],desktopTiers:e=[0,15,30,60],override:n={},glContext:r,failIfMajorPerformanceCaveat:i=!1,benchmarksURL:s="https://unpkg.com/detect-gpu@5.0.56/dist/benchmarks"}={})=>rS(void 0,void 0,void 0,function*(){const o={};if(wD)return{tier:0,type:"SSR"};const{isIpad:a=!!(la!=null&&la.isIpad),isMobile:c=!!(la!=null&&la.isMobile),screenSize:l=window.screen,loadBenchmarks:u=N=>rS(void 0,void 0,void 0,function*(){const R=yield fetch(`${s}/${N}`).then(M=>M.json());if(parseInt(R.shift().split(".")[0],10)<4)throw new NN("Detect GPU benchmark data is out of date. Please update to version 4x");return R})}=n;let{renderer:h}=n;const p=(N,R,M,O,C)=>({device:C,fps:O,gpu:M,isMobile:c,tier:N,type:R});let m,g="";if(h)h=RN(h),m=[h];else{const N=r||function(M,O=!1){const C={alpha:!1,antialias:!1,depth:!1,failIfMajorPerformanceCaveat:O,powerPreference:"high-performance",stencil:!1};M&&delete C.powerPreference;const I=window.document.createElement("canvas"),U=I.getContext("webgl",C)||I.getContext("experimental-webgl",C);return U??void 0}(la==null?void 0:la.isSafari12,i);if(!N)return p(0,"WEBGL_UNSUPPORTED");const R=la!=null&&la.isFirefox?null:N.getExtension("WEBGL_debug_renderer_info");if(h=R?N.getParameter(R.UNMASKED_RENDERER_WEBGL):N.getParameter(N.RENDERER),!h)return p(1,"FALLBACK");g=h,h=RN(h),m=function(M,O,C){return O==="apple gpu"?Ire(M,O,C):[O]}(N,h,c)}const v=(yield Promise.all(m.map(function(N){var R;return rS(this,void 0,void 0,function*(){const M=(ge=>{const Q=c?["adreno","apple","mali-t","mali","nvidia","powervr","samsung"]:["intel","apple","amd","radeon","nvidia","geforce","adreno"];for(const re of Q)if(ge.includes(re))return re})(N);if(!M)return;const O=`${c?"m":"d"}-${M}${a?"-ipad":""}.json`,C=o[O]=(R=o[O])!==null&&R!==void 0?R:u(O);let I;try{I=yield C}catch(ge){if(ge instanceof NN)throw ge;return}const U=function(ge){var Q;const re=(ge=ge.replace(/\([^)]+\)/,"")).match(/\d+/)||ge.match(/(\W|^)([A-Za-z]{1,3})(\W|$)/g);return(Q=re==null?void 0:re.join("").replace(/\W|amd/g,""))!==null&&Q!==void 0?Q:""}(N);let L=I.filter(([,ge])=>ge===U);L.length||(L=I.filter(([ge])=>ge.includes(N)));const P=L.length;if(P===0)return;const T=N.split(/[.,()\[\]/\s]/g).sort().filter((ge,Q,re)=>Q===0||ge!==re[Q-1]).join(" ");let H,[V,,,,B]=P>1?L.map(ge=>[ge,Ore(T,ge[2])]).sort(([,ge],[,Q])=>ge-Q)[0][0]:L[0],z=Number.MAX_VALUE;const{devicePixelRatio:W}=window,K=l.width*W*l.height*W;for(const ge of B){const[Q,re]=ge,we=Q*re,Ae=Math.abs(K-we);AeN===M?R-O:N-M);if(!v.length){const N=kre.find(R=>h.includes(R));return N?p(0,"BLOCKLISTED",N):p(1,"FALLBACK",`${h} (${g})`)}const[,y,_,S]=v[0];if(y===-1)return p(0,"BLOCKLISTED",_,y,S);const E=c?t:e;let b=0;for(let N=0;N=E[N]&&(b=N);return p(b,"BENCHMARK",_,y,S)});var bD={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(To,function(){var n=function(){function r(m){return o.appendChild(m.dom),m}function i(m){for(var g=0;gc+1e3&&(u.update(1e3*l/(m-c),100),c=m,l=0,p)){var g=performance.memory;p.update(g.usedJSHeapSize/1048576,g.jsHeapSizeLimit/1048576)}return m},update:function(){a=this.end()},domElement:o,setMode:i}};return n.Panel=function(r,i,s){var o=1/0,a=0,c=Math.round,l=c(window.devicePixelRatio||1),u=80*l,h=48*l,p=3*l,m=2*l,g=3*l,v=15*l,y=74*l,_=30*l,S=document.createElement("canvas");S.width=u,S.height=h,S.style.cssText="width:80px;height:48px";var E=S.getContext("2d");return E.font="bold "+9*l+"px Helvetica,Arial,sans-serif",E.textBaseline="top",E.fillStyle=s,E.fillRect(0,0,u,h),E.fillStyle=i,E.fillText(r,p,m),E.fillRect(g,v,y,_),E.fillStyle=s,E.globalAlpha=.9,E.fillRect(g,v,y,_),{dom:S,update:function(b,N){o=Math.min(o,b),a=Math.max(a,b),E.fillStyle=s,E.globalAlpha=1,E.fillRect(0,0,u,v),E.fillStyle=i,E.fillText(c(b)+" "+r+" ("+c(o)+"-"+c(a)+")",p,m),E.drawImage(S,g+l,v,y-l,_,g,v,y-l,_),E.fillRect(g+y-l,v,l,_),E.fillStyle=s,E.globalAlpha=.9,E.fillRect(g+y-l,v,l,c((1-b/N)*_))}}},n})})(bD);var Dre=bD.exports;const Ure=Bc(Dre),Ra=!!JSON.parse("false"),Fre=!!JSON.parse("false"),Bre=!!JSON.parse("false"),zre=!!JSON.parse("false");JSON.parse("false");const Vre=!!JSON.parse("false"),Hre=` -vec3 halftone(vec3 texcolor, vec2 st, float frequency) { - float n = 0.1 * snoise(st * 200.0); // Fractal noise - n += 0.05 * snoise(st * 400.0); - n += 0.025 * snoise(st * 800.0); - - // Perform a rough RGB-to-CMYK conversion - vec4 cmyk; - // CMY = 1-RGB - cmyk.xyz = 1.0 - texcolor; - // Black generation: K = min(C,M,Y) - cmyk.w = min(cmyk.x, min(cmyk.y, cmyk.z)); - // Grey component replacement: subtract K from CMY - cmyk.xyz -= cmyk.w; - - // K based modifier - float flex = pow(cmyk.w, 3.11); - - // Distance to nearest point in a grid of - // (frequency x frequency) points over the unit square - - float t = 0.1 + 0.1 * n + 0.11 * flex + 0.1 * cmyk.y; - - // K component: 45 degrees screen angle - vec2 Kst = frequency * mat2(0.707, -0.707, 0.707, 0.707) * st; - vec2 Kuv = 2.0 * fract(Kst) - 1.0; - float k = aastep(0.0, sqrt(cmyk.w) + t - length(Kuv) + n); - - // C component: 15 degrees screen angle - vec2 Cst = frequency*mat2(0.966, -0.259, 0.259, 0.966) * st; - vec2 Cuv = 2.0 * fract(Cst) - 1.0; - float c = aastep(0.0, sqrt(cmyk.x) + t - length(Cuv) + n); - - // M component: -15 degrees screen angle - vec2 Mst = frequency * mat2(0.966, 0.259, -0.259, 0.966) * st; - vec2 Muv = 2.0 * fract(Mst) - 1.0; - float m = aastep(0.0, sqrt(cmyk.y) + t - length(Muv) + n); - - // Y component: 0 degrees screen angle - vec2 Yst = frequency * st; // 0 deg - vec2 Yuv = 2.0 * fract(Yst) - 1.0; - float y = aastep(0.0, sqrt(cmyk.z) + t - length(Yuv) + n); - - // CMY screen in RGB - vec3 black = vec3(n + 0.01); - vec3 rgbscreen = 1.0 - vec3(c,m,y) + n; - - // Blend in K for final color - vec3 factor = mix(rgbscreen, black, 1.1 * k + 0.3 * n); - - // Blend with og color - return mix(factor, texcolor, 0.777); -} - -vec3 halftone(vec3 texcolor, vec2 st) { - return halftone(texcolor, st, 412.321); -} -`,Gre=` -float blendLighten(float base, float blend) { - return max(blend,base); -} - -vec3 blendLighten(vec3 base, vec3 blend) { - return vec3(blendLighten(base.r,blend.r),blendLighten(base.g,blend.g),blendLighten(base.b,blend.b)); -} - -vec3 blendLighten(vec3 base, vec3 blend, float opacity) { - return (blendLighten(base, blend) * opacity + base * (1.0 - opacity)); -} - -float blendDarken(float base, float blend) { - return min(blend,base); -} - -vec3 blendDarken(vec3 base, vec3 blend) { - return vec3(blendDarken(base.r,blend.r),blendDarken(base.g,blend.g),blendDarken(base.b,blend.b)); -} - -vec3 blendDarken(vec3 base, vec3 blend, float opacity) { - return (blendDarken(base, blend) * opacity + base * (1.0 - opacity)); -} -`,Wre=` -float aastep(float threshold, float value) { - float afwidth = length(vec2(dFdx(value), dFdy(value))) * 0.70710678118654757; - return smoothstep(threshold-afwidth, threshold+afwidth, value); -} -`,jre=` -// -// Description : Array and textureless GLSL 2D simplex noise function. -// Author : Ian McEwan, Ashima Arts. -// Maintainer : ijm -// Lastmod : 20110822 (ijm) -// License : Copyright (C) 2011 Ashima Arts. All rights reserved. -// Distributed under the MIT License. See LICENSE file. -// https://github.com/ashima/webgl-noise -// - -vec3 mod289(vec3 x) { - return x - floor(x * (1.0 / 289.0)) * 289.0; -} - -vec2 mod289(vec2 x) { - return x - floor(x * (1.0 / 289.0)) * 289.0; -} - -vec3 permute(vec3 x) { - return mod289(((x*34.0)+1.0)*x); -} - -float snoise(vec2 v) { - const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0 - 0.366025403784439, // 0.5*(sqrt(3.0)-1.0) - -0.577350269189626, // -1.0 + 2.0 * C.x - 0.024390243902439); // 1.0 / 41.0 -// First corner - vec2 i = floor(v + dot(v, C.yy) ); - vec2 x0 = v - i + dot(i, C.xx); - -// Other corners - vec2 i1; - //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0 - //i1.y = 1.0 - i1.x; - i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); - // x0 = x0 - 0.0 + 0.0 * C.xx ; - // x1 = x0 - i1 + 1.0 * C.xx ; - // x2 = x0 - 1.0 + 2.0 * C.xx ; - vec4 x12 = x0.xyxy + C.xxzz; - x12.xy -= i1; - -// Permutations - i = mod289(i); // Avoid truncation effects in permutation - vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 )) - + i.x + vec3(0.0, i1.x, 1.0 )); - - vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0); - m = m*m ; - m = m*m ; - -// Gradients: 41 points uniformly over a line, mapped onto a diamond. -// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287) - - vec3 x = 2.0 * fract(p * C.www) - 1.0; - vec3 h = abs(x) - 0.5; - vec3 ox = floor(x + 0.5); - vec3 a0 = x - ox; - -// Normalise gradients implicitly by scaling m -// Approximation of: m *= inversesqrt( a0*a0 + h*h ); - m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ); - -// Compute final noise value at P - vec3 g; - g.x = a0.x * x0.x + h.x * x0.y; - g.yz = a0.yz * x12.xz + h.yz * x12.yw; - return 130.0 * dot(m, g); -} -`,$re=` -#ifdef ASPECT_CORRECTION - uniform float scale; -#else - uniform mat3 uvTransform; -#endif - -varying vec2 vUv2; - -void mainSupport(const in vec2 uv) { - #ifdef ASPECT_CORRECTION - vUv2 = uv * vec2(aspect, 1.0) * scale; - #else - vUv2 = (uvTransform * vec3(uv, 1.0)).xy; - #endif -} -`,qre=` -uniform float viewheight; -uniform sampler2D splat; - -${Gre} -${Wre} -${jre} -${Hre} - -float rectdistance(vec2 uv) { - vec2 tl = vec2(-1.0); - vec2 br = vec2(1.0); - vec2 d = max(tl - uv, uv - br); - return abs(length(max(vec2(0.0), d)) + min(0.0, max(d.x, d.y))); -} - -vec2 bendy(const in vec2 xn, float dn, float sn) { - // config - float distortion = 0.0173 + dn; // 0.0173, 0.511 - float scale = 0.991 + sn; // 1.0, 0.7 - // calc - vec3 xDistorted = vec3((1.0 + vec2(distortion, distortion) * dot(xn, xn)) * xn, 1.0); - mat3 kk = mat3( - vec3(1.0, 0.0, 0.0), - vec3(0.0, 1.0, 0.0), - vec3(0.0, 0.0, 1.0) - ); - return (kk * xDistorted).xy * scale; -} - -void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) { - #ifdef UV_TRANSFORM - vec4 bright = texture2D(splat, vUv2); - vec4 dark = texture2D(splat, 1.0 - vUv2); - #else - vec4 bright = texture2D(splat, uv); - vec4 dark = texture2D(splat, 1.0 - uv); - #endif - - float n = 0.1 * snoise(uv.st * 200.0); // Fractal noise - n += 0.05 * snoise(uv.st * 400.0); - n += 0.025 * snoise(uv.st * 800.0); - - vec2 xn = 2.0 * (uv.st - 0.5); - vec2 edge = bendy(xn, 0.0091 * n, 0.0011 * -n); - vec2 bent = edge.xy * 0.5 + 0.5; - - float dx = rectdistance(xn); - float bx = rectdistance(edge); - - // apply shape - float doot = max(abs(edge.x), abs(edge.y)); - if (doot < 1.0) { - // display - outputColor = texture2D(inputBuffer, bent); - - // apply scratches - outputColor.rgb = blendLighten(outputColor.rgb, bright.rgb, 0.111); - outputColor.rgb = blendDarken(outputColor.rgb, dark.rgb, 0.111); - - // apply halftones - outputColor.rgb = halftone(outputColor.rgb, uv.st); - - } else if (doot > 1.004) { - // display shell - // rbgb 205 205 193 - vec3 matte = vec3(205.0 / 255.0, 205.0 / 255.0, 193.0 / 255.0); - vec3 dkmatte = mix(matte, vec3(0.0), 0.5); - float mx = pow(1.0 - bx, 16.0) + n; - outputColor = vec4(mix(matte, dkmatte, mx), inputColor.a); - - } else { - // border - outputColor = vec4(mix(vec3(0.0), outputColor.rgb, 0.5), inputColor.a); - } - - // apply inner shade - if (doot >= 0.5 && doot < 1.0) { - float sh = clamp(0.0, 1.0, 1.0 - bx - 0.7); - vec3 shade = mix(outputColor.rgb, vec3(0.0), pow(sh, 4.0)); - outputColor = vec4(shade, inputColor.a); - } - - // apply outer shade - if (doot >= 0.97) { - float sh = clamp(0.0, 1.0, bx * 24.0); - vec3 dkout = mix(vec3(0.0), outputColor.rgb, 0.81); - vec3 shade = mix(dkout, outputColor.rgb, sh); - outputColor = vec4(shade, inputColor.a); - } -} -`;class Xre extends aw{constructor({splat:e,viewheight:n}={}){super("CRTShapeEffect",qre,{blendFunction:Qt.NORMAL,attributes:Ea.CONVOLUTION,defines:new Map([["TEXEL","texel"],["TEXTURE_PRECISION_HIGH","1"]]),uniforms:new Map([["splat",new Mn(e)],["viewheight",new Mn(n??128)]])})}get splat(){var e;return(e=this.uniforms.get("splat"))==null?void 0:e.value}set splat(e){const{splat:n,uniforms:r,defines:i}=this,s=r.get("splat"),o=r.get("uvTransform");n!==e&&s&&o&&(s.value=e,o.value=e.matrix,i.delete("TEXTURE_PRECISION_HIGH"),e!==null&&(e.matrixAutoUpdate?(i.set("UV_TRANSFORM","1"),this.setVertexShader($re)):(i.delete("UV_TRANSFORM"),this.setVertexShader(null)),e.type!==bi&&i.set("TEXTURE_PRECISION_HIGH","1"),(n===null||(n==null?void 0:n.type)!==e.type)&&this.setChanged()))}getTexture(){return this.splat}setTexture(e){this.splat=e}get aspectCorrection(){return this.defines.has("ASPECT_CORRECTION")}set aspectCorrection(e){this.aspectCorrection!==e&&(e?this.defines.set("ASPECT_CORRECTION","1"):this.defines.delete("ASPECT_CORRECTION"),this.setChanged())}get uvTransform(){const e=this.splat;return!!(e!=null&&e.matrixAutoUpdate)}set uvTransform(e){const n=this.splat;Z(n)&&(n.matrixAutoUpdate=e)}setTextureSwizzleRGBA(e,n=e,r=e,i=e){const s="rgba";let o="";(e!==b0.RED||n!==b0.GREEN||r!==b0.BLUE||i!==b0.ALPHA)&&(o=[".",s[e],s[n],s[r],s[i]].join("")),this.defines.set("TEXEL","texel"+o),this.setChanged()}update(){var e;(e=this.splat)!=null&&e.matrixAutoUpdate&&this.splat.updateMatrix()}}const Kre=Nre(Xre),Yre="/assets/scratches-BBiC0fzb.gif",sS=t=>t===Object(t)&&!Array.isArray(t)&&typeof t!="function";function KT(t,e){const n=va(s=>s.gl),r=tm(Ab,sS(t)?Object.values(t):t);return Ne.useLayoutEffect(()=>{e==null||e(r)},[e,r]),Ne.useEffect(()=>{if("initTexture"in n){let s=[];Array.isArray(r)?s=r:r instanceof or?s=[r]:sS(r)&&(s=Object.values(r)),s.forEach(o=>{o instanceof or&&n.initTexture(o)})}},[n,r]),Ne.useMemo(()=>{if(sS(t)){const s={};let o=0;for(const a in t)s[a]=r[o++];return s}else return r},[t,r])}KT.preload=t=>tm.preload(Ab,t);KT.clear=t=>tm.clear(Ab,t);function Zre(t){const e=new Set;function n(r){e.has(r.id)||(e.add(r.id),Yt.invoke(r))}return lh("forward",["all"],r=>{e.has(r.id)||(e.add(r.id),t(r))}),n}function Jre(t){return new Worker("/assets/instance-BaZ499FU.js",{name:t==null?void 0:t.name})}const Qre=lh("gadgetclient",[],t=>{const{desync:e,gadget:n}=os.getState();switch(t.target){case"reset":t.player===n.player&&os.setState({desync:!1,gadget:t.data});break;case"patch":t.player===n.player&&!e&&os.setState(r=>{try{const{newDocument:i}=Vv(r.gadget,t.data,!0,!1);return{...r,gadget:i}}catch(i){i instanceof Nb&&(os.setState({desync:!0}),Qre.reply(t,"desync",void 0,t.player))}return r});break}});function Pp(){return Pp=Object.assign||function(t){for(var e=1;e0}function lw(t){p_++;try{return t()}finally{p_--,p_===0&&iie()}}var uw=!1;function CD(){return uw}function RD(t){uw=!0;try{t()}finally{uw=!1}}function rie(t){return function(){return RD(t)}}var hw=[];function iie(){var t=[].concat(hw);hw=[],ND(t)}function ND(t){var e=new Set;t.forEach(function(n){var r;(n.type==="add"||n.type==="delete")&&n.observable[Br].connections.iterate.forEach(function(i){e.add(i)}),(r=n.observable[Br].connections.byKey.get(n.key))==null||r.forEach(function(i){e.add(i)})}),e.forEach(function(n){n.trigger()})}function T0(t){if(MD()){hw.push(t);return}ND([t])}function IN(t,e){if(t.type==="iterate")t.observable[Br].connections.iterate.add(e);else{var n=t.observable[Br].connections.byKey.get(t.key);n||(n=new Set,t.observable[Br].connections.byKey.set(t.key,n)),n.add(e)}}function A0(t,e){if(!CD()){var n=AD();n&&(IN(t,n),n.registerConnection(t)),e&&(IN(t,e),e.registerConnection(t))}}var ZT=Symbol("$skipreactive"),Br=Symbol("$reactive"),ho=Symbol("$reactiveproxy");function Tm(t,e){return!!(t&&t[ho]&&t[ho].implicitObserver===e)}function JT(t){return t[ZT]=!0,t}function kD(t){return!!(t&&!Tm(t)&&t[Br])}function fw(t,e,n){if(n===void 0&&(n=!1),t[ZT]||Tm(t,e))return t;var r=sie(t,n);if(!e)return r;var i=r[Br].proxiesWithImplicitObserver.get(e);if(!i){var s={implicitObserver:e};Object.setPrototypeOf(s,ID),i=new Proxy(r[Br].raw,s),r[Br].proxiesWithImplicitObserver.set(e,i)}return i}var Zf=fw;function sie(t,e){if(e===void 0&&(e=!1),Tm(t))return t;if(kD(t))return t[Br].proxy;if(t[Br]||t[ho])throw new Error("unexpected");var n={connections:{iterate:new Set,byKey:new Map},proxy:{},raw:t,proxiesWithImplicitObserver:new Map,shallow:e};Object.defineProperty(t,Br,{enumerable:!1,writable:!0,configurable:!0,value:n});var r=new Proxy(t,ID);return n.proxy=r,r}var ID={has:function(e,n){var r=Reflect.has(e,n);return typeof n=="symbol"||A0({observable:e,key:n,type:"has"},this.implicitObserver),r},get:function(e,n,r){if(n===ho)return{implicitObserver:this.implicitObserver};var i=Reflect.get(e,n,r);if(typeof n=="symbol")return n.toString()==="Symbol($reactiveproxy)"&&console.error("warning, Symbol($reactiveproxy) passed, but does not match $reactiveproxy. Multiple Reactive libraries loaded?"),i;if(n==="length"&&Array.isArray(e)?A0({observable:e,type:"iterate"},this.implicitObserver):A0({observable:e,key:n,type:"get"},this.implicitObserver),kD(i))return fw(i,this.implicitObserver);if(e[Br].shallow)return i;if(typeof i=="object"&&i!==null&&!Tm(i,this.implicitObserver)&&!Object.isFrozen(i)){var s=Reflect.getOwnPropertyDescriptor(e,n);if((!s||!(s.writable===!1&&s.configurable===!1))&&(TD()||this.implicitObserver))return fw(i,this.implicitObserver)}return i},ownKeys:function(e){return A0({observable:e,type:"iterate"},this.implicitObserver),Reflect.ownKeys(e)},set:function(e,n,r,i){return lw(function(){if(typeof n=="symbol")return Reflect.set(e,n,r,i);var s=Object.hasOwnProperty.call(e,n),o=Reflect.get(e,n,i),a=Reflect.set(e,n,r,i);if(!s)T0({observable:e,key:n,value:r,type:"add"});else if(r!==o)if(n==="length"&&Array.isArray(e)){if(!(onew Map,dw=t=>{const e=ko();return t.forEach((n,r)=>{e.set(r,n)}),e},Kl=(t,e,n)=>{let r=t.get(e);return r===void 0&&t.set(e,r=n()),r},uie=(t,e)=>{const n=[];for(const[r,i]of t)n.push(e(i,r));return n},hie=(t,e)=>{for(const[n,r]of t)if(e(r,n))return!0;return!1},Jf=()=>new Set,oS=t=>t[t.length-1],fie=(t,e)=>{for(let n=0;n{this.off(e,r),n(...i)};this.on(e,r)}off(e,n){const r=this._observers.get(e);r!==void 0&&(r.delete(n),r.size===0&&this._observers.delete(e))}emit(e,n){return Ul((this._observers.get(e)||ko()).values()).forEach(r=>r(...n))}destroy(){this._observers=ko()}}const Fl=Math.floor,m_=Math.abs,LD=(t,e)=>tt>e?t:e,PD=t=>t!==0?t<0:1/t<0,ON=1,LN=2,aS=4,cS=8,Dp=32,bc=64,Ds=128,Ay=31,pw=63,Gu=127,mie=2147483647,DD=Number.MAX_SAFE_INTEGER,gie=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Fl(t)===t),_ie=t=>t.toLowerCase(),vie=/^\s*/g,yie=t=>t.replace(vie,""),xie=/([A-Z])/g,PN=(t,e)=>yie(t.replace(xie,n=>`${e}${_ie(n)}`)),Sie=t=>{const e=unescape(encodeURIComponent(t)),n=e.length,r=new Uint8Array(n);for(let i=0;iUp.encode(t),wie=Up?Eie:Sie;let vp=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});vp&&vp.decode(new Uint8Array).length===1&&(vp=null);class Am{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Cl=()=>new Am,bie=t=>{let e=t.cpos;for(let n=0;n{const e=new Uint8Array(bie(t));let n=0;for(let r=0;r{const n=t.cbuf.length;n-t.cpos{const n=t.cbuf.length;t.cpos===n&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(n*2),t.cpos=0),t.cbuf[t.cpos++]=e},mw=ei,Ht=(t,e)=>{for(;e>Gu;)ei(t,Ds|Gu&e),e=Fl(e/128);ei(t,Gu&e)},QT=(t,e)=>{const n=PD(e);for(n&&(e=-e),ei(t,(e>pw?Ds:0)|(n?bc:0)|pw&e),e=Fl(e/64);e>0;)ei(t,(e>Gu?Ds:0)|Gu&e),e=Fl(e/128)},gw=new Uint8Array(3e4),Aie=gw.length/3,Mie=(t,e)=>{if(e.length{const n=unescape(encodeURIComponent(e)),r=n.length;Ht(t,r);for(let i=0;i{const n=t.cbuf.length,r=t.cpos,i=LD(n-r,e.length),s=e.length-i;t.cbuf.set(e.subarray(0,i),r),t.cpos+=i,s>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(_h(n*2,s)),t.cbuf.set(e.subarray(i)),t.cpos=s)},xi=(t,e)=>{Ht(t,e.byteLength),My(t,e)},eA=(t,e)=>{Tie(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},Rie=(t,e)=>eA(t,4).setFloat32(0,e,!1),Nie=(t,e)=>eA(t,8).setFloat64(0,e,!1),kie=(t,e)=>eA(t,8).setBigInt64(0,e,!1),DN=new DataView(new ArrayBuffer(4)),Iie=t=>(DN.setFloat32(0,t),DN.getFloat32(0)===t),Fp=(t,e)=>{switch(typeof e){case"string":ei(t,119),Rf(t,e);break;case"number":gie(e)&&m_(e)<=mie?(ei(t,125),QT(t,e)):Iie(e)?(ei(t,124),Rie(t,e)):(ei(t,123),Nie(t,e));break;case"bigint":ei(t,122),kie(t,e);break;case"object":if(e===null)ei(t,126);else if(die(e)){ei(t,117),Ht(t,e.length);for(let n=0;n0&&Ht(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const FN=t=>{t.count>0&&(QT(t.encoder,t.count===1?t.s:-t.s),t.count>1&&Ht(t.encoder,t.count-2))};class g_{constructor(){this.encoder=new Am,this.s=0,this.count=0}write(e){this.s===e?this.count++:(FN(this),this.count=1,this.s=e)}toUint8Array(){return FN(this),Mo(this.encoder)}}const BN=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);QT(t.encoder,e),t.count>1&&Ht(t.encoder,t.count-2)}};class lS{constructor(){this.encoder=new Am,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(BN(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return BN(this),Mo(this.encoder)}}class Oie{constructor(){this.sarr=[],this.s="",this.lensE=new g_}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new Am;return this.sarr.push(this.s),this.s="",Rf(e,this.sarr.join("")),My(e,this.lensE.toUint8Array()),Mo(e)}}const Bl=t=>new Error(t),wa=()=>{throw Bl("Method unimplemented")},Na=()=>{throw Bl("Unexpected case")},UD=Bl("Unexpected end of array"),FD=Bl("Integer out of Range");class Cy{constructor(e){this.arr=e,this.pos=0}}const vh=t=>new Cy(t),Lie=t=>t.pos!==t.arr.length,Pie=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},Oi=t=>Pie(t,Gt(t)),Qf=t=>t.arr[t.pos++],Gt=t=>{let e=0,n=1;const r=t.arr.length;for(;t.posDD)throw FD}throw UD},tA=t=>{let e=t.arr[t.pos++],n=e&pw,r=64;const i=(e&bc)>0?-1:1;if(!(e&Ds))return i*n;const s=t.arr.length;for(;t.posDD)throw FD}throw UD},Die=t=>{let e=Gt(t);if(e===0)return"";{let n=String.fromCodePoint(Qf(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(Qf(t));else for(;e>0;){const r=e<1e4?e:1e4,i=t.arr.subarray(t.pos,t.pos+r);t.pos+=r,n+=String.fromCodePoint.apply(null,i),e-=r}return decodeURIComponent(escape(n))}},Uie=t=>vp.decode(Oi(t)),Nf=vp?Uie:Die,nA=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},Fie=t=>nA(t,4).getFloat32(0,!1),Bie=t=>nA(t,8).getFloat64(0,!1),zie=t=>nA(t,8).getBigInt64(0,!1),Vie=[t=>{},t=>null,tA,Fie,Bie,zie,t=>!1,t=>!0,Nf,t=>{const e=Gt(t),n={};for(let r=0;r{const e=Gt(t),n=[];for(let r=0;rVie[127-Qf(t)](t);class zN extends Cy{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Lie(this)?this.count=Gt(this)+1:this.count=-1),this.count--,this.s}}class __ extends Cy{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=tA(this);const e=PD(this.s);this.count=1,e&&(this.s=-this.s,this.count=Gt(this)+2)}return this.count--,this.s}}class uS extends Cy{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=tA(this),n=e&1;this.diff=Fl(e/2),this.count=1,n&&(this.count=Gt(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Hie{constructor(e){this.decoder=new __(e),this.str=Nf(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),n=this.str.slice(this.spos,e);return this.spos=e,n}}const Gie=crypto.getRandomValues.bind(crypto),BD=()=>Gie(new Uint32Array(1))[0],Wie="10000000-1000-4000-8000"+-1e11,jie=()=>Wie.replace(/[018]/g,t=>(t^BD()&15>>t/4).toString(16)),VN=t=>new Promise(t);Promise.all.bind(Promise);const HN=t=>t===void 0?null:t;class $ie{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let zD=new $ie,qie=!0;try{typeof localStorage<"u"&&localStorage&&(zD=localStorage,qie=!1)}catch{}const Xie=zD,Kie=Object.assign,Yie=Object.keys,Zie=(t,e)=>{for(const n in t)e(t[n],n)},GN=t=>Yie(t).length,Jie=t=>{for(const e in t)return!1;return!0},Qie=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},ese=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),tse=(t,e)=>t===e||GN(t)===GN(e)&&Qie(t,(n,r)=>(n!==void 0||ese(e,r))&&e[r]===n),nse=Object.freeze,VD=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&VD(t[e])}return nse(t)},rA=(t,e,n=0)=>{try{for(;nt,ise=(t,e)=>e.includes(t);var HD={};const zp=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let ia;const sse=()=>{if(ia===void 0)if(zp){ia=ko();const t=process.argv;let e=null;for(let n=0;n{if(t.length!==0){const[e,n]=t.split("=");ia.set(`--${PN(e,"-")}`,n),ia.set(`-${PN(e,"-")}`,n)}})):ia=ko();return ia},_w=t=>sse().has(t),iv=t=>HN(zp?HD[t.toUpperCase().replaceAll("-","_")]:Xie.getItem(t)),GD=t=>_w("--"+t)||iv(t)!==null;GD("production");const ose=zp&&ise(HD.FORCE_COLOR,["true","1","2"]),ase=ose||!_w("--no-colors")&&!GD("no-color")&&(!zp||process.stdout.isTTY)&&(!zp||_w("--color")||iv("COLORTERM")!==null||(iv("TERM")||"").includes("color")),cse=t=>new Uint8Array(t),lse=t=>{const e=cse(t.byteLength);return e.set(t),e};class use{constructor(e,n){this.left=e,this.right=n}}const ac=(t,e)=>new use(t,e);typeof DOMParser<"u"&&new DOMParser;const hse=t=>uie(t,(e,n)=>`${n}:${e};`).join(""),Kc=Symbol,WD=Kc(),jD=Kc(),fse=Kc(),dse=Kc(),pse=Kc(),$D=Kc(),mse=Kc(),iA=Kc(),gse=Kc(),_se=t=>{var i;t.length===1&&((i=t[0])==null?void 0:i.constructor)===Function&&(t=t[0]());const e=[],n=[];let r=0;for(;r0&&n.push(e.join(""));r{var o;t.length===1&&((o=t[0])==null?void 0:o.constructor)===Function&&(t=t[0]());const e=[],n=[],r=ko();let i=[],s=0;for(;s0||l.length>0?(e.push("%c"+a),n.push(l)):e.push(a)}else break}}for(s>0&&(i=n,i.unshift(e.join("")));s{console.log(...qD(t)),XD.forEach(e=>e.print(t))},Sse=(...t)=>{console.warn(...qD(t)),t.unshift(iA),XD.forEach(e=>e.print(t))},XD=Jf(),KD=t=>({[Symbol.iterator](){return this},next:t}),Ese=(t,e)=>KD(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),hS=(t,e)=>KD(()=>{const{done:n,value:r}=t.next();return{done:n,value:n?void 0:e(r)}});class sA{constructor(e,n){this.clock=e,this.len=n}}class Mm{constructor(){this.clients=new Map}}const YD=(t,e,n)=>e.clients.forEach((r,i)=>{const s=t.doc.store.clients.get(i);for(let o=0;o{let n=0,r=t.length-1;for(;n<=r;){const i=Fl((n+r)/2),s=t[i],o=s.clock;if(o<=e){if(e{const n=t.clients.get(e.client);return n!==void 0&&wse(n,e.clock)!==null},oA=t=>{t.clients.forEach(e=>{e.sort((i,s)=>i.clock-s.clock);let n,r;for(n=1,r=1;n=s.clock?i.len=_h(i.len,s.clock+s.len-i.clock):(r{const e=new Mm;for(let n=0;n{if(!e.clients.has(i)){const s=r.slice();for(let o=n+1;o{Kl(t.clients,e,()=>[]).push(new sA(n,r))},Tse=()=>new Mm,Ase=t=>{const e=Tse();return t.clients.forEach((n,r)=>{const i=[];for(let s=0;s0&&e.clients.set(r,i)}),e},vd=(t,e)=>{Ht(t.restEncoder,e.clients.size),Ul(e.clients.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{t.resetDsCurVal(),Ht(t.restEncoder,n);const i=r.length;Ht(t.restEncoder,i);for(let s=0;s{const e=new Mm,n=Gt(t.restDecoder);for(let r=0;r0){const o=Kl(e.clients,i,()=>[]);for(let a=0;a{const r=new Mm,i=Gt(t.restDecoder);for(let s=0;s0){const s=new th;return Ht(s.restEncoder,0),vd(s,r),s.toUint8Array()}return null},JD=BD;class Yc extends pie{constructor({guid:e=jie(),collectionid:n=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:a=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=JD(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new aU,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=VN(l=>{this.on("load",()=>{this.isLoaded=!0,l(this)})});const c=()=>VN(l=>{const u=h=>{(h===void 0||h===!0)&&(this.off("sync",u),l())};this.on("sync",u)});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;e!==null&&!this.shouldLoad&&Pn(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Ul(this.subdocs).map(e=>e.guid))}transact(e,n=null){return Pn(this,e,n)}get(e,n=cr){const r=Kl(this.share,e,()=>{const s=new n;return s._integrate(this,null),s}),i=r.constructor;if(n!==cr&&i!==n)if(i===cr){const s=new n;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(e,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,ba)}getText(e=""){return this.get(e,Fo)}getMap(e=""){return this.get(e,ka)}getXmlElement(e=""){return this.get(e,Pc)}getXmlFragment(e=""){return this.get(e,Ia)}toJSON(){const e={};return this.share.forEach((n,r)=>{e[r]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,Ul(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new Yc({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,Pn(e.parent.doc,r=>{const i=n.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class QD{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Gt(this.restDecoder)}readDsLen(){return Gt(this.restDecoder)}}class eU extends QD{readLeftID(){return an(Gt(this.restDecoder),Gt(this.restDecoder))}readRightID(){return an(Gt(this.restDecoder),Gt(this.restDecoder))}readClient(){return Gt(this.restDecoder)}readInfo(){return Qf(this.restDecoder)}readString(){return Nf(this.restDecoder)}readParentInfo(){return Gt(this.restDecoder)===1}readTypeRef(){return Gt(this.restDecoder)}readLen(){return Gt(this.restDecoder)}readAny(){return Bp(this.restDecoder)}readBuf(){return lse(Oi(this.restDecoder))}readJSON(){return JSON.parse(Nf(this.restDecoder))}readKey(){return Nf(this.restDecoder)}}class Mse{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Gt(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Gt(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class ed extends Mse{constructor(e){super(e),this.keys=[],Gt(e),this.keyClockDecoder=new uS(Oi(e)),this.clientDecoder=new __(Oi(e)),this.leftClockDecoder=new uS(Oi(e)),this.rightClockDecoder=new uS(Oi(e)),this.infoDecoder=new zN(Oi(e),Qf),this.stringDecoder=new Hie(Oi(e)),this.parentInfoDecoder=new zN(Oi(e),Qf),this.typeRefDecoder=new __(Oi(e)),this.lenDecoder=new __(Oi(e))}readLeftID(){return new kf(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new kf(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Bp(this.restDecoder)}readBuf(){return Oi(this.restDecoder)}readJSON(){return Bp(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e{r=_h(r,e[0].id.clock);const i=Uo(e,r);Ht(t.restEncoder,e.length-i),t.writeClient(n),Ht(t.restEncoder,r);const s=e[i];s.write(t,r-s.id.clock);for(let o=i+1;o{const r=new Map;n.forEach((i,s)=>{ii(e,s)>i&&r.set(s,i)}),Ry(e).forEach((i,s)=>{n.has(s)||r.set(s,0)}),Ht(t.restEncoder,r.size),Ul(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{Cse(t,e.clients.get(i),i,s)})},Rse=(t,e)=>{const n=ko(),r=Gt(t.restDecoder);for(let i=0;i{const r=[];let i=Ul(n.keys()).sort((m,g)=>m-g);if(i.length===0)return null;const s=()=>{if(i.length===0)return null;let m=n.get(i[i.length-1]);for(;m.refs.length===m.i;)if(i.pop(),i.length>0)m=n.get(i[i.length-1]);else return null;return m};let o=s();if(o===null)return null;const a=new aU,c=new Map,l=(m,g)=>{const v=c.get(m);(v==null||v>g)&&c.set(m,g)};let u=o.refs[o.i++];const h=new Map,p=()=>{for(const m of r){const g=m.id.client,v=n.get(g);v?(v.i--,a.clients.set(g,v.refs.slice(v.i)),n.delete(g),v.i=0,v.refs=[]):a.clients.set(g,[m]),i=i.filter(y=>y!==g)}r.length=0};for(;;){if(u.constructor!==Qs){const g=Kl(h,u.id.client,()=>ii(e,u.id.client))-u.id.clock;if(g<0)r.push(u),l(u.id.client,u.id.clock-1),p();else{const v=u.getMissing(t,e);if(v!==null){r.push(u);const y=n.get(v)||{refs:[],i:0};if(y.refs.length===y.i)l(v,ii(e,v)),p();else{u=y.refs[y.i++];continue}}else(g===0||g0)u=r.pop();else if(o!==null&&o.i0){const m=new th;return cA(m,a,new Map),Ht(m.restEncoder,0),{missing:c,update:m.toUint8Array()}}return null},kse=(t,e)=>cA(t,e.doc.store,e.beforeState),Ise=(t,e,n,r=new ed(t))=>Pn(e,i=>{i.local=!1;let s=!1;const o=i.doc,a=o.store,c=Rse(r,o),l=Nse(i,a,c),u=a.pendingStructs;if(u){for(const[p,m]of u.missing)if(mm)&&u.missing.set(p,m)}u.update=ov([u.update,l.update])}}else a.pendingStructs=l;const h=WN(r,i,a);if(a.pendingDs){const p=new ed(vh(a.pendingDs));Gt(p.restDecoder);const m=WN(p,i,a);h&&m?a.pendingDs=ov([h,m]):a.pendingDs=h||m}else a.pendingDs=h;if(s){const p=a.pendingStructs.update;a.pendingStructs=null,rU(i.doc,p)}},n,!1),rU=(t,e,n,r=ed)=>{const i=vh(e);Ise(i,t,n,new r(i))},Ose=(t,e,n)=>rU(t,e,n,eU),Lse=(t,e,n=new Map)=>{cA(t,e.store,n),vd(t,Ase(e.store))},Pse=(t,e=new Uint8Array([0]),n=new th)=>{const r=iU(e);Lse(n,t,r);const i=[n.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(Zse(t.store.pendingStructs.update,e)),i.length>1){if(n.constructor===Cm)return Kse(i.map((s,o)=>o===0?s:Qse(s)));if(n.constructor===th)return ov(i)}return i[0]},Dse=(t,e)=>Pse(t,e,new Cm),Use=t=>{const e=new Map,n=Gt(t.restDecoder);for(let r=0;rUse(new QD(vh(t))),sU=(t,e)=>(Ht(t.restEncoder,e.size),Ul(e.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{Ht(t.restEncoder,n),Ht(t.restEncoder,r)}),t),Fse=(t,e)=>sU(t,Ry(e.store)),Bse=(t,e=new nU)=>(t instanceof Map?sU(e,t):Fse(e,t),e.toUint8Array()),zse=t=>Bse(t,new tU);class Vse{constructor(){this.l=[]}}const jN=()=>new Vse,$N=(t,e)=>t.l.push(e),qN=(t,e)=>{const n=t.l,r=n.length;t.l=n.filter(i=>e!==i),r===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},oU=(t,e,n)=>rA(t.l,[e,n]);class kf{constructor(e,n){this.client=e,this.clock=n}}const M0=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,an=(t,e)=>new kf(t,e),Hse=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw Na()},lf=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!ZD(e.ds,t.id),vw=(t,e)=>{const n=Kl(t.meta,vw,Jf),r=t.doc.store;n.has(e)||(e.sv.forEach((i,s)=>{i{}),n.add(e))};class aU{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Ry=t=>{const e=new Map;return t.clients.forEach((n,r)=>{const i=n[n.length-1];e.set(r,i.id.clock+i.length)}),e},ii=(t,e)=>{const n=t.clients.get(e);if(n===void 0)return 0;const r=n[n.length-1];return r.id.clock+r.length},cU=(t,e)=>{let n=t.clients.get(e.id.client);if(n===void 0)n=[],t.clients.set(e.id.client,n);else{const r=n[n.length-1];if(r.id.clock+r.length!==e.id.clock)throw Na()}n.push(e)},Uo=(t,e)=>{let n=0,r=t.length-1,i=t[r],s=i.id.clock;if(s===e)return r;let o=Fl(e/(s+i.length-1)*r);for(;n<=r;){if(i=t[o],s=i.id.clock,s<=e){if(e{const n=t.clients.get(e.client);return n[Uo(n,e.clock)]},fS=Gse,yw=(t,e,n)=>{const r=Uo(e,n),i=e[r];return i.id.clock{const n=t.doc.store.clients.get(e.client);return n[yw(t,n,e.clock)]},XN=(t,e,n)=>{const r=e.clients.get(n.client),i=Uo(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==ks&&r.splice(i+1,0,uv(t,s,n.clock-s.id.clock+1)),s},Wse=(t,e,n)=>{const r=t.clients.get(e.id.client);r[Uo(r,e.id.clock)]=n},lU=(t,e,n,r,i)=>{if(r===0)return;const s=n+r;let o=yw(t,e,n),a;do a=e[o++],se.deleteSet.clients.size===0&&!hie(e.afterState,(n,r)=>e.beforeState.get(r)!==n)?!1:(oA(e.deleteSet),kse(t,e),vd(t,e.deleteSet),!0),YN=(t,e,n)=>{const r=e._item;(r===null||r.id.clock<(t.beforeState.get(r.id.client)||0)&&!r.deleted)&&Kl(t.changed,e,Jf).add(n)},v_=(t,e)=>{let n=t[e],r=t[e-1],i=e;for(;i>0;n=r,r=t[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof Fr&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}const s=e-i;return s&&t.splice(e+1-s,s),s},$se=(t,e,n)=>{for(const[r,i]of t.clients.entries()){const s=e.clients.get(r);for(let o=i.length-1;o>=0;o--){const a=i[o],c=a.clock+a.len;for(let l=Uo(s,a.clock),u=s[l];l{t.clients.forEach((n,r)=>{const i=e.clients.get(r);for(let s=n.length-1;s>=0;s--){const o=n[s],a=LD(i.length-1,1+Uo(i,o.clock+o.len-1));for(let c=a,l=i[c];c>0&&l.id.clock>=o.clock;l=i[c])c-=1+v_(i,c)}})},uU=(t,e)=>{if(ea.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(n,c)})),a.push(()=>{n.changedParentTypes.forEach((c,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=l,u._path=null}),c.sort((u,h)=>u.path.length-h.path.length),oU(l._dEH,c,n))})}),a.push(()=>r.emit("afterTransaction",[n,r])),rA(a,[]),n._needFormattingCleanup&&doe(n)}finally{r.gc&&$se(s,i,r.gcFilter),qse(s,i),n.afterState.forEach((u,h)=>{const p=n.beforeState.get(h)||0;if(p!==u){const m=i.clients.get(h),g=_h(Uo(m,p),1);for(let v=m.length-1;v>=g;)v-=1+v_(m,v)}});for(let u=o.length-1;u>=0;u--){const{client:h,clock:p}=o[u].id,m=i.clients.get(h),g=Uo(m,p);g+11||g>0&&v_(m,g)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(xse(iA,WD,"[yjs] ",jD,$D,"Changed the client-id because another client seems to be using it."),r.clientID=JD()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const u=new Cm;KN(u,n)&&r.emit("update",[u.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const u=new th;KN(u,n)&&r.emit("updateV2",[u.toUint8Array(),n.origin,r,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:l}=n;(a.size>0||l.size>0||c.size>0)&&(a.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),l.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:c,added:a,removed:l},r,n]),l.forEach(u=>u.destroy())),t.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,t])):uU(t,e+1)}}},Pn=(t,e,n=null,r=!0)=>{const i=t._transactionCleanups;let s=!1,o=null;t._transaction===null&&(s=!0,t._transaction=new jse(t,n,r),i.push(t._transaction),i.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{o=e(t._transaction)}finally{if(s){const a=t._transaction===i[0];t._transaction=null,a&&uU(i,0)}}return o};function*Xse(t){const e=Gt(t.restDecoder);for(let n=0;nov(t,eU,Cm),Yse=(t,e)=>{if(t.constructor===ks){const{client:n,clock:r}=t.id;return new ks(an(n,r+e),t.length-e)}else if(t.constructor===Qs){const{client:n,clock:r}=t.id;return new Qs(an(n,r+e),t.length-e)}else{const n=t,{client:r,clock:i}=n.id;return new Fr(an(r,i+e),null,an(r,i+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},ov=(t,e=ed,n=th)=>{if(t.length===1)return t[0];const r=t.map(u=>new e(vh(u)));let i=r.map(u=>new lA(u,!0)),s=null;const o=new n,a=new uA(o);for(;i=i.filter(p=>p.curr!==null),i.sort((p,m)=>{if(p.curr.id.client===m.curr.id.client){const g=p.curr.id.clock-m.curr.id.clock;return g===0?p.curr.constructor===m.curr.constructor?0:p.curr.constructor===Qs?1:-1:g}else return m.curr.id.client-p.curr.id.client}),i.length!==0;){const u=i[0],h=u.curr.id.client;if(s!==null){let p=u.curr,m=!1;for(;p!==null&&p.id.clock+p.length<=s.struct.id.clock+s.struct.length&&p.id.client>=s.struct.id.client;)p=u.next(),m=!0;if(p===null||p.id.client!==h||m&&p.id.clock>s.struct.id.clock+s.struct.length)continue;if(h!==s.struct.id.client)Sl(a,s.struct,s.offset),s={struct:p,offset:0},u.next();else if(s.struct.id.clock+s.struct.length0&&(s.struct.constructor===Qs?s.struct.length-=g:p=Yse(p,g)),s.struct.mergeWith(p)||(Sl(a,s.struct,s.offset),s={struct:p,offset:0},u.next())}}else s={struct:u.curr,offset:0},u.next();for(let p=u.curr;p!==null&&p.id.client===h&&p.id.clock===s.struct.id.clock+s.struct.length&&p.constructor!==Qs;p=u.next())Sl(a,s.struct,s.offset),s={struct:p,offset:0}}s!==null&&(Sl(a,s.struct,s.offset),s=null),hA(a);const c=r.map(u=>aA(u)),l=bse(c);return vd(o,l),o.toUint8Array()},Zse=(t,e,n=ed,r=th)=>{const i=iU(e),s=new r,o=new uA(s),a=new n(vh(t)),c=new lA(a,!1);for(;c.curr;){const u=c.curr,h=u.id.client,p=i.get(h)||0;if(c.curr.constructor===Qs){c.next();continue}if(u.id.clock+u.length>p)for(Sl(o,u,_h(p-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Sl(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=p;)c.next()}hA(o);const l=aA(a);return vd(s,l),s.toUint8Array()},hU=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Mo(t.encoder.restEncoder)}),t.encoder.restEncoder=Cl(),t.written=0)},Sl=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&hU(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),Ht(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},hA=t=>{hU(t);const e=t.encoder.restEncoder;Ht(e,t.clientStructs.length);for(let n=0;n{const i=new n(vh(t)),s=new lA(i,!1),o=new r,a=new uA(o);for(let l=s.curr;l!==null;l=s.next())Sl(a,e(l),0);hA(a);const c=aA(i);return vd(o,c),o.toUint8Array()},Qse=t=>Jse(t,rse,ed,Cm),ZN="You must not compute changes after the event-handler fired.";class Ny{constructor(e,n){this.target=e,this.currentTarget=e,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=eoe(this.currentTarget,this.target))}deletes(e){return ZD(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Bl(ZN);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(i=>{if(i!==null){const s=n._map.get(i);let o,a;if(this.adds(s)){let c=s.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(s))if(c!==null&&this.deletes(c))o="delete",a=oS(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",a=oS(c.content.getContent())):(o="add",a=void 0)}else if(this.deletes(s))o="delete",a=oS(s.content.getContent());else return;e.set(i,{action:o,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Bl(ZN);const n=this.target,r=Jf(),i=Jf(),s=[];if(e={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(n).has(null)){let a=null;const c=()=>{a&&s.push(a)};for(let l=n._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=l.length,i.add(l)):this.adds(l)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(l.content.getContent()),r.add(l)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=l.length);a!==null&&a.retain===void 0&&c()}this._changes=e}return e}}const eoe=(t,e)=>{const n=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)n.unshift(e._item.parentSub);else{let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;n.unshift(r)}e=e._item.parent}return n},wi=()=>{Sse("Invalid access: Add Yjs type to a document before reading data.")},fU=80;let fA=0;class toe{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=fA++}}const noe=t=>{t.timestamp=fA++},dU=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=fA++},roe=(t,e,n)=>{if(t.length>=fU){const r=t.reduce((i,s)=>i.timestamp{if(t._start===null||e===0||t._searchMarker===null)return null;const n=t._searchMarker.length===0?null:t._searchMarker.reduce((s,o)=>m_(e-s.index)e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&m_(n.index-i){for(let r=t.length-1;r>=0;r--){const i=t[r];if(n>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){t.splice(r,1);continue}i.p=s,s.marker=!0}(e0&&e===i.index)&&(i.index=_h(e,i.index+n))}},Iy=(t,e,n)=>{const r=t,i=e.changedParentTypes;for(;Kl(i,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;oU(r._eH,n,e)};class cr{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=jN(),this._dEH=jN(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw wa()}clone(){throw wa()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,n){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){$N(this._eH,e)}observeDeep(e){$N(this._dEH,e)}unobserve(e){qN(this._eH,e)}unobserveDeep(e){qN(this._dEH,e)}toJSON(){}}const pU=(t,e,n)=>{t.doc??wi(),e<0&&(e=t._length+e),n<0&&(n=t._length+n);let r=n-e;const i=[];let s=t._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){const o=s.content.getContent();if(o.length<=e)e-=o.length;else{for(let a=e;a0;a++)i.push(o[a]),r--;e=0}}s=s.right}return i},mU=t=>{t.doc??wi();const e=[];let n=t._start;for(;n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let i=0;i{let n=0,r=t._start;for(t.doc??wi();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let s=0;s{const n=[];return Hp(t,(r,i)=>{n.push(e(r,i,t))}),n},ioe=t=>{let e=t._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};n=e.content.getContent(),r=0,e=e.right}const i=n[r++];return n.length<=r&&(n=null),{done:!1,value:i}}}},_U=(t,e)=>{t.doc??wi();const n=ky(t,e);let r=t._start;for(n!==null&&(r=n.p,e-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e{let i=n;const s=t.doc,o=s.clientID,a=s.store,c=n===null?e._start:n.right;let l=[];const u=()=>{l.length>0&&(i=new Fr(an(o,ii(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new rh(l)),i.integrate(t,0),l=[])};r.forEach(h=>{if(h===null)l.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:i=new Fr(an(o,ii(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new Rm(new Uint8Array(h))),i.integrate(t,0);break;case Yc:i=new Fr(an(o,ii(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new Nm(h)),i.integrate(t,0);break;default:if(h instanceof cr)i=new Fr(an(o,ii(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new Zc(h)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},vU=()=>Bl("Length exceeded!"),yU=(t,e,n,r)=>{if(n>e._length)throw vU();if(n===0)return e._searchMarker&&Vp(e._searchMarker,n,r.length),av(t,e,null,r);const i=n,s=ky(e,n);let o=e._start;for(s!==null&&(o=s.p,n-=s.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let i=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return av(t,e,i,n)},xU=(t,e,n,r)=>{if(r===0)return;const i=n,s=r,o=ky(e,n);let a=e._start;for(o!==null&&(a=o.p,n-=o.index);a!==null&&n>0;a=a.right)!a.deleted&&a.countable&&(n0&&a!==null;)a.deleted||(r0)throw vU();e._searchMarker&&Vp(e._searchMarker,i,-s+r)},cv=(t,e,n)=>{const r=e._map.get(n);r!==void 0&&r.delete(t)},dA=(t,e,n,r)=>{const i=e._map.get(n)||null,s=t.doc,o=s.clientID;let a;if(r==null)a=new rh([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:a=new rh([r]);break;case Uint8Array:a=new Rm(r);break;case Yc:a=new Nm(r);break;default:if(r instanceof cr)a=new Zc(r);else throw new Error("Unexpected content type")}new Fr(an(o,ii(s.store,o)),i,i&&i.lastId,null,null,e,n,a).integrate(t,0)},pA=(t,e)=>{t.doc??wi();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},SU=t=>{const e={};return t.doc??wi(),t._map.forEach((n,r)=>{n.deleted||(e[r]=n.content.getContent()[n.length-1])}),e},EU=(t,e)=>{t.doc??wi();const n=t._map.get(e);return n!==void 0&&!n.deleted},ooe=(t,e)=>{const n={};return t._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&lf(s,e)&&(n[i]=s.content.getContent()[s.length-1])}),n},C0=t=>(t.doc??wi(),Ese(t._map.entries(),e=>!e[1].deleted));class aoe extends Ny{}class ba extends cr{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new ba;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ba}clone(){const e=new ba;return e.insert(0,this.toArray().map(n=>n instanceof cr?n.clone():n)),e}get length(){return this.doc??wi(),this._length}_callObserver(e,n){super._callObserver(e,n),Iy(this,e,new aoe(this,e))}insert(e,n){this.doc!==null?Pn(this.doc,r=>{yU(r,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?Pn(this.doc,n=>{soe(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?Pn(this.doc,r=>{xU(r,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return _U(this,e)}toArray(){return mU(this)}slice(e=0,n=this.length){return pU(this,e,n)}toJSON(){return this.map(e=>e instanceof cr?e.toJSON():e)}map(e){return gU(this,e)}forEach(e){Hp(this,e)}[Symbol.iterator](){return ioe(this)}_write(e){e.writeTypeRef(Ioe)}}const coe=t=>new ba;class loe extends Ny{constructor(e,n,r){super(e,n),this.keysChanged=r}}class ka extends cr{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,n){super._integrate(e,n),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new ka}clone(){const e=new ka;return this.forEach((n,r)=>{e.set(r,n instanceof cr?n.clone():n)}),e}_callObserver(e,n){Iy(this,e,new loe(this,e,n))}toJSON(){this.doc??wi();const e={};return this._map.forEach((n,r)=>{if(!n.deleted){const i=n.content.getContent()[n.length-1];e[r]=i instanceof cr?i.toJSON():i}}),e}get size(){return[...C0(this)].length}keys(){return hS(C0(this),e=>e[0])}values(){return hS(C0(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return hS(C0(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??wi(),this._map.forEach((n,r)=>{n.deleted||e(n.content.getContent()[n.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?Pn(this.doc,n=>{cv(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?Pn(this.doc,r=>{dA(r,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return pA(this,e)}has(e){return EU(this,e)}clear(){this.doc!==null?Pn(this.doc,e=>{this.forEach(function(n,r,i){cv(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Ooe)}}const uoe=t=>new ka,wl=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&tse(t,e);class xw{constructor(e,n,r,i){this.left=e,this.right=n,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Na(),this.right.content.constructor){case Wr:this.right.deleted||yd(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const JN=(t,e,n)=>{for(;e.right!==null&&n>0;){switch(e.right.content.constructor){case Wr:e.right.deleted||yd(e.currentAttributes,e.right.content);break;default:e.right.deleted||(n{const i=new Map,s=r?ky(e,n):null;if(s){const o=new xw(s.p.left,s.p,s.index,i);return JN(t,o,n-s.index)}else{const o=new xw(null,e._start,0,i);return JN(t,o,n)}},wU=(t,e,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Wr&&wl(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=t.doc,s=i.clientID;r.forEach((o,a)=>{const c=n.left,l=n.right,u=new Fr(an(s,ii(i.store,s)),c,c&&c.lastId,l,l&&l.id,e,null,new Wr(a,o));u.integrate(t,0),n.right=u,n.forward()})},yd=(t,e)=>{const{key:n,value:r}=e;r===null?t.delete(n):t.set(n,r)},bU=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Wr&&wl(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},TU=(t,e,n,r)=>{const i=t.doc,s=i.clientID,o=new Map;for(const a in r){const c=r[a],l=n.currentAttributes.get(a)??null;if(!wl(l,c)){o.set(a,l);const{left:u,right:h}=n;n.right=new Fr(an(s,ii(i.store,s)),u,u&&u.lastId,h,h&&h.id,e,null,new Wr(a,c)),n.right.integrate(t,0),n.forward()}}return o},dS=(t,e,n,r,i)=>{n.currentAttributes.forEach((p,m)=>{i[m]===void 0&&(i[m]=null)});const s=t.doc,o=s.clientID;bU(n,i);const a=TU(t,e,n,i),c=r.constructor===String?new Oa(r):r instanceof cr?new Zc(r):new yh(r);let{left:l,right:u,index:h}=n;e._searchMarker&&Vp(e._searchMarker,n.index,c.getLength()),u=new Fr(an(o,ii(s.store,o)),l,l&&l.lastId,u,u&&u.id,e,null,c),u.integrate(t,0),n.right=u,n.index=h,n.forward(),wU(t,e,n,a)},QN=(t,e,n,r,i)=>{const s=t.doc,o=s.clientID;bU(n,i);const a=TU(t,e,n,i);e:for(;n.right!==null&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Wr));){if(!n.right.deleted)switch(n.right.content.constructor){case Wr:{const{key:c,value:l}=n.right.content,u=i[c];if(u!==void 0){if(wl(u,l))a.delete(c);else{if(r===0)break e;a.set(c,l)}n.right.delete(t)}else n.currentAttributes.set(c,l);break}default:r0){let c="";for(;r>0;r--)c+=` -`;n.right=new Fr(an(o,ii(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Oa(c)),n.right.integrate(t,0),n.forward()}wU(t,e,n,a)},AU=(t,e,n,r,i)=>{let s=e;const o=ko();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===Wr){const l=s.content;o.set(l.key,l)}s=s.right}let a=0,c=!1;for(;e!==s;){if(n===e&&(c=!0),!e.deleted){const l=e.content;switch(l.constructor){case Wr:{const{key:u,value:h}=l,p=r.get(u)??null;(o.get(u)!==l||p===h)&&(e.delete(t),a++,!c&&(i.get(u)??null)===h&&p!==h&&(p===null?i.delete(u):i.set(u,p))),!c&&!e.deleted&&yd(i,l);break}}}e=e.right}return a},hoe=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const n=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===Wr){const r=e.content.key;n.has(r)?e.delete(t):n.add(r)}e=e.left}},foe=t=>{let e=0;return Pn(t.doc,n=>{let r=t._start,i=t._start,s=ko();const o=dw(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Wr:yd(o,i.content);break;default:e+=AU(n,r,i,s,o),s=dw(o),r=i;break}i=i.right}}),e},doe=t=>{const e=new Set,n=t.doc;for(const[r,i]of t.afterState.entries()){const s=t.beforeState.get(r)||0;i!==s&&lU(t,n.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===Wr&&o.constructor!==ks&&e.add(o.parent)})}Pn(n,r=>{YD(t,t.deleteSet,i=>{if(i instanceof ks||!i.parent._hasFormatting||e.has(i.parent))return;const s=i.parent;i.content.constructor===Wr?e.add(s):hoe(r,i)});for(const i of e)foe(i)})},ek=(t,e,n)=>{const r=n,i=dw(e.currentAttributes),s=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case Zc:case yh:case Oa:n{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,n=[];Pn(e,r=>{const i=new Map,s=new Map;let o=this.target._start,a=null;const c={};let l="",u=0,h=0;const p=()=>{if(a!==null){let m=null;switch(a){case"delete":h>0&&(m={delete:h}),h=0;break;case"insert":(typeof l=="object"||l.length>0)&&(m={insert:l},i.size>0&&(m.attributes={},i.forEach((g,v)=>{g!==null&&(m.attributes[v]=g)}))),l="";break;case"retain":u>0&&(m={retain:u},Jie(c)||(m.attributes=Kie({},c))),u=0;break}m&&n.push(m),a=null}};for(;o!==null;){switch(o.content.constructor){case Zc:case yh:this.adds(o)?this.deletes(o)||(p(),a="insert",l=o.content.getContent()[0],p()):this.deletes(o)?(a!=="delete"&&(p(),a="delete"),h+=1):o.deleted||(a!=="retain"&&(p(),a="retain"),u+=1);break;case Oa:this.adds(o)?this.deletes(o)||(a!=="insert"&&(p(),a="insert"),l+=o.content.str):this.deletes(o)?(a!=="delete"&&(p(),a="delete"),h+=o.length):o.deleted||(a!=="retain"&&(p(),a="retain"),u+=o.length);break;case Wr:{const{key:m,value:g}=o.content;if(this.adds(o)){if(!this.deletes(o)){const v=i.get(m)??null;wl(v,g)?g!==null&&o.delete(r):(a==="retain"&&p(),wl(g,s.get(m)??null)?delete c[m]:c[m]=g)}}else if(this.deletes(o)){s.set(m,g);const v=i.get(m)??null;wl(v,g)||(a==="retain"&&p(),c[m]=v)}else if(!o.deleted){s.set(m,g);const v=c[m];v!==void 0&&(wl(v,g)?v!==null&&o.delete(r):(a==="retain"&&p(),g===null?delete c[m]:c[m]=g))}o.deleted||(a==="insert"&&p(),yd(i,o.content));break}}o=o.right}for(p();n.length>0;){const m=n[n.length-1];if(m.retain!==void 0&&m.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Fo extends cr{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??wi(),this._length}_integrate(e,n){super._integrate(e,n);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new Fo}clone(){const e=new Fo;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const r=new poe(this,e,n);Iy(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??wi();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Oa&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?Pn(this.doc,r=>{const i=new xw(null,this._start,0,new Map);for(let s=0;s0)&&dS(r,this,i,a,o.attributes||{})}else o.retain!==void 0?QN(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&ek(r,i,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,r){this.doc??wi();const i=[],s=new Map,o=this.doc;let a="",c=this._start;function l(){if(a.length>0){const h={};let p=!1;s.forEach((g,v)=>{p=!0,h[v]=g});const m={insert:a};p&&(m.attributes=h),i.push(m),a=""}}const u=()=>{for(;c!==null;){if(lf(c,e)||n!==void 0&&lf(c,n))switch(c.content.constructor){case Oa:{const h=s.get("ychange");e!==void 0&&!lf(c,e)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(l(),s.set("ychange",r?r("removed",c.id):{type:"removed"})):n!==void 0&&!lf(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(l(),s.set("ychange",r?r("added",c.id):{type:"added"})):h!==void 0&&(l(),s.delete("ychange")),a+=c.content.str;break}case Zc:case yh:{l();const h={insert:c.content.getContent()[0]};if(s.size>0){const p={};h.attributes=p,s.forEach((m,g)=>{p[g]=m})}i.push(h);break}case Wr:lf(c,e)&&(l(),yd(s,c.content));break}c=c.right}l()};return e||n?Pn(o,h=>{e&&vw(h,e),n&&vw(h,n),u()},"cleanup"):u(),i}insert(e,n,r){if(n.length<=0)return;const i=this.doc;i!==null?Pn(i,s=>{const o=R0(s,this,e,!r);r||(r={},o.currentAttributes.forEach((a,c)=>{r[c]=a})),dS(s,this,o,n,r)}):this._pending.push(()=>this.insert(e,n,r))}insertEmbed(e,n,r){const i=this.doc;i!==null?Pn(i,s=>{const o=R0(s,this,e,!r);dS(s,this,o,n,r||{})}):this._pending.push(()=>this.insertEmbed(e,n,r||{}))}delete(e,n){if(n===0)return;const r=this.doc;r!==null?Pn(r,i=>{ek(i,R0(i,this,e,!0),n)}):this._pending.push(()=>this.delete(e,n))}format(e,n,r){if(n===0)return;const i=this.doc;i!==null?Pn(i,s=>{const o=R0(s,this,e,!1);o.right!==null&&QN(s,this,o,n,r)}):this._pending.push(()=>this.format(e,n,r))}removeAttribute(e){this.doc!==null?Pn(this.doc,n=>{cv(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?Pn(this.doc,r=>{dA(r,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return pA(this,e)}getAttributes(){return SU(this)}_write(e){e.writeTypeRef(Loe)}}const moe=t=>new Fo;class pS{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??wi()}[Symbol.iterator](){return this}next(){let e=this._currentNode,n=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(n)))do if(n=e.content.type,!e.deleted&&(n.constructor===Pc||n.constructor===Ia)&&n._start!==null)e=n._start;else for(;e!==null;)if(e.right!==null){e=e.right;break}else e.parent===this._root?e=null:e=e.parent._item;while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class Ia extends cr{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ia}clone(){const e=new Ia;return e.insert(0,this.toArray().map(n=>n instanceof cr?n.clone():n)),e}get length(){return this.doc??wi(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new pS(this,e)}querySelector(e){e=e.toUpperCase();const r=new pS(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),Ul(new pS(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){Iy(this,e,new voe(this,n,e))}toString(){return gU(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,n={},r){const i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),Hp(this,s=>{i.insertBefore(s.toDOM(e,n,r),null)}),i}insert(e,n){this.doc!==null?Pn(this.doc,r=>{yU(r,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)Pn(this.doc,r=>{const i=e&&e instanceof cr?e._item:e;av(r,this,i,n)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(s=>s===e)+1;if(i===0&&e!==null)throw Bl("Reference item not found");r.splice(i,0,...n)}}delete(e,n=1){this.doc!==null?Pn(this.doc,r=>{xU(r,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return mU(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return _U(this,e)}slice(e=0,n=this.length){return pU(this,e,n)}forEach(e){Hp(this,e)}_write(e){e.writeTypeRef(Doe)}}const goe=t=>new Ia;class Pc extends Ia{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,n){super._integrate(e,n),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new Pc(this.nodeName)}clone(){const e=new Pc(this.nodeName),n=this.getAttributes();return Zie(n,(r,i)=>{typeof r=="string"&&e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof cr?r.clone():r)),e}toString(){const e=this.getAttributes(),n=[],r=[];for(const a in e)r.push(a);r.sort();const i=r.length;for(let a=0;a0?" "+n.join(" "):"";return`<${s}${o}>${super.toString()}`}removeAttribute(e){this.doc!==null?Pn(this.doc,n=>{cv(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?Pn(this.doc,r=>{dA(r,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return pA(this,e)}hasAttribute(e){return EU(this,e)}getAttributes(e){return e?ooe(this,e):SU(this)}toDOM(e=document,n={},r){const i=e.createElement(this.nodeName),s=this.getAttributes();for(const o in s){const a=s[o];typeof a=="string"&&i.setAttribute(o,a)}return Hp(this,o=>{i.appendChild(o.toDOM(e,n,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(Poe),e.writeKey(this.nodeName)}}const _oe=t=>new Pc(t.readKey());class voe extends Ny{constructor(e,n,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class td extends ka{constructor(e){super(),this.hookName=e}_copy(){return new td(this.hookName)}clone(){const e=new td(this.hookName);return this.forEach((n,r)=>{e.set(r,n)}),e}toDOM(e=document,n={},r){const i=n[this.hookName];let s;return i!==void 0?s=i.createDom(this):s=document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(s,this),s}_write(e){e.writeTypeRef(Uoe),e.writeKey(this.hookName)}}const yoe=t=>new td(t.readKey());class nh extends Fo{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new nh}clone(){const e=new nh;return e.applyDelta(this.toDelta()),e}toDOM(e=document,n,r){const i=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const n=[];for(const i in e.attributes){const s=[];for(const o in e.attributes[i])s.push({key:o,value:e.attributes[i][o]});s.sort((o,a)=>o.keyi.nodeName=0;i--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Foe)}}const xoe=t=>new nh;class mA{constructor(e,n){this.id=e,this.length=n}get deleted(){throw wa()}mergeWith(e){return!1}write(e,n,r){throw wa()}integrate(e,n){throw wa()}}const Soe=0;class ks extends mA{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){n>0&&(this.id.clock+=n,this.length-=n),cU(e.doc.store,this)}write(e,n){e.writeInfo(Soe),e.writeLen(this.length-n)}getMissing(e,n){return null}}class Rm{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Rm(this.content)}splice(e){throw wa()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const Eoe=t=>new Rm(t.readBuf());class Gp{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Gp(this.len)}splice(e){const n=new Gp(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){sv(e.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(e){}gc(e){}write(e,n){e.writeLen(this.len-n)}getRef(){return 1}}const woe=t=>new Gp(t.readLen()),MU=(t,e)=>new Yc({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Nm{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const n={};this.opts=n,e.gc||(n.gc=!1),e.autoLoad&&(n.autoLoad=!0),e.meta!==null&&(n.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Nm(MU(this.doc.guid,this.opts))}splice(e){throw wa()}mergeWith(e){return!1}integrate(e,n){this.doc._item=n,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,n){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const boe=t=>new Nm(MU(t.readString(),t.readAny()));class yh{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new yh(this.embed)}splice(e){throw wa()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const Toe=t=>new yh(t.readJSON());class Wr{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Wr(this.key,this.value)}splice(e){throw wa()}mergeWith(e){return!1}integrate(e,n){const r=n.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,n){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const Aoe=t=>new Wr(t.readKey(),t.readJSON());class lv{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new lv(this.arr)}splice(e){const n=new lv(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const r=this.arr.length;e.writeLen(r-n);for(let i=n;i{const e=t.readLen(),n=[];for(let r=0;r{const e=t.readLen(),n=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const Noe=t=>new Oa(t.readString()),koe=[coe,uoe,moe,_oe,goe,yoe,xoe],Ioe=0,Ooe=1,Loe=2,Poe=3,Doe=4,Uoe=5,Foe=6;class Zc{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Zc(this.type._copy())}splice(e){throw wa()}mergeWith(e){return!1}integrate(e,n){this.type._integrate(e.doc,n)}delete(e){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.delete(e),n=n.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let n=this.type._start;for(;n!==null;)n.gc(e,!0),n=n.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,n){this.type._write(e)}getRef(){return 7}}const Boe=t=>new Zc(koe[t.readTypeRef()](t)),uv=(t,e,n)=>{const{client:r,clock:i}=e.id,s=new Fr(an(r,i+n),e,an(r,i+n-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(n));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=an(e.redone.client,e.redone.clock+n)),e.right=s,s.right!==null&&(s.right.left=s),t._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=n,s};class Fr extends mA{constructor(e,n,r,i,s,o,a,c){super(e,c.getLength()),this.origin=r,this.left=n,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?LN:0}set marker(e){(this.info&cS)>0!==e&&(this.info^=cS)}get marker(){return(this.info&cS)>0}get keep(){return(this.info&ON)>0}set keep(e){this.keep!==e&&(this.info^=ON)}get countable(){return(this.info&LN)>0}get deleted(){return(this.info&aS)>0}set deleted(e){this.deleted!==e&&(this.info^=aS)}markDeleted(){this.info|=aS}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=ii(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=ii(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===kf&&this.id.client!==this.parent.client&&this.parent.clock>=ii(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=XN(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=zl(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ks||this.right&&this.right.constructor===ks)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Fr&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===Fr&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===kf){const r=fS(n,this.parent);r.constructor===ks?this.parent=null:this.parent=r.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=XN(e,e.doc.store,an(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),M0(this.origin,i.origin)){if(i.id.client{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),sv(e.deleteSet,this.id.client,this.id.clock,this.length),YN(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw Na();this.content.gc(e),n?Wse(e,this,new ks(this.id,this.length)):this.content=new Gp(this.length)}write(e,n){const r=n>0?an(this.id.client,this.id.clock+n-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&Ay|(r===null?0:Ds)|(i===null?0:bc)|(s===null?0:Dp);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const a=this.parent;if(a._item!==void 0){const c=a._item;if(c===null){const l=Hse(a);e.writeParentInfo(!0),e.writeString(l)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else a.constructor===String?(e.writeParentInfo(!0),e.writeString(a)):a.constructor===kf?(e.writeParentInfo(!1),e.writeLeftID(a)):Na();s!==null&&e.writeString(s)}this.content.write(e,n)}}const CU=(t,e)=>zoe[e&Ay](t),zoe=[()=>{Na()},woe,Moe,Eoe,Noe,Toe,Aoe,Boe,Roe,boe,()=>{Na()}],Voe=10;class Qs extends mA{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){Na()}write(e,n){e.writeInfo(Voe),Ht(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const RU=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},NU="__ $YJS$ __";RU[NU]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");RU[NU]=!0;let Sw,Ew,Hoe=t=>t();function Goe(t,e){if(Ew)return Ew(t,e);Hoe(t)}function ih(t,e,n){if(Sw)return Sw.apply(null,arguments);throw new Error("observable implementation not provided. Call enableReactiveBindings, enableVueBindings or enableMobxBindings.")}function Woe(t){Sw=function(e,n,r){const i=t.createAtom(e);return n&&n(),i},Ew=(e,n)=>t.reaction(e,n,{fireImmediately:!1})}const tk=new WeakSet;function joe(t){if(tk.has(t))return t;tk.add(t);let e;const n=new Map;function r(){if(!e){const h=p=>{(p.changes.added.size||p.changes.deleted.size||p.changes.keys.size||p.changes.delta.length)&&e.reportChanged()};e=ih("map",()=>{t.observe(h)},()=>{t.unobserve(h)})}e.reportObserved(t._implicitObserver)}function i(h){let p=n.get(h);if(!p){const m=g=>{p.reportChanged()};p=ih(h+"",()=>{t.observe(m)},()=>{t.unobserve(m)}),n.set(h,p)}p.reportObserved(t._implicitObserver)}const s=t.get;t.get=function(h){if(typeof h!="number")throw new Error("unexpected");return i(h),Reflect.apply(s,this,arguments)};function o(h){const p=t[h];t[h]=function(){return r(),Reflect.apply(p,this,arguments)}}function a(h){let p=t,m=Object.getOwnPropertyDescriptor(p,h);if(m||(p=Object.getPrototypeOf(p),m=Object.getOwnPropertyDescriptor(p,h)),m||(p=Object.getPrototypeOf(p),m=Object.getOwnPropertyDescriptor(p,h)),!m)throw new Error("property not found");const g=m.get;m.get=function(){return this._disableTracking||r(),Reflect.apply(g,this,arguments)},Object.defineProperty(t,h,m)}function c(h,p){let m=t,g=Object.getOwnPropertyDescriptor(m,h);if(g||(m=Object.getPrototypeOf(m),g=Object.getOwnPropertyDescriptor(m,h)),g||(m=Object.getPrototypeOf(m),g=Object.getOwnPropertyDescriptor(m,h)),!g)throw new Error("property not found");Object.defineProperty(t,p,g)}o("forEach"),o("toJSON"),o("toArray"),o("slice"),o("map"),c("length","lengthUntracked"),a("length");const l=t.push;t.push=function(h){this._disableTracking=!0;const p=l.call(this,h);return this._disableTracking=!1,p};const u=t.slice;return t.slice=function(h,p){this._disableTracking=!0;const m=u.call(this,h,p);return this._disableTracking=!1,m},t}const nk=new WeakSet;function $oe(t){if(nk.has(t))return t;nk.add(t);let e;function n(){if(!e){let s=Array.from(t.share.keys());const o=a=>{const c=Array.from(t.share.keys());JSON.stringify(s)!==JSON.stringify(c)&&(s=c,e.reportChanged())};e=ih("map",()=>{t.on("beforeObserverCalls",o)},()=>{t.off("beforeObserverCalls",o)})}e.reportObserved(t._implicitObserver)}const r=t.get;t.get=function(s){if(typeof s!="string")throw new Error("unexpected");const o=Reflect.apply(r,this,arguments);return Oy(o),o};function i(s){const o=t[s];let a;t[s]=function(){let c,l=arguments;return n(),a&&a.removeObservers(),a=Goe(()=>(c=Reflect.apply(o,t,l),c),()=>e.reportChanged()),c}}return i("toJSON"),Object.defineProperty(t,"keys",{get:()=>(n(),Object.keys(t.share))}),t}const rk=new WeakSet;function qoe(t){if(rk.has(t))return t;rk.add(t);let e;const n=new Map;function r(){if(!e){const a=c=>{(c.changes.added.size||c.changes.deleted.size||c.changes.keys.size||c.changes.delta.length)&&e.reportChanged()};e=ih("map",()=>{t.observe(a)},()=>{t.unobserve(a)})}e.reportObserved(t._implicitObserver)}function i(a){let c=n.get(a);if(!c){const l=u=>{u.keysChanged.has(a)&&(u.changes.added.size||u.changes.deleted.size||u.changes.keys.size||u.changes.delta.length)&&c.reportChanged()};c=ih(a,()=>{t.observe(l)},()=>{t.unobserve(l)}),n.set(a,c)}c.reportObserved(t._implicitObserver)}const s=t.get;t.get=function(a){if(typeof a!="string")throw new Error("unexpected");return i(a),Reflect.apply(s,this,arguments)};function o(a){const c=t[a];t[a]=function(){return r(),Reflect.apply(c,this,arguments)}}return o("values"),o("entries"),o("keys"),o("forEach"),o("toJSON"),t}const ik=new WeakSet;function sk(t){if(ik.has(t))return t;ik.add(t);let e;const n=i=>{e.reportChanged()};e=ih("text",()=>{t.observe(n)},()=>{t.unobserve(n)});function r(i){const s=t[i];t[i]=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(s,this,arguments)}}return r("toString"),r("toJSON"),t}const ok=new WeakSet;function ak(t){if(ok.has(t))return t;ok.add(t);let e;const n=s=>{(s.changes.added.size||s.changes.deleted.size||s.changes.keys.size||s.changes.delta.length)&&e.reportChanged()};e=ih("xml",()=>{t.observe(n)},()=>{t.unobserve(n)});function r(s){const o=t[s];t[s]=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(o,this,arguments)}}function i(s){let o=t,a=Object.getOwnPropertyDescriptor(o,s);if(a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),!a)throw new Error("property not found");const c=a.get;a.get=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(c,this,arguments)},Object.defineProperty(t,s,a)}return r("toString"),r("toDOM"),r("toArray"),r("getAttribute"),i("firstChild"),t}function Oy(t){return t instanceof nh||t instanceof Fo?sk(t):t instanceof ba?joe(t):t instanceof ka?qoe(t):t instanceof Yc||Object.prototype.hasOwnProperty.call(t,"autoLoad")?$oe(t):t instanceof Ia||t instanceof Pc?ak(t):t}function ck(t){t.share.forEach(e=>{e.constructor!==cr&&Oy(e)})}function lk(t,e){for(let r=t.length-1;r>=e;r--){let i=t[r];if(!i.deleted){var n;if(i instanceof ks)continue;(n=i.content)==null||n.getContent().forEach(s=>{s instanceof cr&&Oy(s)})}}}const uk=new WeakSet;function Xoe(t){uk.has(t)||(uk.add(t),Oy(t),t.store.clients.forEach(e=>{e&&lk(e,0)}),ck(t),t.on("beforeObserverCalls",e=>{ck(t),e.afterState.forEach((n,r)=>{const i=e.beforeState.get(r)||0;if(i!==n){const s=e.doc.store.clients.get(r);if(!s)return;const o=Uo(s,i);lk(s,o)}})}))}class Wp{constructor(e){this.value=void 0,this.value=e}}function Koe(t){return ArrayBuffer.isView(t)?new Wp(t):new Wp(Object.freeze(t))}function Yoe(t){const e=function(){var a;let c=(a=this[ho])==null?void 0:a.implicitObserver;return t._implicitObserver=c,t.slice.bind(t).apply(t,arguments).map(u=>{const h=Ly(u,c);return c&&typeof h=="object"?Zf(h,c):h})},n=function(a){return a.map(c=>{const l=gA(c);let u=Vl(l)||l;if(u instanceof Wp&&(u=u.value),u instanceof cr&&u.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return u})},r=function(){return[].findIndex.apply(e.apply(this),arguments)},i={slice:e,unshift:(...o)=>(t.unshift(n(o)),t.lengthUntracked),push:(...o)=>(t.push(n(o)),t.lengthUntracked),insert:t.insert.bind(t),toJSON:t.toJSON.bind(t),forEach:function(){return[].forEach.apply(e.apply(this),arguments)},every:function(){return[].every.apply(e.apply(this),arguments)},filter:function(){return[].filter.apply(e.apply(this),arguments)},find:function(){return[].find.apply(e.apply(this),arguments)},findIndex:r,some:function(){return[].some.apply(e.apply(this),arguments)},includes:function(){return[].includes.apply(e.apply(this),arguments)},map:function(){return[].map.apply(e.apply(this),arguments)},indexOf:function(){const o=arguments[0];return r.call(this,a=>tae(a,o))},splice:function(){let o=arguments[0]<0?t.length-Math.abs(arguments[0]):arguments[0],a=arguments[1],c=Array.from(Array.from(arguments).slice(2)),l=e.apply(this,[o,Number.isInteger(a)?o+a:void 0]);return t.doc?t.doc.transact(()=>{t.delete(o,a),t.insert(o,n(c))}):(t.delete(o,a),t.insert(o,n(c))),l}},s=[];for(let o in i)s[o]=i[o];return s}function Kd(t){if(typeof t=="string"&&t.trim().length){const e=Number(t);if(Number.isInteger(e))return e}return t}function hk(t,e=new ba){if(e[Br])throw new Error("unexpected");const n=Yoe(e),r=new Proxy(n,{set:(i,s,o)=>{throw typeof Kd(s)!="number"?new Error:new Error("array assignment is not implemented / supported")},get:(i,s,o)=>{const a=Kd(s);if(a===Py)return e;if(typeof a=="number"){let u;if(o&&o[ho]){var c;u=(c=o[ho])==null?void 0:c.implicitObserver,e._implicitObserver=u}let h=e.get(a);return h=Ly(h,u),h}if(a===Symbol.toStringTag)return"Array";if(a===Symbol.iterator){const u=e.slice();return Reflect.get(u,a)}return a==="length"?e.length:Reflect.get(i,a,o)},deleteProperty:(i,s)=>{const o=Kd(s);if(typeof o!="number")throw new Error;return o=0?(e.delete(o),!0):!1},has:(i,s)=>{const o=Kd(s);return typeof o!="number"?Reflect.has(i,o):o=0},getOwnPropertyDescriptor(i,s){const o=Kd(s);if(o==="length")return{enumerable:!1,configurable:!1,writable:!0};if(typeof o=="number"&&o>=0&&o{const s=[];for(let o=0;o{if(typeof i!="string")throw new Error;const o=gA(s);let a=Vl(o)||o;if(a instanceof Wp&&(a=a.value),a instanceof cr&&a.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return e.set(i,a),!0},get:(r,i,s)=>{if(i===Py)return e;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[ho]){var a;o=(a=s[ho])==null?void 0:a.implicitObserver,e._implicitObserver=o}let c=e.get(i);return c=Ly(c,o),c},deleteProperty:(r,i)=>{if(typeof i!="string")throw new Error;return e.has(i)?(e.delete(i),!0):!1},has:(r,i)=>!!(typeof i=="string"&&e.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&e.has(i))return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(e.keys())});yp.set(e,n);for(let r in t)n[r]=t[r];return n}function Zoe(t){return t instanceof cr}const yp=new WeakMap;function Ly(t,e){if(Zoe(t)){if(t._implicitObserver=e,t instanceof ba||t instanceof ka){if(!yp.has(t)){const n=gA(t);yp.set(t,n)}t=yp.get(t)}else if(t instanceof Pc||t instanceof Ia||t instanceof nh||t instanceof td||t instanceof Fo)JT(t),t.__v_skip=!0;else throw new Error("unknown YType");return t}else{if(t===null)return null;if(typeof t=="object")return Koe(t)}return t}function gA(t){if(t==null)return t;if(t=Vl(t)||t,t instanceof ba)return hk([],t);if(t instanceof ka)return fk({},t);if(typeof t=="string")return t;if(Array.isArray(t))return hk(t);if(t instanceof Pc||t instanceof Ia||t instanceof nh||t instanceof td)return t;if(t instanceof Fo)return t;if(typeof t=="object")return t instanceof Wp?t:fk(t);if(typeof t=="number"||typeof t=="boolean")return t;throw new Error("invalid")}function Joe(t){for(let[e,n]of Object.entries(t))if(Array.isArray(n)){if(n.length!==0)throw new Error("Root Array initializer must always be empty array")}else if(n&&typeof n=="object"){if(Object.keys(n).length!==0||Object.getPrototypeOf(n)!==Object.prototype)throw new Error("Root Object initializer must always be {}")}else if(n!=="xml"&&n!=="text")throw new Error("unknown Root initializer")}function dk(t,e,n){let r=e[n];if(!r){n!=="__v_raw"&&n!=="__v_isRef"&&n!=="__v_isReadonly"&&console.warn("property not found on root doc",n);return}return r==="xml"?t.getXmlFragment(n):r==="text"?t.getText(n):Array.isArray(r)?t.getArray(n):t.getMap(n)}function Qoe(t,e){if(t[Br])throw new Error("unexpected");Joe(e);const n=new Proxy({},{set:(r,i,s)=>{throw typeof i!="string"?new Error:new Error("cannot set new elements on root doc")},get:(r,i,s)=>{if(i===Py)return t;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[ho]){var a;o=(a=s[ho])==null?void 0:a.implicitObserver,t._implicitObserver=o}if(i==="toJSON"){for(let u of Object.keys(e))dk(t,e,u);return Reflect.get(t,i)}let c=dk(t,e,i);return c=Ly(c,o),c},deleteProperty:(r,i)=>{throw new Error("deleteProperty not available for doc")},has:(r,i)=>!!(typeof i=="string"&&t.share.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&t.share.has(i)||i==="toJSON")return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(t.share.keys())});return yp.set(t,n),n}Woe(lie);const Py=Symbol("INTERNAL_SYMBOL");function pk(t,e){const n=Vl(t)||t;if(!n)throw new Error("not a valid synced object");return n instanceof Yc?(n.on("update",e),()=>{n.off("update",e)}):(n.observeDeep(e),()=>{n.unobserveDeep(e)})}function eae(t){const e=Vl(t);if(!(e instanceof Yc))throw new Error("store is not a valid syncedStore that maps to a Y.Doc");return e}function Vl(t){if(typeof t!="object"||t===null)return;const e=t[Py];return e&&(JT(e),e.__v_skip=!0),e}function tae(t,e){if(t===e)return!0;if(typeof t=="object"&&typeof e=="object"){const n=Vl(t),r=Vl(e);return!n||!r?!1:n===r}return!1}function nae(t,e=new Yc){return Xoe(e),Qoe(e,t)}function rae(t,e){var n=Ne.useReducer(function(a){return a+1},0),r=n[1],i=Ne.useRef(),s=Ne.useRef(!1);i.current||(i.current=new YT(function(){s.current&&r()}));var o=Ne.useMemo(function(){var a;return(a=i.current)==null||a.removeObservers(),Zf(t,i.current)},[]);return Ne.useEffect(function(){return s.current=!0,i.current||r(),function(){var a;s.current=!1,(a=i.current)==null||a.removeObservers(),i.current=null}},[]),o}function iae(t,e){if(!Vl(t))throw new Error("syncedObject passed to useSyncedStore is not a SyncedStore Store or internal data type.");return rae(t)}const _A=0,kU=1,IU=2,sae=(t,e)=>{Ht(t,_A);const n=zse(e);xi(t,n)},OU=(t,e,n)=>{Ht(t,kU),xi(t,Dse(e,n))},oae=(t,e,n)=>OU(e,n,Oi(t)),LU=(t,e,n)=>{try{Ose(e,Oi(t),n)}catch(r){console.error("Caught error while handling a Yjs update",r)}},aae=(t,e)=>{Ht(t,IU),xi(t,e)},cae=LU,lae=(t,e,n,r)=>{const i=Gt(t);switch(i){case _A:oae(t,e,n);break;case kU:LU(t,n,r);break;case IU:cae(t,n,r);break;default:throw new Error("Unknown message type")}return i},La=nae({shared:[]});function km(t,e,n){return t.find(r=>r.key===e&&r.type===n)}function uae(){return iae(La)}function PU(t,e){const n=uae(),r=km(n.shared,t,e);return Z(r)?r:void 0}function vA(t){return PU(t,0)}function DU(t){return PU(t,1)}function UU(t,e,n){const r=km(La.shared,t,e);Z(r)||La.shared.push({key:t,type:e,value:n})}function hae(t,e){UU(t,0,e)}function FU(t,e){const n=new Fo(e);UU(t,1,n)}function Rl(t,e){const n=km(La.shared,t,0);if(Z(n)){n.value=e;return}La.shared.push({key:t,type:0,value:e})}function fae(t,e){const n=new Fo(e),r=km(La.shared,t,1);if(Z(r)){r.value=n;return}La.shared.push({key:t,type:1,value:n})}function BU(t,e,n){let r;function i(){const o=km(La.shared,t,e);Z(o)&&(s(),r=pk(o,()=>n(o.value)))}const s=pk(La.shared,i);return i(),()=>r==null?void 0:r()}function dae(t,e){return BU(t,0,e)}function pae(t,e){return BU(t,1,n=>e(n.toJSON()))}function y_(t){return Mo(t)}let mk=!1;const bl=eae(La),fc=lh("modem",["second"],t=>{switch(t.target){case"second":!mk&&t.data%2===0&&fc.emit("modem:join");break;case"join":if(t.sender!==fc.id()){fc.reply(t,"joinack");const e=Cl();sae(e,bl),fc.reply(t,"sync",y_(e));const n=Cl();OU(n,bl),fc.reply(t,"sync",y_(n))}break;case"joinack":mk=!0;break;case"sync":{if(Z(t.data)&&t.sender!==fc.id()){const e=vh(t.data),n=Cl();lae(e,n,bl,fc)===_A&&fc.emit("modem:sync",y_(n))}break}}});function zU(t){const e=Cl();aae(e,t),fc.emit("modem:sync",y_(e))}bl.on("update",zU);bl.on("destroy",()=>{bl==null||bl.off("update",zU)});function yA(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function mae(t,e){const n=indexedDB.open(t);n.onupgradeneeded=()=>n.result.createObjectStore(e);const r=yA(n);return(i,s)=>r.then(o=>s(o.transaction(e,i).objectStore(e)))}let mS;function VU(){return mS||(mS=mae("keyval-store","keyval")),mS}function gae(t,e=VU()){return e("readonly",n=>yA(n.get(t)))}function _ae(t,e,n=VU()){return n("readwrite",r=>new Promise((i,s)=>{r.get(t).onsuccess=function(){try{r.put(e(this.result),t),i(yA(r.transaction))}catch(o){s(o)}}}))}const ww=66.666,hv=Math.round(1e3/ww),vae=3;function Qh(t){return new Promise(e=>setTimeout(e,t))}var ku=(t=>(t[t.Border=-1]="Border",t[t.Data=0]="Data",t[t.Function=1]="Function",t[t.Position=2]="Position",t[t.Timing=3]="Timing",t[t.Alignment=4]="Alignment",t))(ku||{}),yae=Object.defineProperty,xae=(t,e,n)=>e in t?yae(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,N0=(t,e,n)=>(xae(t,typeof e!="symbol"?e+"":e,n),n);const Sae=[0,1],HU=[1,0],GU=[2,3],WU=[3,2],Eae={L:Sae,M:HU,Q:GU,H:WU},wae=/^[0-9]*$/,bae=/^[A-Z0-9 $%*+.\/:-]*$/,gS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",xA=1,SA=40,gk=3,Tae=3,k0=40,Aae=10,jU=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],$U=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]];class Mae{constructor(e,n,r,i){if(this.version=e,this.ecc=n,N0(this,"size"),N0(this,"mask"),N0(this,"modules",[]),N0(this,"types",[]),eSA)throw new RangeError("Version value out of range");if(i<-1||i>7)throw new RangeError("Mask value out of range");this.size=e*4+17;const s=Array.from({length:this.size},()=>!1);for(let a=0;a0));this.drawFunctionPatterns();const o=this.addEccAndInterleave(r);if(this.drawCodewords(o),i===-1){let a=1e9;for(let c=0;c<8;c++){this.applyMask(c),this.drawFormatBits(c);const l=this.getPenaltyScore();l=0&&e=0&&n>>9)*1335;const i=(n<<10|r)^21522;for(let s=0;s<=5;s++)this.setFunctionModule(8,s,cc(i,s));this.setFunctionModule(8,7,cc(i,6)),this.setFunctionModule(8,8,cc(i,7)),this.setFunctionModule(7,8,cc(i,8));for(let s=9;s<15;s++)this.setFunctionModule(14-s,8,cc(i,s));for(let s=0;s<8;s++)this.setFunctionModule(this.size-1-s,8,cc(i,s));for(let s=8;s<15;s++)this.setFunctionModule(8,this.size-15+s,cc(i,s));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let r=0;r<12;r++)e=e<<1^(e>>>11)*7973;const n=this.version<<12|e;for(let r=0;r<18;r++){const i=cc(n,r),s=this.size-11+r%3,o=Math.floor(r/3);this.setFunctionModule(s,o,i),this.setFunctionModule(o,s,i)}}drawFinderPattern(e,n){for(let r=-4;r<=4;r++)for(let i=-4;i<=4;i++){const s=Math.max(Math.abs(i),Math.abs(r)),o=e+i,a=n+r;o>=0&&o=0&&a{(p!==c-s||g>=a)&&h.push(m[p])});return h}drawCodewords(e){if(e.length!==Math.floor(bw(this.version)/8))throw new RangeError("Invalid argument");let n=0;for(let r=this.size-1;r>=1;r-=2){r===6&&(r=5);for(let i=0;i>>3],7-(n&7)),n++)}}}applyMask(e){if(e<0||e>7)throw new RangeError("Mask value out of range");for(let n=0;n5&&e++):(this.finderPenaltyAddHistory(a,c),o||(e+=this.finderPenaltyCountPatterns(c)*k0),o=this.modules[s][l],a=1);e+=this.finderPenaltyTerminateAndCount(o,a,c)*k0}for(let s=0;s5&&e++):(this.finderPenaltyAddHistory(a,c),o||(e+=this.finderPenaltyCountPatterns(c)*k0),o=this.modules[l][s],a=1);e+=this.finderPenaltyTerminateAndCount(o,a,c)*k0}for(let s=0;so+(a?1:0),n);const r=this.size*this.size,i=Math.ceil(Math.abs(n*20-r*10)/r)-1;return e+=i*Aae,e}getAlignmentPatternPositions(){if(this.version===1)return[];{const e=Math.floor(this.version/7)+2,n=this.version===32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,r=[6];for(let i=this.size-7;r.length0&&e[2]===n&&e[3]===n*3&&e[4]===n&&e[5]===n;return(r&&e[0]>=n*4&&e[6]>=n?1:0)+(r&&e[6]>=n*4&&e[0]>=n?1:0)}finderPenaltyTerminateAndCount(e,n,r){return e&&(this.finderPenaltyAddHistory(n,r),n=0),n+=this.size,this.finderPenaltyAddHistory(n,r),this.finderPenaltyCountPatterns(r)}finderPenaltyAddHistory(e,n){n[0]===0&&(e+=this.size),n.pop(),n.unshift(e)}}function mc(t,e,n){if(e<0||e>31||t>>>e)throw new RangeError("Value out of range");for(let r=e-1;r>=0;r--)n.push(t>>>r&1)}function cc(t,e){return(t>>>e&1)!==0}class EA{constructor(e,n,r){if(this.mode=e,this.numChars=n,this.bitData=r,n<0)throw new RangeError("Invalid argument");this.bitData=r.slice()}getData(){return this.bitData.slice()}}const Cae=[1,10,12,14],Rae=[2,9,11,13],Nae=[4,8,16,16];function qU(t,e){return t[Math.floor((e+7)/17)+1]}function XU(t){const e=[];for(const n of t)mc(n,8,e);return new EA(Nae,t.length,e)}function kae(t){if(!KU(t))throw new RangeError("String contains non-numeric characters");const e=[];for(let n=0;n=1<SA)throw new RangeError("Version number out of range");let e=(16*t+128)*t+64;if(t>=2){const n=Math.floor(t/7)+2;e-=(25*n-10)*n-55,t>=7&&(e-=36)}return e}function x_(t,e){return Math.floor(bw(t)/8)-jU[e[0]][t]*$U[e[0]][t]}function Dae(t){if(t<1||t>255)throw new RangeError("Degree out of range");const e=[];for(let r=0;r0);for(const r of t){const i=r^n.shift();n.push(0),e.forEach((s,o)=>n[o]^=Tw(s,i))}return n}function Tw(t,e){if(t>>>8||e>>>8)throw new RangeError("Byte out of range");let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(e>>>r&1)*t;return n}function Fae(t,e,n=1,r=40,i=-1,s=!0){if(!(xA<=n&&n<=r&&r<=SA)||i<-1||i>7)throw new RangeError("Invalid value");let o,a;for(o=n;;o++){const h=x_(o,e)*8,p=Lae(t,o);if(p<=h){a=p;break}if(o>=r)throw new RangeError("Data too long")}for(const h of[HU,GU,WU])s&&a<=x_(o,h)*8&&(e=h);const c=[];for(const h of t){mc(h.mode[0],4,c),mc(h.numChars,qU(h.mode,o),c);for(const p of h.getData())c.push(p)}const l=x_(o,e)*8;mc(0,Math.min(4,l-c.length),c),mc(0,(8-c.length%8)%8,c);for(let h=236;c.length0);return c.forEach((h,p)=>u[p>>>3]|=h<<7-(p&7)),new Mae(o,e,u,i)}function Bae(t,e){var h;const{ecc:n="L",boostEcc:r=!1,minVersion:i=1,maxVersion:s=40,maskPattern:o=-1,border:a=1}=e||{},c=typeof t=="string"?Oae(t):Array.isArray(t)?[XU(t)]:void 0;if(!c)throw new Error(`uqr only supports encoding string and binary data, but got: ${typeof t}`);const l=Fae(c,Eae[n],i,s,o,r),u=zae({version:l.version,maskPattern:l.mask,size:l.size,data:l.modules,types:l.types},a);return e!=null&&e.invert&&(u.data=u.data.map(p=>p.map(m=>!m))),(h=e==null?void 0:e.onEncoded)==null||h.call(e,u),u}function zae(t,e=1){if(!e)return t;const{size:n}=t,r=n+e*2;t.size=r,t.data.forEach(s=>{for(let o=0;o!1)),t.data.push(Array.from({length:r},o=>!1));const i=ku.Border;t.types.forEach(s=>{for(let o=0;oi)),t.types.push(Array.from({length:r},o=>i));return t}function Vae(t,e,n,r=!1){return e<0||n<0||e>=t.length||n>=t.length?r:t[n][e]}function Hae(t,e={}){const n={WHITE_ALL:"█",WHITE_BLACK:"▀",BLACK_WHITE:"▄",BLACK_ALL:" "},r=Bae(t,e),i=!1,s=!0,o=(l,u)=>Vae(r.data,l,u,!0),a=[];let c="";for(let l=0;l`$${i[a.charCodeAt(0)]}`).join("");Bn(t,o)}Bn(t,`!copyit ${e};${n}`)}async function $ae(t){return gae(t)}async function qae(t,e){return _ae(t,e)}function Xae(t){try{return sessionStorage.getItem(t)??void 0}catch(e){Vn(Or.name(),`readsession ${t}`,e.message)}}function Kae(t,e){try{Z(e)?sessionStorage.setItem(t,e):sessionStorage.removeItem(t)}catch(n){Vn(Or.name(),`writesession ${t} <- ${e}`,n.message)}}function Yae(){try{const t=window.location.hash.slice(1);if(t.length)return t}catch(t){Vn("register","crash",t.message)}return""}let Aw=!0;window.addEventListener("hashchange",()=>{Aw?window.location.reload():Aw=!0});function Zae(t){const e=`#${t}`;window.location.hash!==e&&(Aw=!1,window.location.hash=e,ro(Or.name(),`wrote ${(t==null?void 0:t.length)??0} chars [${t.slice(0,8)}...${t.slice(-8)}]`))}async function yk(t){const e=new FormData;e.append("url",t);const n=new Request("https://bytes.zed.cafe",{method:"POST",body:e});return await(await fetch(n)).text()}async function Jae(){return $ae("SELECTED_ID")}async function Qae(t){return qae("SELECTED_ID",()=>t)}let _S=0;const xk=1,Or=lh("register",["second","ready","error"],function(t){const e=os.getState();switch(t.target){case"error:login:main":case"error:login:title":case"error:login:player":u2(Or.name());break;case"dev":Au("register:dev",async function(){if(window.location.href.includes("/locked/")?"locked":""){const r=await yk(window.location.href);vk("devshare",r,r)}else gc(Or.name(),"creating locked terminal"),await Qh(100),window.location.href=window.location.href.replace("/#","/locked/#")});break;case"share":Au("register:share",async function(){const n=await yk(window.location.href.replace(/cafe.*locked/,"cafe"));vk("share",n,n)});break;case"refresh":Au("register:refresh",async function(){gc(Or.name(),"BYE"),await Qh(100),window.location.reload()});break;case"nuke":Au("register:nuke",async function(){gc(Or.name(),"nuke in"),rn(Or.name(),"3","..."),await Qh(1e3),rn(Or.name(),"2","..."),await Qh(1e3),rn(Or.name(),"1","..."),await Qh(1e3),gc(Or.name(),"BYE"),await Qh(100),window.location.hash="",window.location.reload()});break;case"ready":{if(!Z(t.player))return;const n="SESSION_ID",r=Xae(n)??t.player;Kae(n,r),e.gadget.player||(os.setState(i=>({...i,gadget:{...i.gadget,player:r}})),setTimeout(()=>R9("register",r),256));break}case"ackinit":{Au("register:ackinit",async()=>{if(!Z(t.player))return;const n=Yae();if(n.length===0){Vn(Or.name(),"content","no content found"),u2(Or.name());return}const r=await Jae()??"";N9(Or.name(),n,r,t.player)});break}case"ackbooks":Z(t.player)&&k9(Or.name(),t.player);break;case"acklogin":if(Z(t.player)){const{player:n}=t;Lb(Or.name()),setTimeout(()=>g9(Or.name(),n),1e3)}break;case"flush":if(cn(t.data)){const[n,r]=t.data;Kt(n)&&Kt(r)&&(document.title=n,Zae(r))}break;case"select":Au("register:select",async()=>{Kt(t.data)&&(await Qae(t.data),x9(Or.name()))});break;case"second":++_S,_S>=xk&&(_S-=xk,e.gadget.player&&O9(Or.name(),e.gadget.player));break}});lh("tape",[],t=>{const{layout:e,terminal:n,editor:r}=ts.getState();function i(o){let a=[[fr(),o.target,o.sender,...o.data],...n.logs];a.length>wN&&(a=a.slice(0,wN)),ts.setState(c=>({terminal:{...c.terminal,logs:a}}))}function s(o){let c=e+(o?1:-1);if(c<0&&(c+=Pi.MAX),c>=Pi.MAX&&(c-=Pi.MAX),!r.open)switch(c){case Pi.SPLIT_Y:case Pi.SPLIT_Y_ALT:c=Pi.TOP;break}ts.setState({layout:c})}switch(t.target){case"info":n.level>=d_.INFO&&i(t);break;case"debug":n.level>=d_.DEBUG&&i(t);break;case"error":n.level>d_.OFF&&i(t);break;case"crash":ts.setState(o=>({layout:Pi.FULL,terminal:{...o.terminal,open:!0}}));break;case"terminal:open":ts.setState(o=>({terminal:{...o.terminal,open:!0}}));break;case"terminal:close":ts.setState(o=>({terminal:{...o.terminal,open:!1}}));break;case"terminal:inclayout":ZW(t.data)&&s(t.data);break;case"editor:open":if(cn(t.data)&&Z(t.player)){const{player:o}=t,[a,c,l,u]=t.data??["","",""];ts.setState(h=>({terminal:{...h.terminal,open:!0},editor:{open:!0,player:o,book:a,page:c,type:l,title:u}}))}break;case"editor:close":ts.setState(o=>({editor:{...o.editor,open:!1}}));break}});const vS=lh("clock",[],()=>{});let yS=0,I0=0,xS=0,Sk=performance.now();function ZU(){const t=performance.now(),e=t-Sk,n=window.location.href.includes("/locked/")?"locked":"";xS+=e,xS>=ww&&(xS%=ww,vS.emit("tick",I0,n),vS.emit("tock",I0,n),++yS,++I0,yS>=hv&&(yS%=hv,vS.emit("second",I0,n))),Sk=t,setTimeout(ZU,1)}ZU();let O0;function ece(){if(Z(O0))return;O0=new Jre;const t=Zre(e=>O0.postMessage(e));O0.addEventListener("message",e=>t(e.data))}const Mw=3,JU=2,If=8,Of=14,as=If*JU,Hi=Of*JU,yc=16;var op=(t=>(t[t.BLANK=0]="BLANK",t[t.TILES=1]="TILES",t[t.SPRITES=2]="SPRITES",t[t.DITHER=3]="DITHER",t[t.MEDIA=4]="MEDIA",t[t.CONTROL=5]="CONTROL",t))(op||{});function tce(t){let e=0,n=0,r=0,i=0,s=1;return t.forEach(o=>{switch(o.type){case 1:e=Math.max(e,o.width),n=Math.max(n,o.height);break;case 3:e=Math.max(e,o.width),n=Math.max(n,o.height);break;case 5:r=o.focusx,i=o.focusy,s=o.viewscale;break}}),{width:e,height:n,focusx:r,focusy:i,viewscale:s}}var Si=(t=>(t[t.START=0]="START",t[t.LEFT=1]="LEFT",t[t.RIGHT=2]="RIGHT",t[t.TOP=3]="TOP",t[t.BOTTOM=4]="BOTTOM",t[t.SCROLL=5]="SCROLL",t))(Si||{});const nce={start:0,left:1,right:2,top:3,bottom:4,scroll:5},rce={0:1,1:20,2:20,3:1,4:1,5:40};function xd(t,e){return`${t}:${e}`}const QU=1,e3=16,t3=256;var Ue=(t=>(t[t.NONE=0]="NONE",t[t.ALT=1]="ALT",t[t.CTRL=2]="CTRL",t[t.SHIFT=3]="SHIFT",t[t.MOVE_UP=4]="MOVE_UP",t[t.MOVE_DOWN=5]="MOVE_DOWN",t[t.MOVE_LEFT=6]="MOVE_LEFT",t[t.MOVE_RIGHT=7]="MOVE_RIGHT",t[t.OK_BUTTON=8]="OK_BUTTON",t[t.CANCEL_BUTTON=9]="CANCEL_BUTTON",t[t.MENU_BUTTON=10]="MENU_BUTTON",t[t.SHOOT_UP=11]="SHOOT_UP",t[t.SHOOT_DOWN=12]="SHOOT_DOWN",t[t.SHOOT_LEFT=13]="SHOOT_LEFT",t[t.SHOOT_RIGHT=14]="SHOOT_RIGHT",t))(Ue||{});const ice=new xe,n3=Ne.createContext([]);function Dy(){return Ne.useContext(n3)}function sce({width:t=0,height:e=0,children:n,...r}){const i=Ne.useRef(null),[s]=Ne.useState(()=>{const a=[];return t&&a.push(new Eo,new Eo),e&&a.push(new Eo,new Eo),a}),[o]=Ne.useState(()=>[new xe(0,0,0),new xe(0,0,0),new xe(0,0,0),new xe(0,0,0),new xe(0,0,0)]);return zv(()=>{if(i.current){const a=i.current.localToWorld(o[0].set(0,0,0)),c=[];if(t){const l=t*.5;c.push(i.current.localToWorld(o[3].set(l,0,0)),i.current.localToWorld(o[4].set(-l,0,0)))}if(e){const l=e*.5;c.push(i.current.localToWorld(o[1].set(0,l,0)),i.current.localToWorld(o[2].set(0,-l,0)))}for(let l=0;lSymbol.iterator in t,wk=t=>"entries"in t,bk=(t,e)=>{const n=t instanceof Map?t:new Map(t.entries()),r=e instanceof Map?e:new Map(e.entries());if(n.size!==r.size)return!1;for(const[i,s]of n)if(!Object.is(s,r.get(i)))return!1;return!0},oce=(t,e)=>{const n=t[Symbol.iterator](),r=e[Symbol.iterator]();let i=n.next(),s=r.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=n.next(),s=r.next()}return!!i.done&&!!s.done};function ace(t,e){return Object.is(t,e)?!0:typeof t!="object"||t===null||typeof e!="object"||e===null?!1:!Ek(t)||!Ek(e)?bk({entries:()=>Object.entries(t)},{entries:()=>Object.entries(e)}):wk(t)&&wk(e)?bk(t,e):oce(t,e)}function Yl(t){const e=Co.useRef();return n=>{const r=t(n);return ace(e.current,r)?e.current:e.current=r}}const cce=Date.now(),So={get value(){return(Date.now()-cce)/1e3%1e6}},lce=120;let r3=0;function uce(t){r3=lce/t}uce(150);const bA={get value(){return r3}};function TA(t){const e=t.clone();return e.uniforms.time=So,e.uniforms.interval=bA,e}function hce(t,e,n,r){const i=e*n*4;for(let s=0,o=0;s - - varying vec2 vUv; - - void main() { - vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); - gl_Position = projectionMatrix * mvPosition; - - vUv = uv; - - #include - } - `,fragmentShader:` - #include - - uniform vec3 color; - uniform sampler2D data; - - varying vec2 vUv; - - // adapted from https://www.shadertoy.com/view/Mlt3z8 - float bayerDither2x2( vec2 v ) { - return mod( 3.0 * v.y + 2.0 * v.x, 4.0 ); - } - - float bayerDither4x4( vec2 v ) { - vec2 P1 = mod( v, 2.0 ); - vec2 P2 = mod( floor( 0.5 * v ), 2.0 ); - return 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 ); - } - - void main() { - #include - - float alpha = texture2D(data, vUv).r; - if (alpha < 1.0) { - vec2 ditherCoord = floor( mod( gl_FragCoord.xy, 4.0 ) ); - if ( bayerDither4x4( ditherCoord ) / 16.0 >= alpha ) { - discard; - } - } - - gl_FragColor.rgba = vec4(color.xyz, 1.0); - } - `});function pce(){return TA(dce)}function Uy(t,e,n){typeof t!="number"&&(t=0,e=0,n=1),typeof e!="number"&&(e=t,t=0,n=1),typeof n!="number"&&(n=1);const r=[],i=Math.min(t,e),s=Math.max(t,e);for(let o=i;o<=s;o+=n)r.push(o);return r}function mce(t){return t[sp(0,t.length-1)]}function _c(...t){return mce(t.flat())}function i3(t,e=16){return t?Uy(e-1).map(n=>{const r=n*Mw;return new ln(t.bits[r]/63,t.bits[r+1]/63,t.bits[r+2]/63)}):[]}function gce(t){const e=document.createElement("canvas");if(e.width=(t==null?void 0:t.width)||1,e.height=(t==null?void 0:t.height)||1,t){const n=e.getContext("2d"),r=n==null?void 0:n.getImageData(0,0,t.width,t.height);if(r&&n){let i=0;const{data:s}=r;for(let o=0;oAA(t),[t])}const fv=[0,1,0],c3=[1,1,0],dv=[1,0,0],l3=[0,0,0],Tce=new Float32Array([...fv,...dv,...c3,...fv,...l3,...dv]),Ace=new Float32Array([...fv.slice(0,2),...dv.slice(0,2),...c3.slice(0,2),...fv.slice(0,2),...l3.slice(0,2),...dv.slice(0,2)]);function Mce(t,e,n,r,i,s){const o=e*n*4;for(let a=0,c=0;a{switch(a%3){case 0:return o*r;case 1:return o*i;default:return o}});t.setAttribute("position",new Jn(s,3)),t.setAttribute("uv",new Jn(Ace,2)),t.computeBoundingBox(),t.computeBoundingSphere()}const Rce=i3(o3()),Ak=AA(Fy()),Nce=new Gi({transparent:!1,uniforms:{time:So,interval:bA,map:new Mn(Ak),alt:new Mn(Ak),data:new Mn(null),palette:new Mn(Rce),size:{value:new St},step:{value:new St}},vertexShader:` - #include - varying vec2 vUv; - void main() { - vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); - gl_Position = projectionMatrix * mvPosition; - vUv = uv; - #include - } - `,fragmentShader:` - #include - - uniform float time; - uniform float interval; - uniform sampler2D map; - uniform sampler2D alt; - uniform usampler2D data; - uniform vec3 palette[16]; - uniform vec2 size; - uniform vec2 step; - varying vec2 vUv; - - void main() { - #include - - uvec4 tiledata = texture(data, vUv); - int colori = int(tiledata.z); - int bgi = int(tiledata.w); - - vec2 charPosition = mod(vUv, size) / size; - vec2 uv = vec2(charPosition.x * step.x, charPosition.y * step.y); - vec3 color = palette[colori]; - - uv.x += step.x * float(tiledata.x); - uv.y += step.y * float(tiledata.y); - uv.y = 1.0 - uv.y; - - bool useAlt = mod(time, interval * 2.0) > interval; - vec3 blip = useAlt ? texture(alt, uv).rgb : texture(map, uv).rgb; - - if (blip.r == 0.0) { - if (bgi >= ${wn.ONCLEAR}) { - discard; - } - color = palette[bgi]; - } - - gl_FragColor.rgb = color; - gl_FragColor.a = 1.0; - } - `});function kce(){return TA(Nce)}function By({width:t,height:e,alphas:n}){const r=Dy(),i=Ne.useRef(null),[s]=Ne.useState(()=>pce());return Ne.useEffect(()=>{s.uniforms.data.value=fce(t,e)},[s.uniforms.data,t,e]),Ne.useEffect(()=>{hce(s.uniforms.data.value,t,e,n)},[s.uniforms.data.value,t,e,n]),Ne.useEffect(()=>{i.current&&(u3(i.current,t,e),s.clipping=r.length>0,s.clippingPlanes=r,s.needsUpdate=!0)},[s,r,t,e]),ve.jsx("mesh",{material:s,children:ve.jsx("bufferGeometry",{ref:i})})}function Ice({width:t,height:e,alpha:n}){const r=Ne.useMemo(()=>new Array(t*e).fill(n),[t,e,n]);return ve.jsx(By,{width:t,height:e,alphas:r})}const Yd=new WG,gu=new St;function Oce({width:t,height:e,top:n,left:r,right:i,bottom:s,scale:o=.125,alpha:a=.25}){const c=Ne.useMemo(()=>{const l=new Array(t*e);Yd.min.x=r,Yd.min.y=n,Yd.max.x=i,Yd.max.y=s,gu.x=0,gu.y=0;for(let u=0;u=t&&(gu.x=0,++gu.y);return l},[t,e,n,r,i,s,o,a]);return ve.jsx(By,{width:t,height:e,alphas:c})}const Lce=i3(o3()),Mk=AA(Fy()),Pce=hv*2,Dce=new Gi({transparent:!1,uniforms:{time:So,interval:bA,smoothrate:new Mn(Pce),map:new Mn(Mk),alt:new Mn(Mk),palette:new Mn(Lce),pointSize:{value:new St(as,Hi)},rows:new Mn(1),step:new Mn(new St)},vertexShader:` - #include - - attribute float visible; - attribute vec4 charData; - attribute vec3 lastPosition; - attribute vec2 lastColor; - attribute vec2 lastBg; - attribute vec2 animShake; - attribute vec2 animBounce; - - uniform float smoothrate; - uniform float time; - uniform float interval; - uniform vec2 pointSize; - uniform vec3 palette[16]; - uniform float tindex; - - varying float vVisible; - varying vec2 vCharData; - varying vec3 vColor; - varying vec4 vBg; - - float rand(float co) { - return fract(sin(co*(91.3458)) * 47453.5453); - } - - vec3 colorFromIndex(float index) { - return palette[int(index)]; - } - - vec4 empty; - - vec4 bgFromIndex(float index) { - if (int(index) >= ${wn.ONCLEAR}) { - return empty; - } - vec4 bg; - bg.rgb = colorFromIndex(index); - bg.a = 1.0; - return bg; - } - - float animDelta(float startTime, float deltaMod, float maxDelta) { - float delta = time - startTime; - if (delta < 0.0) { - return maxDelta; - } - return clamp(delta * deltaMod, 0.0, maxDelta); - } - - void main() { - vVisible = visible; - - float deltaPosition = clamp((time - lastPosition.z) * smoothrate, 0.0, 1.0); - vec2 animPosition = mix(lastPosition.xy, position.xy, deltaPosition); - - float deltaShake = 1.0 - animDelta(animShake.y, smoothrate * 0.5, 1.0); - animPosition += vec2( - deltaShake - rand(cos(time) + animShake.x) * deltaShake * 2.0, - deltaShake - rand(sin(time) + animShake.x) * deltaShake * 2.0 - ) * 0.5; - - float deltaBounce = 1.0 - abs(1.0 - animDelta(animBounce.y, smoothrate, 2.0)); - animPosition.y -= smoothstep(0.0, 1.0, deltaBounce); - - float deltaColor = animDelta(lastColor.y, smoothrate, 1.0); - vec3 sourceColor = colorFromIndex(lastColor.x); - vec3 destColor = colorFromIndex(charData.z); - vColor = mix(sourceColor, destColor, deltaColor); - - float deltaBg = animDelta(lastBg.y, smoothrate, 1.0); - vec4 sourceBg = bgFromIndex(lastBg.x); - vec4 destBg = bgFromIndex(charData.w); - vBg = mix(sourceBg, destBg, deltaBg); - - vCharData.xy = charData.xy; - - animPosition = animPosition * pointSize; - animPosition += pointSize * 0.5; - animPosition.x += (pointSize.y - pointSize.x) * 0.5; - - vec4 mvPosition = modelViewMatrix * vec4(animPosition, 0.0, 1.0); - gl_Position = projectionMatrix * mvPosition; - - // this handles things being scaled - gl_PointSize = pointSize.y * modelViewMatrix[0][0]; - - #include - } - `,fragmentShader:` - #include - - uniform float time; - uniform float interval; - uniform sampler2D map; - uniform sampler2D alt; - uniform float rows; - uniform vec2 step; - uniform vec2 pointSize; - - varying float vVisible; - varying vec2 vCharData; - varying vec3 vColor; - varying vec4 vBg; - - void main() { - #include - - float xscale = pointSize.y / pointSize.x; - float px = gl_PointCoord.x * xscale; - - if (vVisible == 0.0 || px >= 1.0) { - discard; - } - - vec2 lookup = vec2(vCharData.x, vCharData.y); - - vec2 idx = vec2(px, 1.0 - gl_PointCoord.y); - vec2 char = vec2(lookup.x * step.x, (rows - lookup.y) * step.y); - vec2 uv = idx * step + char; - - bool useAlt = mod(time, interval * 2.0) > interval; - vec3 blip = useAlt ? texture2D(alt, uv).rgb : texture2D(map, uv).rgb; - - if (blip.r == 0.0) { - gl_FragColor = vBg; - } else { - gl_FragColor.rgb = vColor; - gl_FragColor.a = 1.0; - } - } - `});function Uce(){return TA(Dce)}const Fce=Fy(),Ck=2048;function Bce({sprites:t}){const e=a3(Fce),n=Dy(),r=Ne.useRef(null),i=Ne.useRef([]),[s]=Ne.useState(()=>Uce()),{width:o=0,height:a=0}=(e==null?void 0:e.image)??{};return Ne.useMemo(()=>{var h;i.current.length===0&&(i.current=Array.from({length:Ck},()=>({id:"",x:0,y:0,char:0,color:0,bg:0})));const c={};for(let p=0;pp.id));let u=0;for(let p=0;p{const{current:c}=r,{current:l}=i;if(!c||!l)return;let u=c.getAttribute("visible"),h=c.getAttribute("lastVisible"),p=c.getAttribute("position"),m=c.getAttribute("charData"),g=c.getAttribute("lastPosition"),v=c.getAttribute("lastColor"),y=c.getAttribute("lastBg"),_=c.getAttribute("animShake"),S=c.getAttribute("animBounce");if(!u||u.count!==l.length){u=new Jn(new Float32Array(l.length),1),h=new Jn(new Float32Array(l.length),1),p=new Jn(new Float32Array(l.length*3),3),m=new Jn(new Float32Array(l.length*4),4),g=new Jn(new Float32Array(l.length*3),3),v=new Jn(new Float32Array(l.length*2),2),y=new Jn(new Float32Array(l.length*2),2),_=new Jn(new Float32Array(l.length*2),2),S=new Jn(new Float32Array(l.length*2),2);for(let E=0;E{if(!e||!r.current)return;const c=Math.round(o/If),l=Math.round(a/Of);s.uniforms.rows.value=l-1,s.uniforms.step.value.x=1/c,s.uniforms.step.value.y=1/l,s.clipping=n.length>0,s.clippingPlanes=n,s.needsUpdate=!0},[e,s,o,a,n]),ve.jsx("points",{frustumCulled:!1,material:s,children:ve.jsx("bufferGeometry",{ref:r})})}const zce=Fy();function h3({width:t,height:e,char:n,color:r,bg:i}){const s=a3(zce),o=Dy(),[a]=Ne.useState(()=>kce()),c=Ne.useRef(null),{width:l=0,height:u=0}=(s==null?void 0:s.image)??{};return Ne.useEffect(()=>{t===0||e===0||(a.uniforms.data.value=Cce(t,e))},[a.uniforms.data,t,e]),Ne.useEffect(()=>{t===0||e===0||Mce(a.uniforms.data.value,t,e,n,r,i)},[a.uniforms.data.value,t,e,n,r,i]),Ne.useEffect(()=>{t===0||e===0||!c.current||!s||(u3(c.current,t,e),a.uniforms.size.value.x=1/t,a.uniforms.size.value.y=1/e,a.uniforms.step.value.x=1/Math.round(l/If),a.uniforms.step.value.y=1/Math.round(u/Of),a.clipping=o.length>0,a.clippingPlanes=o,a.needsUpdate=!0)},[s,a,t,e,l,u,o]),ve.jsx("mesh",{material:a,children:ve.jsx("bufferGeometry",{ref:c})})}function Vce({id:t,z:e}){const n=os(Yl(r=>r.gadget.layers.find(i=>i.id===t)));switch(n==null?void 0:n.type){default:case op.BLANK:return null;case op.TILES:return ve.jsx("group",{position:[0,0,e],children:ve.jsx(h3,{width:n.width,height:n.height,char:[...n.char],color:[...n.color],bg:[...n.bg]})},n.id);case op.SPRITES:return ve.jsx("group",{position:[0,0,e],children:ve.jsx(Bce,{sprites:[...n.sprites]})},n.id);case op.DITHER:return ve.jsx("group",{position:[0,0,e],children:ve.jsx(By,{width:n.width,height:n.height,alphas:[...n.alphas]})},n.id)}}var MA={};Object.defineProperty(MA,"__esModule",{value:!0});var f3=MA.GamepadHelper=void 0;const Yn=class Yn{static getButtonValue(e,n){var r,i;return(i=(r=Yn.gamepads[e])==null?void 0:r.buttons[n])==null?void 0:i.value}static getAxisValue(e,n){var r;return(r=Yn.gamepads[e])==null?void 0:r.axes[n]}static update(){Yn.checkForNewGamepads(),!(!Yn.gamepads||Object.keys(Yn.gamepads).length<1)&&(Yn.gamepadsLastUpdate&&Object.keys(Yn.gamepadsLastUpdate).length>0&&Object.values(Yn.gamepads).forEach(e=>{var n;for(let r=0;r1;m&&(p=p.slice(0,-1));var g=RA(p),v=SS[g];if(p.length>1&&!v&&!d3[p]&&!CA[g])throw new TypeError('Unknown modifier: "'+p+'"');(s===1||!v)&&(n?r.key=g:r.which=g3(p)),v&&(r[v]=m?null:!0)}}catch(y){c=!0,l=y}finally{try{!a&&u.return&&u.return()}finally{if(c)throw l}}return r}function m3(t,e){for(var n in t){var r=t[n],i=void 0;if(r!=null&&(n==="key"&&e.key!=null?i=e.key.toLowerCase():n==="which"?i=r===91&&e.which===93?91:e.which:i=e[n],!(i==null&&r===!1)&&i!==r))return!1}return!0}function g3(t){t=RA(t);var e=CA[t]||t.toUpperCase().charCodeAt(0);return e}function RA(t){return t=t.toLowerCase(),t=d3[t]||t,t}var jce=Jc.default=zy;Jc.isHotkey=zy;Jc.isCodeHotkey=Gce;Jc.isKeyHotkey=Wce;Jc.parseHotkey=p3;Jc.compareHotkey=m3;Jc.toKeyCode=g3;Jc.toKeyName=RA;function _3(t){return{all:t=t||new Map,on:function(e,n){var r=t.get(e);r?r.push(n):t.set(e,[n])},off:function(e,n){var r=t.get(e);r&&(n?r.splice(r.indexOf(n)>>>0,1):t.set(e,[]))},emit:function(e,n){var r=t.get(e);r&&r.slice().map(function(i){i(n)}),(r=t.get("*"))&&r.slice().map(function(i){i(e,n)})}}}const nd=navigator.userAgent.includes("Mac"),$ce=nd?"cmd":"ctrl",ma={[Ue.NONE]:!1,[Ue.ALT]:!1,[Ue.CTRL]:!1,[Ue.SHIFT]:!1,[Ue.MOVE_UP]:!1,[Ue.MOVE_DOWN]:!1,[Ue.MOVE_LEFT]:!1,[Ue.MOVE_RIGHT]:!1,[Ue.OK_BUTTON]:!1,[Ue.CANCEL_BUTTON]:!1,[Ue.MENU_BUTTON]:!1,[Ue.SHOOT_UP]:!1,[Ue.SHOOT_DOWN]:!1,[Ue.SHOOT_LEFT]:!1,[Ue.SHOOT_RIGHT]:!1};let S_=0,Rk=performance.now();const Nk=250;function Qi(t){ma[t]||(S_=0,y3(t,{alt:ma[Ue.ALT],ctrl:ma[Ue.CTRL],shift:ma[Ue.SHIFT]})),ma[t]=!0}function es(t){ma[t]=!1}const fa={root:_3(),ignorehotkeys:!1},v3=Ne.createContext(fa.root);function Vy(t){return{alt:t.altKey,ctrl:nd?t.metaKey:t.ctrlKey,shift:t.shiftKey}}function y3(t,e){fa.root.emit(Ue[t],e)}document.addEventListener("keydown",t=>{const e=$t(t.key),n=Vy(t);switch(e){case"s":n.ctrl&&Hv("tape","#save",rv()),t.preventDefault();break;case"v":case"r":n.ctrl||t.preventDefault();break;case"i":!nd&&n.shift&&n.ctrl||t.preventDefault();break;case"dead":nd&&n.alt&&n.ctrl||t.preventDefault();break;case"alt":case"meta":case"shift":case"control":break;default:t.preventDefault();break}switch(n.alt?Qi(Ue.ALT):es(Ue.ALT),n.ctrl?Qi(Ue.CTRL):es(Ue.CTRL),n.shift?Qi(Ue.SHIFT):es(Ue.SHIFT),e){case"arrowleft":Qi(Ue.MOVE_LEFT);break;case"arrowright":Qi(Ue.MOVE_RIGHT);break;case"arrowup":Qi(Ue.MOVE_UP);break;case"arrowdown":Qi(Ue.MOVE_DOWN);break;case"enter":Qi(Ue.OK_BUTTON);break;case"esc":case"escape":Qi(Ue.CANCEL_BUTTON);break;case"tab":Qi(Ue.MENU_BUTTON);break}fa.root.emit("keydown",t)},{capture:!0});document.addEventListener("keyup",t=>{const e=$t(t.key),n=Vy(t);switch(n.alt?Qi(Ue.ALT):es(Ue.ALT),n.ctrl?Qi(Ue.CTRL):es(Ue.CTRL),n.shift?Qi(Ue.SHIFT):es(Ue.SHIFT),e){case"arrowleft":es(Ue.MOVE_LEFT);break;case"arrowright":es(Ue.MOVE_RIGHT);break;case"arrowup":es(Ue.MOVE_UP);break;case"arrowdown":es(Ue.MOVE_DOWN);break;case"enter":es(Ue.OK_BUTTON);break;case"esc":case"escape":es(Ue.CANCEL_BUTTON);break;case"tab":es(Ue.MENU_BUTTON);break}},{capture:!0});const qce=0,Xce=1,Kce=2,Yce=3,Zce=4,Jce=5,Qce=6,ele=7,tle=9,nle=12,rle=13,ile=14,sle=15,x3={[qce]:Ue.OK_BUTTON,[Xce]:Ue.CANCEL_BUTTON,[Kce]:Ue.OK_BUTTON,[Yce]:Ue.CANCEL_BUTTON,[Zce]:Ue.ALT,[Jce]:Ue.ALT,[Qce]:Ue.CTRL,[ele]:Ue.CTRL,[tle]:Ue.MENU_BUTTON,[nle]:Ue.MOVE_UP,[rle]:Ue.MOVE_DOWN,[ile]:Ue.MOVE_LEFT,[sle]:Ue.MOVE_RIGHT};document.addEventListener("gamepadbuttondown",t=>{Qi(x3[t.detail.button])});document.addEventListener("gamepadbuttonup",t=>{es(x3[t.detail.button])});function S3(){const t=performance.now(),e=t-Rk;if(S_+=e,S_>=Nk){S_%=Nk;const n={alt:!!ma[Ue.ALT],ctrl:!!ma[Ue.CTRL],shift:!!ma[Ue.SHIFT]};[Ue.MOVE_UP,Ue.MOVE_DOWN,Ue.MOVE_LEFT,Ue.MOVE_RIGHT,Ue.OK_BUTTON,Ue.CANCEL_BUTTON,Ue.MENU_BUTTON,Ue.SHOOT_UP,Ue.SHOOT_DOWN,Ue.SHOOT_LEFT,Ue.SHOOT_RIGHT].forEach(i=>{ma[i]&&y3(i,n)})}Rk=t,f3.update(),setTimeout(S3,1)}S3();const kk="keyup";function xp({hotkey:t,children:e}){return Ne.useEffect(()=>{const n=jce(t,{byKey:!0});function r(i){fa.ignorehotkeys===!1&&n(i)&&e()}return document.addEventListener(kk,r,!1),()=>document.removeEventListener(kk,r,!1)},[t,e]),null}function gs(t){const e=Ne.useContext(v3);return Ne.useEffect(()=>{const n=Object.entries(t);return n.forEach(([r,i])=>e.on(r,i)),()=>{n.forEach(([r,i])=>e.off(r,i))}},[e,t]),null}function Im({blockhotkeys:t,children:e}){const[n]=Ne.useState(()=>_3());return Ne.useEffect(()=>{const r=fa.root,i=fa.ignorehotkeys;return fa.root=n,fa.ignorehotkeys=!!t,()=>{fa.root=r,fa.ignorehotkeys=i}},[n,t]),ve.jsx(v3.Provider,{value:n,children:e})}const ole=new St(0,0);function _u(t,e,n){let r=0;n.alt&&(r|=QU),n.ctrl&&(r|=e3),n.shift&&(r|=t3),L9("framed",e,r,t)}function ale({width:t,height:e}){const n=t*as,r=e*Hi,i=Ne.useRef(null);zv((a,c)=>{const{current:l}=i;if(!l)return;const u=tce(os.getState().gadget.layers),h=u.width*as*u.viewscale,p=h-n,m=u.height*Hi*u.viewscale,g=m-r,v=Math.round(Math.min(n,r)*.3333),y=-u.focusx*as*u.viewscale,_=n*.5+y,S=-u.focusy*Hi*u.viewscale,E=r*.5+S,b=h=v){const O=M<0?-v:v;l.userData.focus.x=Math.round(b-O)}}if(g<0)l.userData.focus.y=N;else{const M=l.position.y-N;if(Math.abs(M)>=v){const O=M<0?-v:v;l.userData.focus.y=Math.round(N-O*.5)}}const R=6;l.position.x+=(l.userData.focus.x-l.position.x)*c*R,l.position.y+=(l.userData.focus.y-l.position.y)*c*R,p>=0&&(l.position.x=Cn(l.position.x,-p,0)),g>=0&&(l.position.y=Cn(l.position.y,-g,0))});const s=os(a=>a.gadget.player);os(a=>a.gadget.layers.length);const{layers:o}=os.getState().gadget;return ve.jsxs(ve.Fragment,{children:[ve.jsx(gs,{MOVE_LEFT:a=>_u(s,Ue.MOVE_LEFT,a),MOVE_RIGHT:a=>_u(s,Ue.MOVE_RIGHT,a),MOVE_UP:a=>_u(s,Ue.MOVE_UP,a),MOVE_DOWN:a=>_u(s,Ue.MOVE_DOWN,a),OK_BUTTON:a=>_u(s,Ue.OK_BUTTON,a),CANCEL_BUTTON:a=>_u(s,Ue.CANCEL_BUTTON,a),MENU_BUTTON:a=>_u(s,Ue.MENU_BUTTON,a)}),ve.jsx(sce,{width:n,height:r,children:ve.jsx("group",{ref:i,children:o.map((a,c)=>ve.jsx(Vce,{id:a.id,z:c*2},a.id))})})]})}function Rw(t){console&&console.error&&console.error(`Error: ${t}`)}function E3(t){console&&console.warn&&console.warn(`Warning: ${t}`)}function w3(t){const e=new Date().getTime(),n=t();return{time:new Date().getTime()-e,value:n}}function b3(t){function e(){}e.prototype=t;const n=new e;function r(){return typeof n.bar}return r(),r(),t}function cle(t){return lle(t)?t.LABEL:t.name}function lle(t){return ds(t.LABEL)&&t.LABEL!==""}class Va{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){this._definition=e}accept(e){e.visit(this),Tt(this.definition,n=>{n.accept(e)})}}class _s extends Va{constructor(e){super([]),this.idx=1,fs(this,zo(e,n=>n!==void 0))}set definition(e){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(e){e.visit(this)}}class Sd extends Va{constructor(e){super(e.definition),this.orgText="",fs(this,zo(e,n=>n!==void 0))}}class vs extends Va{constructor(e){super(e.definition),this.ignoreAmbiguities=!1,fs(this,zo(e,n=>n!==void 0))}}class hs extends Va{constructor(e){super(e.definition),this.idx=1,fs(this,zo(e,n=>n!==void 0))}}class Ha extends Va{constructor(e){super(e.definition),this.idx=1,fs(this,zo(e,n=>n!==void 0))}}class Ga extends Va{constructor(e){super(e.definition),this.idx=1,fs(this,zo(e,n=>n!==void 0))}}class Ur extends Va{constructor(e){super(e.definition),this.idx=1,fs(this,zo(e,n=>n!==void 0))}}class jo extends Va{constructor(e){super(e.definition),this.idx=1,fs(this,zo(e,n=>n!==void 0))}}class $o extends Va{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){super(e.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,fs(this,zo(e,n=>n!==void 0))}}let Qn=class{constructor(e){this.idx=1,fs(this,zo(e,n=>n!==void 0))}accept(e){e.visit(this)}};function ule(t){return ot(t,E_)}function E_(t){function e(n){return ot(n,E_)}if(t instanceof _s){const n={type:"NonTerminal",name:t.nonTerminalName,idx:t.idx};return ds(t.label)&&(n.label=t.label),n}else{if(t instanceof vs)return{type:"Alternative",definition:e(t.definition)};if(t instanceof hs)return{type:"Option",idx:t.idx,definition:e(t.definition)};if(t instanceof Ha)return{type:"RepetitionMandatory",idx:t.idx,definition:e(t.definition)};if(t instanceof Ga)return{type:"RepetitionMandatoryWithSeparator",idx:t.idx,separator:E_(new Qn({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof jo)return{type:"RepetitionWithSeparator",idx:t.idx,separator:E_(new Qn({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof Ur)return{type:"Repetition",idx:t.idx,definition:e(t.definition)};if(t instanceof $o)return{type:"Alternation",idx:t.idx,definition:e(t.definition)};if(t instanceof Qn){const n={type:"Terminal",name:t.terminalType.name,label:cle(t.terminalType),idx:t.idx};ds(t.label)&&(n.terminalLabel=t.label);const r=t.terminalType.PATTERN;return t.terminalType.PATTERN&&(n.pattern=Ic(r)?r.source:r),n}else{if(t instanceof Sd)return{type:"Rule",name:t.name,orgText:t.orgText,definition:e(t.definition)};throw Error("non exhaustive match")}}}class xh{visit(e){const n=e;switch(n.constructor){case _s:return this.visitNonTerminal(n);case vs:return this.visitAlternative(n);case hs:return this.visitOption(n);case Ha:return this.visitRepetitionMandatory(n);case Ga:return this.visitRepetitionMandatoryWithSeparator(n);case jo:return this.visitRepetitionWithSeparator(n);case Ur:return this.visitRepetition(n);case $o:return this.visitAlternation(n);case Qn:return this.visitTerminal(n);case Sd:return this.visitRule(n);default:throw Error("non exhaustive match")}}visitNonTerminal(e){}visitAlternative(e){}visitOption(e){}visitRepetition(e){}visitRepetitionMandatory(e){}visitRepetitionMandatoryWithSeparator(e){}visitRepetitionWithSeparator(e){}visitAlternation(e){}visitTerminal(e){}visitRule(e){}}function hle(t){return t instanceof vs||t instanceof hs||t instanceof Ur||t instanceof Ha||t instanceof Ga||t instanceof jo||t instanceof Qn||t instanceof Sd}function pv(t,e=[]){return t instanceof hs||t instanceof Ur||t instanceof jo?!0:t instanceof $o?nT(t.definition,r=>pv(r,e)):t instanceof _s&&qi(e,t)?!1:t instanceof Va?(t instanceof _s&&e.push(t),No(t.definition,r=>pv(r,e))):!1}function fle(t){return t instanceof $o}function da(t){if(t instanceof _s)return"SUBRULE";if(t instanceof hs)return"OPTION";if(t instanceof $o)return"OR";if(t instanceof Ha)return"AT_LEAST_ONE";if(t instanceof Ga)return"AT_LEAST_ONE_SEP";if(t instanceof jo)return"MANY_SEP";if(t instanceof Ur)return"MANY";if(t instanceof Qn)return"CONSUME";throw Error("non exhaustive match")}class Hy{walk(e,n=[]){Tt(e.definition,(r,i)=>{const s=ci(e.definition,i+1);if(r instanceof _s)this.walkProdRef(r,s,n);else if(r instanceof Qn)this.walkTerminal(r,s,n);else if(r instanceof vs)this.walkFlat(r,s,n);else if(r instanceof hs)this.walkOption(r,s,n);else if(r instanceof Ha)this.walkAtLeastOne(r,s,n);else if(r instanceof Ga)this.walkAtLeastOneSep(r,s,n);else if(r instanceof jo)this.walkManySep(r,s,n);else if(r instanceof Ur)this.walkMany(r,s,n);else if(r instanceof $o)this.walkOr(r,s,n);else throw Error("non exhaustive match")})}walkTerminal(e,n,r){}walkProdRef(e,n,r){}walkFlat(e,n,r){const i=n.concat(r);this.walk(e,i)}walkOption(e,n,r){const i=n.concat(r);this.walk(e,i)}walkAtLeastOne(e,n,r){const i=[new hs({definition:e.definition})].concat(n,r);this.walk(e,i)}walkAtLeastOneSep(e,n,r){const i=Ik(e,n,r);this.walk(e,i)}walkMany(e,n,r){const i=[new hs({definition:e.definition})].concat(n,r);this.walk(e,i)}walkManySep(e,n,r){const i=Ik(e,n,r);this.walk(e,i)}walkOr(e,n,r){const i=n.concat(r);Tt(e.definition,s=>{const o=new vs({definition:[s]});this.walk(o,i)})}}function Ik(t,e,n){return[new hs({definition:[new Qn({terminalType:t.separator})].concat(t.definition)})].concat(e,n)}function Om(t){if(t instanceof _s)return Om(t.referencedRule);if(t instanceof Qn)return mle(t);if(hle(t))return dle(t);if(fle(t))return ple(t);throw Error("non exhaustive match")}function dle(t){let e=[];const n=t.definition;let r=0,i=n.length>r,s,o=!0;for(;i&&o;)s=n[r],o=pv(s),e=e.concat(Om(s)),r=r+1,i=n.length>r;return ty(e)}function ple(t){const e=ot(t.definition,n=>Om(n));return ty(ls(e))}function mle(t){return[t.terminalType]}const T3="_~IN~_";class gle extends Hy{constructor(e){super(),this.topProd=e,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(e,n,r){}walkProdRef(e,n,r){const i=vle(e.referencedRule,e.idx)+this.topProd.name,s=n.concat(r),o=new vs({definition:s}),a=Om(o);this.follows[i]=a}}function _le(t){const e={};return Tt(t,n=>{const r=new gle(n).startWalking();fs(e,r)}),e}function vle(t,e){return t.name+e+T3}function Mt(t){return t.charCodeAt(0)}function ES(t,e){Array.isArray(t)?t.forEach(function(n){e.push(n)}):e.push(t)}function Zd(t,e){if(t[e]===!0)throw"duplicate flag "+e;t[e],t[e]=!0}function ef(t){if(t===void 0)throw Error("Internal Error - Should never get here!");return!0}function yle(){throw Error("Internal Error - Should never get here!")}function Ok(t){return t.type==="Character"}const mv=[];for(let t=Mt("0");t<=Mt("9");t++)mv.push(t);const gv=[Mt("_")].concat(mv);for(let t=Mt("a");t<=Mt("z");t++)gv.push(t);for(let t=Mt("A");t<=Mt("Z");t++)gv.push(t);const Lk=[Mt(" "),Mt("\f"),Mt(` -`),Mt("\r"),Mt(" "),Mt("\v"),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt(" "),Mt("\u2028"),Mt("\u2029"),Mt(" "),Mt(" "),Mt(" "),Mt("\uFEFF")],xle=/[0-9a-fA-F]/,P0=/[0-9]/,Sle=/[1-9]/;class Ele{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(e){this.idx=e.idx,this.input=e.input,this.groupIdx=e.groupIdx}pattern(e){this.idx=0,this.input=e,this.groupIdx=0,this.consumeChar("/");const n=this.disjunction();this.consumeChar("/");const r={type:"Flags",loc:{begin:this.idx,end:e.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":Zd(r,"global");break;case"i":Zd(r,"ignoreCase");break;case"m":Zd(r,"multiLine");break;case"u":Zd(r,"unicode");break;case"y":Zd(r,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:r,value:n,loc:this.loc(0)}}disjunction(){const e=[],n=this.idx;for(e.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),e.push(this.alternative());return{type:"Disjunction",value:e,loc:this.loc(n)}}alternative(){const e=[],n=this.idx;for(;this.isTerm();)e.push(this.term());return{type:"Alternative",value:e,loc:this.loc(n)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){const e=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(e)};case"$":return{type:"EndAnchor",loc:this.loc(e)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(e)};case"B":return{type:"NonWordBoundary",loc:this.loc(e)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let n;switch(this.popChar()){case"=":n="Lookahead";break;case"!":n="NegativeLookahead";break}ef(n);const r=this.disjunction();return this.consumeChar(")"),{type:n,value:r,loc:this.loc(e)}}return yle()}quantifier(e=!1){let n;const r=this.idx;switch(this.popChar()){case"*":n={atLeast:0,atMost:1/0};break;case"+":n={atLeast:1,atMost:1/0};break;case"?":n={atLeast:0,atMost:1};break;case"{":const i=this.integerIncludingZero();switch(this.popChar()){case"}":n={atLeast:i,atMost:i};break;case",":let s;this.isDigit()?(s=this.integerIncludingZero(),n={atLeast:i,atMost:s}):n={atLeast:i,atMost:1/0},this.consumeChar("}");break}if(e===!0&&n===void 0)return;ef(n);break}if(!(e===!0&&n===void 0)&&ef(n))return this.peekChar(0)==="?"?(this.consumeChar("?"),n.greedy=!1):n.greedy=!0,n.type="Quantifier",n.loc=this.loc(r),n}atom(){let e;const n=this.idx;switch(this.peekChar()){case".":e=this.dotAll();break;case"\\":e=this.atomEscape();break;case"[":e=this.characterClass();break;case"(":e=this.group();break}if(e===void 0&&this.isPatternCharacter()&&(e=this.patternCharacter()),ef(e))return e.loc=this.loc(n),this.isQuantifier()&&(e.quantifier=this.quantifier()),e}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[Mt(` -`),Mt("\r"),Mt("\u2028"),Mt("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let e,n=!1;switch(this.popChar()){case"d":e=mv;break;case"D":e=mv,n=!0;break;case"s":e=Lk;break;case"S":e=Lk,n=!0;break;case"w":e=gv;break;case"W":e=gv,n=!0;break}if(ef(e))return{type:"Set",value:e,complement:n}}controlEscapeAtom(){let e;switch(this.popChar()){case"f":e=Mt("\f");break;case"n":e=Mt(` -`);break;case"r":e=Mt("\r");break;case"t":e=Mt(" ");break;case"v":e=Mt("\v");break}if(ef(e))return{type:"Character",value:e}}controlLetterEscapeAtom(){this.consumeChar("c");const e=this.popChar();if(/[a-zA-Z]/.test(e)===!1)throw Error("Invalid ");return{type:"Character",value:e.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:Mt("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){const e=this.popChar();return{type:"Character",value:Mt(e)}}classPatternCharacterAtom(){switch(this.peekChar()){case` -`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:const e=this.popChar();return{type:"Character",value:Mt(e)}}}characterClass(){const e=[];let n=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),n=!0);this.isClassAtom();){const r=this.classAtom();if(r.type,Ok(r)&&this.isRangeDash()){this.consumeChar("-");const i=this.classAtom();if(i.type,Ok(i)){if(i.value=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(e){return{begin:e,end:this.idx}}}class NA{visitChildren(e){for(const n in e){const r=e[n];e.hasOwnProperty(n)&&(r.type!==void 0?this.visit(r):Array.isArray(r)&&r.forEach(i=>{this.visit(i)},this))}}visit(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e);break}this.visitChildren(e)}visitPattern(e){}visitFlags(e){}visitDisjunction(e){}visitAlternative(e){}visitStartAnchor(e){}visitEndAnchor(e){}visitWordBoundary(e){}visitNonWordBoundary(e){}visitLookahead(e){}visitNegativeLookahead(e){}visitCharacter(e){}visitSet(e){}visitGroup(e){}visitGroupBackReference(e){}visitQuantifier(e){}}let w_={};const wle=new Ele;function Gy(t){const e=t.toString();if(w_.hasOwnProperty(e))return w_[e];{const n=wle.pattern(e);return w_[e]=n,n}}function ble(){w_={}}const A3="Complement Sets are not supported for first char optimization",_v=`Unable to use "first char" lexer optimizations: -`;function Tle(t,e=!1){try{const n=Gy(t);return Nw(n.value,{},n.flags.ignoreCase)}catch(n){if(n.message===A3)e&&E3(`${_v} Unable to optimize: < ${t.toString()} > - Complement Sets cannot be automatically optimized. - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let r="";e&&(r=` - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),Rw(`${_v} - Failed parsing: < ${t.toString()} > - Using the @chevrotain/regexp-to-ast library - Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+r)}}return[]}function Nw(t,e,n){switch(t.type){case"Disjunction":for(let i=0;i{if(typeof c=="number")D0(c,e,n);else{const l=c;if(n===!0)for(let u=l.from;u<=l.to;u++)D0(u,e,n);else{for(let u=l.from;u<=l.to&&u=cp){const u=l.from>=cp?l.from:cp,h=l.to,p=Gl(u),m=Gl(h);for(let g=p;g<=m;g++)e[g]=g}}}});break;case"Group":Nw(o.value,e,n);break;default:throw Error("Non Exhaustive Match")}const a=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&kw(o)===!1||o.type!=="Group"&&a===!1)break}break;default:throw Error("non exhaustive match!")}return Rr(e)}function D0(t,e,n){const r=Gl(t);e[r]=r,n===!0&&Ale(t,e)}function Ale(t,e){const n=String.fromCharCode(t),r=n.toUpperCase();if(r!==n){const i=Gl(r.charCodeAt(0));e[i]=i}else{const i=n.toLowerCase();if(i!==n){const s=Gl(i.charCodeAt(0));e[s]=s}}}function Pk(t,e){return Wf(t.value,n=>{if(typeof n=="number")return qi(e,n);{const r=n;return Wf(e,i=>r.from<=i&&i<=r.to)!==void 0}})}function kw(t){const e=t.quantifier;return e&&e.atLeast===0?!0:t.value?un(t.value)?No(t.value,kw):kw(t.value):!1}class Mle extends NA{constructor(e){super(),this.targetCharCodes=e,this.found=!1}visitChildren(e){if(this.found!==!0){switch(e.type){case"Lookahead":this.visitLookahead(e);return;case"NegativeLookahead":this.visitNegativeLookahead(e);return}super.visitChildren(e)}}visitCharacter(e){qi(this.targetCharCodes,e.value)&&(this.found=!0)}visitSet(e){e.complement?Pk(e,this.targetCharCodes)===void 0&&(this.found=!0):Pk(e,this.targetCharCodes)!==void 0&&(this.found=!0)}}function kA(t,e){if(e instanceof RegExp){const n=Gy(e),r=new Mle(t);return r.visit(n),r.found}else return Wf(e,n=>qi(t,n.charCodeAt(0)))!==void 0}const sh="PATTERN",ap="defaultMode",U0="modes";let M3=typeof new RegExp("(?:)").sticky=="boolean";function Cle(t,e){e=tT(e,{useSticky:M3,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` -`],tracer:(S,E)=>E()});const n=e.tracer;n("initCharCodeToOptimizedIndexMap",()=>{Zle()});let r;n("Reject Lexer.NA",()=>{r=ey(t,S=>S[sh]===zr.NA)});let i=!1,s;n("Transform Patterns",()=>{i=!1,s=ot(r,S=>{const E=S[sh];if(Ic(E)){const b=E.source;return b.length===1&&b!=="^"&&b!=="$"&&b!=="."&&!E.ignoreCase?b:b.length===2&&b[0]==="\\"&&!qi(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],b[1])?b[1]:e.useSticky?Uk(E):Dk(E)}else{if(Hc(E))return i=!0,{exec:E};if(typeof E=="object")return i=!0,E;if(typeof E=="string"){if(E.length===1)return E;{const b=E.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),N=new RegExp(b);return e.useSticky?Uk(N):Dk(N)}}else throw Error("non exhaustive match")}})});let o,a,c,l,u;n("misc mapping",()=>{o=ot(r,S=>S.tokenTypeIdx),a=ot(r,S=>{const E=S.GROUP;if(E!==zr.SKIPPED){if(ds(E))return E;if(Oc(E))return!1;throw Error("non exhaustive match")}}),c=ot(r,S=>{const E=S.LONGER_ALT;if(E)return un(E)?ot(E,N=>K2(r,N)):[K2(r,E)]}),l=ot(r,S=>S.PUSH_MODE),u=ot(r,S=>wt(S,"POP_MODE"))});let h;n("Line Terminator Handling",()=>{const S=N3(e.lineTerminatorCharacters);h=ot(r,E=>!1),e.positionTracking!=="onlyOffset"&&(h=ot(r,E=>wt(E,"LINE_BREAKS")?!!E.LINE_BREAKS:R3(E,S)===!1&&kA(S,E.PATTERN)))});let p,m,g,v;n("Misc Mapping #2",()=>{p=ot(r,C3),m=ot(s,Xle),g=ps(r,(S,E)=>{const b=E.GROUP;return ds(b)&&b!==zr.SKIPPED&&(S[b]=[]),S},{}),v=ot(s,(S,E)=>({pattern:s[E],longerAlt:c[E],canLineTerminator:h[E],isCustom:p[E],short:m[E],group:a[E],push:l[E],pop:u[E],tokenTypeIdx:o[E],tokenType:r[E]}))});let y=!0,_=[];return e.safeMode||n("First Char Optimization",()=>{_=ps(r,(S,E,b)=>{if(typeof E.PATTERN=="string"){const N=E.PATTERN.charCodeAt(0),R=Gl(N);wS(S,R,v[b])}else if(un(E.START_CHARS_HINT)){let N;Tt(E.START_CHARS_HINT,R=>{const M=typeof R=="string"?R.charCodeAt(0):R,O=Gl(M);N!==O&&(N=O,wS(S,O,v[b]))})}else if(Ic(E.PATTERN))if(E.PATTERN.unicode)y=!1,e.ensureOptimizations&&Rw(`${_v} Unable to analyze < ${E.PATTERN.toString()} > pattern. - The regexp unicode flag is not currently supported by the regexp-to-ast library. - This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{const N=Tle(E.PATTERN,e.ensureOptimizations);Dn(N)&&(y=!1),Tt(N,R=>{wS(S,R,v[b])})}else e.ensureOptimizations&&Rw(`${_v} TokenType: <${E.name}> is using a custom token pattern without providing parameter. - This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),y=!1;return S},[])}),{emptyGroups:g,patternIdxToConfig:v,charCodeToPatternIdxToConfig:_,hasCustom:i,canBeOptimized:y}}function Rle(t,e){let n=[];const r=kle(t);n=n.concat(r.errors);const i=Ile(r.valid),s=i.valid;return n=n.concat(i.errors),n=n.concat(Nle(s)),n=n.concat(zle(s)),n=n.concat(Vle(s,e)),n=n.concat(Hle(s)),n}function Nle(t){let e=[];const n=fo(t,r=>Ic(r[sh]));return e=e.concat(Lle(n)),e=e.concat(Ule(n)),e=e.concat(Fle(n)),e=e.concat(Ble(n)),e=e.concat(Ple(n)),e}function kle(t){const e=fo(t,i=>!wt(i,sh)),n=ot(e,i=>({message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:sr.MISSING_PATTERN,tokenTypes:[i]})),r=Qv(t,e);return{errors:n,valid:r}}function Ile(t){const e=fo(t,i=>{const s=i[sh];return!Ic(s)&&!Hc(s)&&!wt(s,"exec")&&!ds(s)}),n=ot(e,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:sr.INVALID_PATTERN,tokenTypes:[i]})),r=Qv(t,e);return{errors:n,valid:r}}const Ole=/[^\\][$]/;function Lle(t){class e extends NA{constructor(){super(...arguments),this.found=!1}visitEndAnchor(s){this.found=!0}}const n=fo(t,i=>{const s=i.PATTERN;try{const o=Gy(s),a=new e;return a.visit(o),a.found}catch{return Ole.test(s.source)}});return ot(n,i=>({message:`Unexpected RegExp Anchor Error: - Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain end of input anchor '$' - See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:sr.EOI_ANCHOR_FOUND,tokenTypes:[i]}))}function Ple(t){const e=fo(t,r=>r.PATTERN.test(""));return ot(e,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' must not match an empty string",type:sr.EMPTY_MATCH_PATTERN,tokenTypes:[r]}))}const Dle=/[^\\[][\^]|^\^/;function Ule(t){class e extends NA{constructor(){super(...arguments),this.found=!1}visitStartAnchor(s){this.found=!0}}const n=fo(t,i=>{const s=i.PATTERN;try{const o=Gy(s),a=new e;return a.visit(o),a.found}catch{return Dle.test(s.source)}});return ot(n,i=>({message:`Unexpected RegExp Anchor Error: - Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain start of input anchor '^' - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:sr.SOI_ANCHOR_FOUND,tokenTypes:[i]}))}function Fle(t){const e=fo(t,r=>{const i=r[sh];return i instanceof RegExp&&(i.multiline||i.global)});return ot(e,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:sr.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[r]}))}function Ble(t){const e=[];let n=ot(t,s=>ps(t,(o,a)=>(s.PATTERN.source===a.PATTERN.source&&!qi(e,a)&&a.PATTERN!==zr.NA&&(e.push(a),o.push(a)),o),[]));n=sm(n);const r=fo(n,s=>s.length>1);return ot(r,s=>{const o=ot(s,c=>c.name);return{message:`The same RegExp pattern ->${Oo(s).PATTERN}<-has been used in all of the following Token Types: ${o.join(", ")} <-`,type:sr.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}})}function zle(t){const e=fo(t,r=>{if(!wt(r,"GROUP"))return!1;const i=r.GROUP;return i!==zr.SKIPPED&&i!==zr.NA&&!ds(i)});return ot(e,r=>({message:"Token Type: ->"+r.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:sr.INVALID_GROUP_TYPE_FOUND,tokenTypes:[r]}))}function Vle(t,e){const n=fo(t,i=>i.PUSH_MODE!==void 0&&!qi(e,i.PUSH_MODE));return ot(n,i=>({message:`Token Type: ->${i.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${i.PUSH_MODE}<-which does not exist`,type:sr.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}))}function Hle(t){const e=[],n=ps(t,(r,i,s)=>{const o=i.PATTERN;return o===zr.NA||(ds(o)?r.push({str:o,idx:s,tokenType:i}):Ic(o)&&Wle(o)&&r.push({str:o.source,idx:s,tokenType:i})),r},[]);return Tt(t,(r,i)=>{Tt(n,({str:s,idx:o,tokenType:a})=>{if(i${a.name}<- can never be matched. -Because it appears AFTER the Token Type ->${r.name}<-in the lexer's definition. -See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;e.push({message:c,type:sr.UNREACHABLE_PATTERN,tokenTypes:[r,a]})}})}),e}function Gle(t,e){if(Ic(e)){const n=e.exec(t);return n!==null&&n.index===0}else{if(Hc(e))return e(t,0,[],{});if(wt(e,"exec"))return e.exec(t,0,[],{});if(typeof e=="string")return e===t;throw Error("non exhaustive match")}}function Wle(t){return Wf([".","\\","[","]","|","^","$","(",")","?","*","+","{"],n=>t.source.indexOf(n)!==-1)===void 0}function Dk(t){const e=t.ignoreCase?"i":"";return new RegExp(`^(?:${t.source})`,e)}function Uk(t){const e=t.ignoreCase?"iy":"y";return new RegExp(`${t.source}`,e)}function jle(t,e,n){const r=[];return wt(t,ap)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+ap+`> property in its definition -`,type:sr.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),wt(t,U0)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+U0+`> property in its definition -`,type:sr.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),wt(t,U0)&&wt(t,ap)&&!wt(t.modes,t.defaultMode)&&r.push({message:`A MultiMode Lexer cannot be initialized with a ${ap}: <${t.defaultMode}>which does not exist -`,type:sr.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),wt(t,U0)&&Tt(t.modes,(i,s)=>{Tt(i,(o,a)=>{if(Oc(o))r.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${s}> at index: <${a}> -`,type:sr.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED});else if(wt(o,"LONGER_ALT")){const c=un(o.LONGER_ALT)?o.LONGER_ALT:[o.LONGER_ALT];Tt(c,l=>{!Oc(l)&&!qi(i,l)&&r.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${l.name}> on token <${o.name}> outside of mode <${s}> -`,type:sr.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),r}function $le(t,e,n){const r=[];let i=!1;const s=sm(ls(Rr(t.modes))),o=ey(s,c=>c[sh]===zr.NA),a=N3(n);return e&&Tt(o,c=>{const l=R3(c,a);if(l!==!1){const h={message:Yle(c,l),type:l.issue,tokenType:c};r.push(h)}else wt(c,"LINE_BREAKS")?c.LINE_BREAKS===!0&&(i=!0):kA(a,c.PATTERN)&&(i=!0)}),e&&!i&&r.push({message:`Warning: No LINE_BREAKS Found. - This Lexer has been defined to track line and column information, - But none of the Token Types can be identified as matching a line terminator. - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS - for details.`,type:sr.NO_LINE_BREAKS_FLAGS}),r}function qle(t){const e={},n=uo(t);return Tt(n,r=>{const i=t[r];if(un(i))e[r]=[];else throw Error("non exhaustive match")}),e}function C3(t){const e=t.PATTERN;if(Ic(e))return!1;if(Hc(e))return!0;if(wt(e,"exec"))return!0;if(ds(e))return!1;throw Error("non exhaustive match")}function Xle(t){return ds(t)&&t.length===1?t.charCodeAt(0):!1}const Kle={test:function(t){const e=t.length;for(let n=this.lastIndex;n Token Type - Root cause: ${e.errMsg}. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(e.issue===sr.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. - The problem is in the <${t.name}> Token Type - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function N3(t){return ot(t,n=>ds(n)?n.charCodeAt(0):n)}function wS(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}const cp=256;let b_=[];function Gl(t){return t255?255+~~(t/255):t}}function Lm(t,e){const n=t.tokenTypeIdx;return n===e.tokenTypeIdx?!0:e.isParent===!0&&e.categoryMatchesMap[n]===!0}function vv(t,e){return t.tokenTypeIdx===e.tokenTypeIdx}let Fk=1;const k3={};function Pm(t){const e=Jle(t);Qle(e),tue(e),eue(e),Tt(e,n=>{n.isParent=n.categoryMatches.length>0})}function Jle(t){let e=fi(t),n=t,r=!0;for(;r;){n=sm(ls(ot(n,s=>s.CATEGORIES)));const i=Qv(n,e);e=e.concat(i),Dn(i)?r=!1:n=i}return e}function Qle(t){Tt(t,e=>{O3(e)||(k3[Fk]=e,e.tokenTypeIdx=Fk++),Bk(e)&&!un(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),Bk(e)||(e.CATEGORIES=[]),nue(e)||(e.categoryMatches=[]),rue(e)||(e.categoryMatchesMap={})})}function eue(t){Tt(t,e=>{e.categoryMatches=[],Tt(e.categoryMatchesMap,(n,r)=>{e.categoryMatches.push(k3[r].tokenTypeIdx)})})}function tue(t){Tt(t,e=>{I3([],e)})}function I3(t,e){Tt(t,n=>{e.categoryMatchesMap[n.tokenTypeIdx]=!0}),Tt(e.CATEGORIES,n=>{const r=t.concat(e);qi(r,n)||I3(r,n)})}function O3(t){return wt(t,"tokenTypeIdx")}function Bk(t){return wt(t,"CATEGORIES")}function nue(t){return wt(t,"categoryMatches")}function rue(t){return wt(t,"categoryMatchesMap")}function iue(t){return wt(t,"tokenTypeIdx")}const sue={buildUnableToPopLexerModeMessage(t){return`Unable to pop Lexer Mode after encountering Token ->${t.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(t,e,n,r,i){return`unexpected character: ->${t.charAt(e)}<- at offset: ${e}, skipped ${n} characters.`}};var sr;(function(t){t[t.MISSING_PATTERN=0]="MISSING_PATTERN",t[t.INVALID_PATTERN=1]="INVALID_PATTERN",t[t.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",t[t.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",t[t.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",t[t.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",t[t.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",t[t.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",t[t.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",t[t.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",t[t.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",t[t.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",t[t.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",t[t.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",t[t.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",t[t.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",t[t.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",t[t.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(sr||(sr={}));const lp={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` -`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:sue,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(lp);class zr{constructor(e,n=lp){if(this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(i,s)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;const o=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${i}>`);const{time:a,value:c}=w3(s),l=a>10?console.warn:console.log;return this.traceInitIndent time: ${a}ms`),this.traceInitIndent--,c}else return s()},typeof n=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. -a boolean 2nd argument is no longer supported`);this.config=fs({},lp,n);const r=this.config.traceInitPerf;r===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof r=="number"&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let i,s=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===lp.lineTerminatorsPattern)this.config.lineTerminatorsPattern=Kle;else if(this.config.lineTerminatorCharacters===lp.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(n.safeMode&&n.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),un(e)?i={modes:{defaultMode:fi(e)},defaultMode:ap}:(s=!1,i=fi(e))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(jle(i,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat($le(i,this.trackStartLines,this.config.lineTerminatorCharacters))})),i.modes=i.modes?i.modes:{},Tt(i.modes,(a,c)=>{i.modes[c]=ey(a,l=>Oc(l))});const o=uo(i.modes);if(Tt(i.modes,(a,c)=>{this.TRACE_INIT(`Mode: <${c}> processing`,()=>{if(this.modes.push(c),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(Rle(a,o))}),Dn(this.lexerDefinitionErrors)){Pm(a);let l;this.TRACE_INIT("analyzeTokenTypes",()=>{l=Cle(a,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:n.positionTracking,ensureOptimizations:n.ensureOptimizations,safeMode:n.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[c]=l.patternIdxToConfig,this.charCodeToPatternIdxToConfig[c]=l.charCodeToPatternIdxToConfig,this.emptyGroups=fs({},this.emptyGroups,l.emptyGroups),this.hasCustom=l.hasCustom||this.hasCustom,this.canModeBeOptimized[c]=l.canBeOptimized}})}),this.defaultMode=i.defaultMode,!Dn(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){const c=ot(this.lexerDefinitionErrors,l=>l.message).join(`----------------------- -`);throw new Error(`Errors detected in definition of Lexer: -`+c)}Tt(this.lexerDefinitionWarning,a=>{E3(a.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(M3?(this.chopInput=Vf,this.match=this.matchWithTest):(this.updateLastIndex=Lr,this.match=this.matchWithExec),s&&(this.handleModes=Lr),this.trackStartLines===!1&&(this.computeNewColumn=Vf),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=Lr),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{const a=ps(this.canModeBeOptimized,(c,l,u)=>(l===!1&&c.push(u),c),[]);if(n.ensureOptimizations&&!Dn(a))throw Error(`Lexer Modes: < ${a.join(", ")} > cannot be optimized. - Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. - Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{ble()}),this.TRACE_INIT("toFastProperties",()=>{b3(this)})})}tokenize(e,n=this.defaultMode){if(!Dn(this.lexerDefinitionErrors)){const i=ot(this.lexerDefinitionErrors,s=>s.message).join(`----------------------- -`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: -`+i)}return this.tokenizeInternal(e,n)}tokenizeInternal(e,n){let r,i,s,o,a,c,l,u,h,p,m,g,v,y,_;const S=e,E=S.length;let b=0,N=0;const R=this.hasCustom?0:Math.floor(e.length/10),M=new Array(R),O=[];let C=this.trackStartLines?1:void 0,I=this.trackStartLines?1:void 0;const U=qle(this.emptyGroups),L=this.trackStartLines,P=this.config.lineTerminatorsPattern;let T=0,H=[],V=[];const B=[],z=[];Object.freeze(z);let W;function K(){return H}function j(we){const Ae=Gl(we),Ee=V[Ae];return Ee===void 0?z:Ee}const Y=we=>{if(B.length===1&&we.tokenType.PUSH_MODE===void 0){const Ae=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(we);O.push({offset:we.startOffset,line:we.startLine,column:we.startColumn,length:we.image.length,message:Ae})}else{B.pop();const Ae=Gf(B);H=this.patternIdxToConfig[Ae],V=this.charCodeToPatternIdxToConfig[Ae],T=H.length;const Ee=this.canModeBeOptimized[Ae]&&this.config.safeMode===!1;V&&Ee?W=j:W=K}};function ge(we){B.push(we),V=this.charCodeToPatternIdxToConfig[we],H=this.patternIdxToConfig[we],T=H.length,T=H.length;const Ae=this.canModeBeOptimized[we]&&this.config.safeMode===!1;V&&Ae?W=j:W=K}ge.call(this,n);let Q;const re=this.config.recoveryEnabled;for(;bc.length){c=o,l=u,Q=it;break}}}break}}if(c!==null){if(h=c.length,p=Q.group,p!==void 0&&(m=Q.tokenTypeIdx,g=this.createTokenInstance(c,b,m,Q.tokenType,C,I,h),this.handlePayload(g,l),p===!1?N=this.addToken(M,N,g):U[p].push(g)),e=this.chopInput(e,h),b=b+h,I=this.computeNewColumn(I,h),L===!0&&Q.canLineTerminator===!0){let Le=0,He,qe;P.lastIndex=0;do He=P.test(c),He===!0&&(qe=P.lastIndex-1,Le++);while(He===!0);Le!==0&&(C=C+Le,I=h-qe,this.updateTokenEndLineColumnLocation(g,p,qe,Le,C,I,h))}this.handleModes(Q,Y,ge,g)}else{const Le=b,He=C,qe=I;let it=re===!1;for(;it===!1&&b ${Sp(t)} <--`:`token of type --> ${t.name} <--`} but found --> '${e.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:t,ruleName:e}){return"Redundant input, expecting EOF but found: "+t.image},buildNoViableAltMessage({expectedPathsPerAlt:t,actual:e,previous:n,customUserDescription:r,ruleName:i}){const s="Expecting: ",a=` -but found: '`+Oo(e).image+"'";if(r)return s+r+a;{const c=ps(t,(p,m)=>p.concat(m),[]),l=ot(c,p=>`[${ot(p,m=>Sp(m)).join(", ")}]`),h=`one of these possible Token sequences: -${ot(l,(p,m)=>` ${m+1}. ${p}`).join(` -`)}`;return s+h+a}},buildEarlyExitMessage({expectedIterationPaths:t,actual:e,customUserDescription:n,ruleName:r}){const i="Expecting: ",o=` -but found: '`+Oo(e).image+"'";if(n)return i+n+o;{const c=`expecting at least one iteration which starts with one of these possible Token sequences:: - <${ot(t,l=>`[${ot(l,u=>Sp(u)).join(",")}]`).join(" ,")}>`;return i+c+o}}};Object.freeze(P3);const lue={buildRuleNotFoundError(t,e){return"Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+`<- -inside top level rule: ->`+t.name+"<-"}},Fu={buildDuplicateFoundError(t,e){function n(u){return u instanceof Qn?u.terminalType.name:u instanceof _s?u.nonTerminalName:""}const r=t.name,i=Oo(e),s=i.idx,o=da(i),a=n(i),c=s>0;let l=`->${o}${c?s:""}<- ${a?`with argument: ->${a}<-`:""} - appears more than once (${e.length} times) in the top level rule: ->${r}<-. - For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES - `;return l=l.replace(/[ \t]+/g," "),l=l.replace(/\s\s+/g,` -`),l},buildNamespaceConflictError(t){return`Namespace conflict found in grammar. -The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${t.name}>. -To resolve this make sure each Terminal and Non-Terminal names are unique -This is easy to accomplish by using the convention that Terminal names start with an uppercase letter -and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(t){const e=ot(t.prefixPath,i=>Sp(i)).join(", "),n=t.alternation.idx===0?"":t.alternation.idx;return`Ambiguous alternatives: <${t.ambiguityIndices.join(" ,")}> due to common lookahead prefix -in inside <${t.topLevelRule.name}> Rule, -<${e}> may appears as a prefix path in all these alternatives. -See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX -For Further details.`},buildAlternationAmbiguityError(t){const e=ot(t.prefixPath,i=>Sp(i)).join(", "),n=t.alternation.idx===0?"":t.alternation.idx;let r=`Ambiguous Alternatives Detected: <${t.ambiguityIndices.join(" ,")}> in inside <${t.topLevelRule.name}> Rule, -<${e}> may appears as a prefix path in all these alternatives. -`;return r=r+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES -For Further details.`,r},buildEmptyRepetitionError(t){let e=da(t.repetition);return t.repetition.idx!==0&&(e+=t.repetition.idx),`The repetition <${e}> within Rule <${t.topLevelRule.name}> can never consume any tokens. -This could lead to an infinite loop.`},buildTokenNameError(t){return"deprecated"},buildEmptyAlternationError(t){return`Ambiguous empty alternative: <${t.emptyChoiceIdx+1}> in inside <${t.topLevelRule.name}> Rule. -Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(t){return`An Alternation cannot have more than 256 alternatives: - inside <${t.topLevelRule.name}> Rule. - has ${t.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(t){const e=t.topLevelRule.name,n=ot(t.leftRecursionPath,s=>s.name),r=`${e} --> ${n.concat([e]).join(" --> ")}`;return`Left Recursion found in grammar. -rule: <${e}> can be invoked from itself (directly or indirectly) -without consuming any Tokens. The grammar path that causes this is: - ${r} - To fix this refactor your grammar to remove the left recursion. -see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(t){return"deprecated"},buildDuplicateRuleNameError(t){let e;return t.topLevelRule instanceof Sd?e=t.topLevelRule.name:e=t.topLevelRule,`Duplicate definition, rule: ->${e}<- is already defined in the grammar: ->${t.grammarName}<-`}};function uue(t,e){const n=new hue(t,e);return n.resolveRefs(),n.errors}class hue extends xh{constructor(e,n){super(),this.nameToTopRule=e,this.errMsgProvider=n,this.errors=[]}resolveRefs(){Tt(Rr(this.nameToTopRule),e=>{this.currTopLevel=e,e.accept(this)})}visitNonTerminal(e){const n=this.nameToTopRule[e.nonTerminalName];if(n)e.referencedRule=n;else{const r=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:r,type:Wi.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}}}class fue extends Hy{constructor(e,n){super(),this.topProd=e,this.path=n,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=fi(this.path.ruleStack).reverse(),this.occurrenceStack=fi(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(e,n=[]){this.found||super.walk(e,n)}walkProdRef(e,n,r){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){const i=n.concat(r);this.updateExpectedNext(),this.walk(e.referencedRule,i)}}updateExpectedNext(){Dn(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}}class due extends fue{constructor(e,n){super(e,n),this.path=n,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(e,n,r){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){const i=n.concat(r),s=new vs({definition:i});this.possibleTokTypes=Om(s),this.found=!0}}}class Wy extends Hy{constructor(e,n){super(),this.topRule=e,this.occurrence=n,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}}class pue extends Wy{walkMany(e,n,r){if(e.idx===this.occurrence){const i=Oo(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Qn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkMany(e,n,r)}}class Xk extends Wy{walkManySep(e,n,r){if(e.idx===this.occurrence){const i=Oo(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Qn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkManySep(e,n,r)}}class mue extends Wy{walkAtLeastOne(e,n,r){if(e.idx===this.occurrence){const i=Oo(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Qn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOne(e,n,r)}}class Kk extends Wy{walkAtLeastOneSep(e,n,r){if(e.idx===this.occurrence){const i=Oo(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof Qn&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOneSep(e,n,r)}}function Iw(t,e,n=[]){n=fi(n);let r=[],i=0;function s(a){return a.concat(ci(t,i+1))}function o(a){const c=Iw(s(a),e,n);return r.concat(c)}for(;n.length{Dn(c.definition)===!1&&(r=o(c.definition))}),r;if(a instanceof Qn)n.push(a.terminalType);else throw Error("non exhaustive match")}i++}return r.push({partialPath:n,suffixDef:ci(t,i)}),r}function D3(t,e,n,r){const i="EXIT_NONE_TERMINAL",s=[i],o="EXIT_ALTERNATIVE";let a=!1;const c=e.length,l=c-r-1,u=[],h=[];for(h.push({idx:-1,def:t,ruleStack:[],occurrenceStack:[]});!Dn(h);){const p=h.pop();if(p===o){a&&Gf(h).idx<=l&&h.pop();continue}const m=p.def,g=p.idx,v=p.ruleStack,y=p.occurrenceStack;if(Dn(m))continue;const _=m[0];if(_===i){const S={idx:g,def:ci(m),ruleStack:Rp(v),occurrenceStack:Rp(y)};h.push(S)}else if(_ instanceof Qn)if(g=0;S--){const E=_.definition[S],b={idx:g,def:E.definition.concat(ci(m)),ruleStack:v,occurrenceStack:y};h.push(b),h.push(o)}else if(_ instanceof vs)h.push({idx:g,def:_.definition.concat(ci(m)),ruleStack:v,occurrenceStack:y});else if(_ instanceof Sd)h.push(gue(_,g,v,y));else throw Error("non exhaustive match")}return u}function gue(t,e,n,r){const i=fi(n);i.push(t.name);const s=fi(r);return s.push(1),{idx:e,def:t.definition,ruleStack:i,occurrenceStack:s}}var ir;(function(t){t[t.OPTION=0]="OPTION",t[t.REPETITION=1]="REPETITION",t[t.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",t[t.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",t[t.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",t[t.ALTERNATION=5]="ALTERNATION"})(ir||(ir={}));function U3(t){if(t instanceof hs||t==="Option")return ir.OPTION;if(t instanceof Ur||t==="Repetition")return ir.REPETITION;if(t instanceof Ha||t==="RepetitionMandatory")return ir.REPETITION_MANDATORY;if(t instanceof Ga||t==="RepetitionMandatoryWithSeparator")return ir.REPETITION_MANDATORY_WITH_SEPARATOR;if(t instanceof jo||t==="RepetitionWithSeparator")return ir.REPETITION_WITH_SEPARATOR;if(t instanceof $o||t==="Alternation")return ir.ALTERNATION;throw Error("non exhaustive match")}function _ue(t,e,n,r,i,s){const o=IA(t,e,n),a=z3(o)?vv:Lm;return s(o,r,a,i)}function vue(t,e,n,r,i,s){const o=OA(t,e,i,n),a=z3(o)?vv:Lm;return s(o[0],a,r)}function yue(t,e,n,r){const i=t.length,s=No(t,o=>No(o,a=>a.length===1));if(e)return function(o){const a=ot(o,c=>c.GATE);for(let c=0;cls(c)),a=ps(o,(c,l,u)=>(Tt(l,h=>{wt(c,h.tokenTypeIdx)||(c[h.tokenTypeIdx]=u),Tt(h.categoryMatches,p=>{wt(c,p)||(c[p]=u)})}),c),{});return function(){const c=this.LA(1);return a[c.tokenTypeIdx]}}else return function(){for(let o=0;os.length===1),i=t.length;if(r&&!n){const s=ls(t);if(s.length===1&&Dn(s[0].categoryMatches)){const a=s[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===a}}else{const o=ps(s,(a,c,l)=>(a[c.tokenTypeIdx]=!0,Tt(c.categoryMatches,u=>{a[u]=!0}),a),[]);return function(){const a=this.LA(1);return o[a.tokenTypeIdx]===!0}}}else return function(){e:for(let s=0;sIw([o],1)),r=Yk(n.length),i=ot(n,o=>{const a={};return Tt(o,c=>{const l=bS(c.partialPath);Tt(l,u=>{a[u]=!0})}),a});let s=n;for(let o=1;o<=e;o++){const a=s;s=Yk(a.length);for(let c=0;c{const _=bS(y.partialPath);Tt(_,S=>{i[c][S]=!0})})}}}}return r}function IA(t,e,n,r){const i=new F3(t,ir.ALTERNATION,r);return e.accept(i),B3(i.result,n)}function OA(t,e,n,r){const i=new F3(t,n);e.accept(i);const s=i.result,a=new Sue(e,t,n).startWalking(),c=new vs({definition:s}),l=new vs({definition:a});return B3([c,l],r)}function Ow(t,e){e:for(let n=0;n{const i=e[r];return n===i||i.categoryMatchesMap[n.tokenTypeIdx]})}function z3(t){return No(t,e=>No(e,n=>No(n,r=>Dn(r.categoryMatches))))}function bue(t){const e=t.lookaheadStrategy.validate({rules:t.rules,tokenTypes:t.tokenTypes,grammarName:t.grammarName});return ot(e,n=>Object.assign({type:Wi.CUSTOM_LOOKAHEAD_VALIDATION},n))}function Tue(t,e,n,r){const i=io(t,c=>Aue(c,n)),s=Fue(t,e,n),o=io(t,c=>Lue(c,n)),a=io(t,c=>Rue(c,t,r,n));return i.concat(s,o,a)}function Aue(t,e){const n=new Cue;t.accept(n);const r=n.allProductions,i=hP(r,Mue),s=zo(i,a=>a.length>1);return ot(Rr(s),a=>{const c=Oo(a),l=e.buildDuplicateFoundError(t,a),u=da(c),h={message:l,type:Wi.DUPLICATE_PRODUCTIONS,ruleName:t.name,dslName:u,occurrence:c.idx},p=V3(c);return p&&(h.parameter=p),h})}function Mue(t){return`${da(t)}_#_${t.idx}_#_${V3(t)}`}function V3(t){return t instanceof Qn?t.terminalType.name:t instanceof _s?t.nonTerminalName:""}class Cue extends xh{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(e){this.allProductions.push(e)}visitOption(e){this.allProductions.push(e)}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}visitAlternation(e){this.allProductions.push(e)}visitTerminal(e){this.allProductions.push(e)}}function Rue(t,e,n,r){const i=[];if(ps(e,(o,a)=>a.name===t.name?o+1:o,0)>1){const o=r.buildDuplicateRuleNameError({topLevelRule:t,grammarName:n});i.push({message:o,type:Wi.DUPLICATE_RULE_NAME,ruleName:t.name})}return i}function Nue(t,e,n){const r=[];let i;return qi(e,t)||(i=`Invalid rule override, rule: ->${t}<- cannot be overridden in the grammar: ->${n}<-as it is not defined in any of the super grammars `,r.push({message:i,type:Wi.INVALID_RULE_OVERRIDE,ruleName:t})),r}function H3(t,e,n,r=[]){const i=[],s=T_(e.definition);if(Dn(s))return[];{const o=t.name;qi(s,t)&&i.push({message:n.buildLeftRecursionError({topLevelRule:t,leftRecursionPath:r}),type:Wi.LEFT_RECURSION,ruleName:o});const c=Qv(s,r.concat([t])),l=io(c,u=>{const h=fi(r);return h.push(u),H3(t,u,n,h)});return i.concat(l)}}function T_(t){let e=[];if(Dn(t))return e;const n=Oo(t);if(n instanceof _s)e.push(n.referencedRule);else if(n instanceof vs||n instanceof hs||n instanceof Ha||n instanceof Ga||n instanceof jo||n instanceof Ur)e=e.concat(T_(n.definition));else if(n instanceof $o)e=ls(ot(n.definition,s=>T_(s.definition)));else if(!(n instanceof Qn))throw Error("non exhaustive match");const r=pv(n),i=t.length>1;if(r&&i){const s=ci(t);return e.concat(T_(s))}else return e}class LA extends xh{constructor(){super(...arguments),this.alternations=[]}visitAlternation(e){this.alternations.push(e)}}function kue(t,e){const n=new LA;t.accept(n);const r=n.alternations;return io(r,s=>{const o=Rp(s.definition);return io(o,(a,c)=>{const l=D3([a],[],Lm,1);return Dn(l)?[{message:e.buildEmptyAlternationError({topLevelRule:t,alternation:s,emptyChoiceIdx:c}),type:Wi.NONE_LAST_EMPTY_ALT,ruleName:t.name,occurrence:s.idx,alternative:c+1}]:[]})})}function Iue(t,e,n){const r=new LA;t.accept(r);let i=r.alternations;return i=ey(i,o=>o.ignoreAmbiguities===!0),io(i,o=>{const a=o.idx,c=o.maxLookahead||e,l=IA(a,t,c,o),u=Due(l,o,t,n),h=Uue(l,o,t,n);return u.concat(h)})}class Oue extends xh{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}}function Lue(t,e){const n=new LA;t.accept(n);const r=n.alternations;return io(r,s=>s.definition.length>255?[{message:e.buildTooManyAlternativesError({topLevelRule:t,alternation:s}),type:Wi.TOO_MANY_ALTS,ruleName:t.name,occurrence:s.idx}]:[])}function Pue(t,e,n){const r=[];return Tt(t,i=>{const s=new Oue;i.accept(s);const o=s.allProductions;Tt(o,a=>{const c=U3(a),l=a.maxLookahead||e,u=a.idx,p=OA(u,i,c,l)[0];if(Dn(ls(p))){const m=n.buildEmptyRepetitionError({topLevelRule:i,repetition:a});r.push({message:m,type:Wi.NO_NON_EMPTY_LOOKAHEAD,ruleName:i.name})}})}),r}function Due(t,e,n,r){const i=[],s=ps(t,(a,c,l)=>(e.definition[l].ignoreAmbiguities===!0||Tt(c,u=>{const h=[l];Tt(t,(p,m)=>{l!==m&&Ow(p,u)&&e.definition[m].ignoreAmbiguities!==!0&&h.push(m)}),h.length>1&&!Ow(i,u)&&(i.push(u),a.push({alts:h,path:u}))}),a),[]);return ot(s,a=>{const c=ot(a.alts,u=>u+1);return{message:r.buildAlternationAmbiguityError({topLevelRule:n,alternation:e,ambiguityIndices:c,prefixPath:a.path}),type:Wi.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:e.idx,alternatives:a.alts}})}function Uue(t,e,n,r){const i=ps(t,(o,a,c)=>{const l=ot(a,u=>({idx:c,path:u}));return o.concat(l)},[]);return sm(io(i,o=>{if(e.definition[o.idx].ignoreAmbiguities===!0)return[];const c=o.idx,l=o.path,u=fo(i,p=>e.definition[p.idx].ignoreAmbiguities!==!0&&p.idx{const m=[p.idx+1,c+1],g=e.idx===0?"":e.idx;return{message:r.buildAlternationPrefixAmbiguityError({topLevelRule:n,alternation:e,ambiguityIndices:m,prefixPath:p.path}),type:Wi.AMBIGUOUS_PREFIX_ALTS,ruleName:n.name,occurrence:g,alternatives:m}})}))}function Fue(t,e,n){const r=[],i=ot(e,s=>s.name);return Tt(t,s=>{const o=s.name;if(qi(i,o)){const a=n.buildNamespaceConflictError(s);r.push({message:a,type:Wi.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:o})}}),r}function Bue(t){const e=tT(t,{errMsgProvider:lue}),n={};return Tt(t.rules,r=>{n[r.name]=r}),uue(n,e.errMsgProvider)}function zue(t){return t=tT(t,{errMsgProvider:Fu}),Tue(t.rules,t.tokenTypes,t.errMsgProvider,t.grammarName)}const G3="MismatchedTokenException",W3="NoViableAltException",j3="EarlyExitException",$3="NotAllInputParsedException",q3=[G3,W3,j3,$3];Object.freeze(q3);function yv(t){return qi(q3,t.name)}class jy extends Error{constructor(e,n){super(e),this.token=n,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class X3 extends jy{constructor(e,n,r){super(e,n),this.previousToken=r,this.name=G3}}class Vue extends jy{constructor(e,n,r){super(e,n),this.previousToken=r,this.name=W3}}class Hue extends jy{constructor(e,n){super(e,n),this.name=$3}}class Gue extends jy{constructor(e,n,r){super(e,n),this.previousToken=r,this.name=j3}}const TS={},K3="InRuleRecoveryException";class Wue extends Error{constructor(e){super(e),this.name=K3}}class jue{initRecoverable(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=wt(e,"recoveryEnabled")?e.recoveryEnabled:Dc.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=$ue)}getTokenToInsert(e){const n=Dm(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return n.isInsertedInRecovery=!0,n}canTokenTypeBeInsertedInRecovery(e){return!0}canTokenTypeBeDeletedInRecovery(e){return!0}tryInRepetitionRecovery(e,n,r,i){const s=this.findReSyncTokenType(),o=this.exportLexerState(),a=[];let c=!1;const l=this.LA(1);let u=this.LA(1);const h=()=>{const p=this.LA(0),m=this.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:l,previous:p,ruleName:this.getCurrRuleFullName()}),g=new X3(m,l,this.LA(0));g.resyncedTokens=Rp(a),this.SAVE_ERROR(g)};for(;!c;)if(this.tokenMatcher(u,i)){h();return}else if(r.call(this)){h(),e.apply(this,n);return}else this.tokenMatcher(u,s)?c=!0:(u=this.SKIP_TOKEN(),this.addToResyncTokens(u,a));this.importLexerState(o)}shouldInRepetitionRecoveryBeTried(e,n,r){return!(r===!1||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,n)))}getFollowsForInRuleRecovery(e,n){const r=this.getCurrentGrammarPath(e,n);return this.getNextPossibleTokenTypes(r)}tryInRuleRecovery(e,n){if(this.canRecoverWithSingleTokenInsertion(e,n))return this.getTokenToInsert(e);if(this.canRecoverWithSingleTokenDeletion(e)){const r=this.SKIP_TOKEN();return this.consumeToken(),r}throw new Wue("sad sad panda")}canPerformInRuleRecovery(e,n){return this.canRecoverWithSingleTokenInsertion(e,n)||this.canRecoverWithSingleTokenDeletion(e)}canRecoverWithSingleTokenInsertion(e,n){if(!this.canTokenTypeBeInsertedInRecovery(e)||Dn(n))return!1;const r=this.LA(1);return Wf(n,s=>this.tokenMatcher(r,s))!==void 0}canRecoverWithSingleTokenDeletion(e){return this.canTokenTypeBeDeletedInRecovery(e)?this.tokenMatcher(this.LA(2),e):!1}isInCurrentRuleReSyncSet(e){const n=this.getCurrFollowKey(),r=this.getFollowSetFromFollowKey(n);return qi(r,e)}findReSyncTokenType(){const e=this.flattenFollowSet();let n=this.LA(1),r=2;for(;;){const i=Wf(e,s=>cue(n,s));if(i!==void 0)return i;n=this.LA(r),r++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return TS;const e=this.getLastExplicitRuleShortName(),n=this.getLastExplicitRuleOccurrenceIndex(),r=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:n,inRule:this.shortRuleNameToFullName(r)}}buildFullFollowKeyStack(){const e=this.RULE_STACK,n=this.RULE_OCCURRENCE_STACK;return ot(e,(r,i)=>i===0?TS:{ruleName:this.shortRuleNameToFullName(r),idxInCallingRule:n[i],inRule:this.shortRuleNameToFullName(e[i-1])})}flattenFollowSet(){const e=ot(this.buildFullFollowKeyStack(),n=>this.getFollowSetFromFollowKey(n));return ls(e)}getFollowSetFromFollowKey(e){if(e===TS)return[oh];const n=e.ruleName+e.idxInCallingRule+T3+e.inRule;return this.resyncFollows[n]}addToResyncTokens(e,n){return this.tokenMatcher(e,oh)||n.push(e),n}reSyncTo(e){const n=[];let r=this.LA(1);for(;this.tokenMatcher(r,e)===!1;)r=this.SKIP_TOKEN(),this.addToResyncTokens(r,n);return Rp(n)}attemptInRepetitionRecovery(e,n,r,i,s,o,a){}getCurrentGrammarPath(e,n){const r=this.getHumanReadableRuleStack(),i=fi(this.RULE_OCCURRENCE_STACK);return{ruleStack:r,occurrenceStack:i,lastTok:e,lastTokOccurrence:n}}getHumanReadableRuleStack(){return ot(this.RULE_STACK,e=>this.shortRuleNameToFullName(e))}}function $ue(t,e,n,r,i,s,o){const a=this.getKeyForAutomaticLookahead(r,i);let c=this.firstAfterRepMap[a];if(c===void 0){const p=this.getCurrRuleFullName(),m=this.getGAstProductions()[p];c=new s(m,i).startWalking(),this.firstAfterRepMap[a]=c}let l=c.token,u=c.occurrence;const h=c.isEndOfRule;this.RULE_STACK.length===1&&h&&l===void 0&&(l=oh,u=1),!(l===void 0||u===void 0)&&this.shouldInRepetitionRecoveryBeTried(l,u,o)&&this.tryInRepetitionRecovery(t,e,n,l)}const que=4,Zl=8,Y3=1<H3(n,n,Fu))}validateEmptyOrAlternatives(e){return io(e,n=>kue(n,Fu))}validateAmbiguousAlternationAlternatives(e,n){return io(e,r=>Iue(r,n,Fu))}validateSomeNonEmptyLookaheadPath(e,n){return Pue(e,n,Fu)}buildLookaheadForAlternation(e){return _ue(e.prodOccurrence,e.rule,e.maxLookahead,e.hasPredicates,e.dynamicTokensEnabled,yue)}buildLookaheadForOptional(e){return vue(e.prodOccurrence,e.rule,e.maxLookahead,e.dynamicTokensEnabled,U3(e.prodType),xue)}}class Kue{initLooksAhead(e){this.dynamicTokensEnabled=wt(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:Dc.dynamicTokensEnabled,this.maxLookahead=wt(e,"maxLookahead")?e.maxLookahead:Dc.maxLookahead,this.lookaheadStrategy=wt(e,"lookaheadStrategy")?e.lookaheadStrategy:new Xue({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(e){Tt(e,n=>{this.TRACE_INIT(`${n.name} Rule Lookahead`,()=>{const{alternation:r,repetition:i,option:s,repetitionMandatory:o,repetitionMandatoryWithSeparator:a,repetitionWithSeparator:c}=Zue(n);Tt(r,l=>{const u=l.idx===0?"":l.idx;this.TRACE_INIT(`${da(l)}${u}`,()=>{const h=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:l.idx,rule:n,maxLookahead:l.maxLookahead||this.maxLookahead,hasPredicates:l.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),p=AS(this.fullRuleNameToShort[n.name],Y3,l.idx);this.setLaFuncCache(p,h)})}),Tt(i,l=>{this.computeLookaheadFunc(n,l.idx,Lw,"Repetition",l.maxLookahead,da(l))}),Tt(s,l=>{this.computeLookaheadFunc(n,l.idx,Z3,"Option",l.maxLookahead,da(l))}),Tt(o,l=>{this.computeLookaheadFunc(n,l.idx,Pw,"RepetitionMandatory",l.maxLookahead,da(l))}),Tt(a,l=>{this.computeLookaheadFunc(n,l.idx,A_,"RepetitionMandatoryWithSeparator",l.maxLookahead,da(l))}),Tt(c,l=>{this.computeLookaheadFunc(n,l.idx,Dw,"RepetitionWithSeparator",l.maxLookahead,da(l))})})})}computeLookaheadFunc(e,n,r,i,s,o){this.TRACE_INIT(`${o}${n===0?"":n}`,()=>{const a=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:n,rule:e,maxLookahead:s||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:i}),c=AS(this.fullRuleNameToShort[e.name],r,n);this.setLaFuncCache(c,a)})}getKeyForAutomaticLookahead(e,n){const r=this.getLastExplicitRuleShortName();return AS(r,e,n)}getLaFuncFromCache(e){return this.lookAheadFuncsCache.get(e)}setLaFuncCache(e,n){this.lookAheadFuncsCache.set(e,n)}}class Yue extends xh{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(e){this.dslMethods.option.push(e)}visitRepetitionWithSeparator(e){this.dslMethods.repetitionWithSeparator.push(e)}visitRepetitionMandatory(e){this.dslMethods.repetitionMandatory.push(e)}visitRepetitionMandatoryWithSeparator(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)}visitRepetition(e){this.dslMethods.repetition.push(e)}visitAlternation(e){this.dslMethods.alternation.push(e)}}const F0=new Yue;function Zue(t){F0.reset(),t.accept(F0);const e=F0.dslMethods;return F0.reset(),e}function Zk(t,e){isNaN(t.startOffset)===!0?(t.startOffset=e.startOffset,t.endOffset=e.endOffset):t.endOffseto.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: - ${s.join(` - -`).replace(/\n/g,` - `)}`)}}};return n.prototype=r,n.prototype.constructor=n,n._RULE_NAMES=e,n}function rhe(t,e,n){const r=function(){};J3(r,t+"BaseSemanticsWithDefaults");const i=Object.create(n.prototype);return Tt(e,s=>{i[s]=the}),r.prototype=i,r.prototype.constructor=r,r}var Uw;(function(t){t[t.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",t[t.MISSING_METHOD=1]="MISSING_METHOD"})(Uw||(Uw={}));function ihe(t,e){return she(t,e)}function she(t,e){const n=fo(e,i=>Hc(t[i])===!1),r=ot(n,i=>({msg:`Missing visitor method: <${i}> on ${t.constructor.name} CST Visitor.`,type:Uw.MISSING_METHOD,methodName:i}));return sm(r)}class ohe{initTreeBuilder(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=wt(e,"nodeLocationTracking")?e.nodeLocationTracking:Dc.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=Lr,this.cstFinallyStateUpdate=Lr,this.cstPostTerminal=Lr,this.cstPostNonTerminal=Lr,this.cstPostRule=Lr;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Jk,this.setNodeLocationFromNode=Jk,this.cstPostRule=Lr,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=Lr,this.setNodeLocationFromNode=Lr,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Zk,this.setNodeLocationFromNode=Zk,this.cstPostRule=Lr,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=Lr,this.setNodeLocationFromNode=Lr,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=Lr,this.setNodeLocationFromNode=Lr,this.cstPostRule=Lr,this.setInitialNodeLocation=Lr;else throw Error(`Invalid config option: "${e.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(e){e.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(e){const n=this.LA(1);e.location={startOffset:n.startOffset,startLine:n.startLine,startColumn:n.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(e){const n={name:e,children:Object.create(null)};this.setInitialNodeLocation(n),this.CST_STACK.push(n)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(e){const n=this.LA(0),r=e.location;r.startOffset<=n.startOffset?(r.endOffset=n.endOffset,r.endLine=n.endLine,r.endColumn=n.endColumn):(r.startOffset=NaN,r.startLine=NaN,r.startColumn=NaN)}cstPostRuleOnlyOffset(e){const n=this.LA(0),r=e.location;r.startOffset<=n.startOffset?r.endOffset=n.endOffset:r.startOffset=NaN}cstPostTerminal(e,n){const r=this.CST_STACK[this.CST_STACK.length-1];Jue(r,n,e),this.setNodeLocationFromToken(r.location,n)}cstPostNonTerminal(e,n){const r=this.CST_STACK[this.CST_STACK.length-1];Que(r,n,e),this.setNodeLocationFromNode(r.location,e.location)}getBaseCstVisitorConstructor(){if(Oc(this.baseCstVisitorConstructor)){const e=nhe(this.className,uo(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(Oc(this.baseCstVisitorWithDefaultsConstructor)){const e=rhe(this.className,uo(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){const e=this.RULE_STACK;return e[e.length-1]}getPreviousExplicitRuleShortName(){const e=this.RULE_STACK;return e[e.length-2]}getLastExplicitRuleOccurrenceIndex(){const e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]}}class ahe{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(e){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):Sv}LA(e){const n=this.currIdx+e;return n<0||this.tokVectorLength<=n?Sv:this.tokVector[n]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(e){this.currIdx=e}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}}class che{ACTION(e){return e.call(this)}consume(e,n,r){return this.consumeInternal(n,e,r)}subrule(e,n,r){return this.subruleInternal(n,e,r)}option(e,n){return this.optionInternal(n,e)}or(e,n){return this.orInternal(n,e)}many(e,n){return this.manyInternal(e,n)}atLeastOne(e,n){return this.atLeastOneInternal(e,n)}CONSUME(e,n){return this.consumeInternal(e,0,n)}CONSUME1(e,n){return this.consumeInternal(e,1,n)}CONSUME2(e,n){return this.consumeInternal(e,2,n)}CONSUME3(e,n){return this.consumeInternal(e,3,n)}CONSUME4(e,n){return this.consumeInternal(e,4,n)}CONSUME5(e,n){return this.consumeInternal(e,5,n)}CONSUME6(e,n){return this.consumeInternal(e,6,n)}CONSUME7(e,n){return this.consumeInternal(e,7,n)}CONSUME8(e,n){return this.consumeInternal(e,8,n)}CONSUME9(e,n){return this.consumeInternal(e,9,n)}SUBRULE(e,n){return this.subruleInternal(e,0,n)}SUBRULE1(e,n){return this.subruleInternal(e,1,n)}SUBRULE2(e,n){return this.subruleInternal(e,2,n)}SUBRULE3(e,n){return this.subruleInternal(e,3,n)}SUBRULE4(e,n){return this.subruleInternal(e,4,n)}SUBRULE5(e,n){return this.subruleInternal(e,5,n)}SUBRULE6(e,n){return this.subruleInternal(e,6,n)}SUBRULE7(e,n){return this.subruleInternal(e,7,n)}SUBRULE8(e,n){return this.subruleInternal(e,8,n)}SUBRULE9(e,n){return this.subruleInternal(e,9,n)}OPTION(e){return this.optionInternal(e,0)}OPTION1(e){return this.optionInternal(e,1)}OPTION2(e){return this.optionInternal(e,2)}OPTION3(e){return this.optionInternal(e,3)}OPTION4(e){return this.optionInternal(e,4)}OPTION5(e){return this.optionInternal(e,5)}OPTION6(e){return this.optionInternal(e,6)}OPTION7(e){return this.optionInternal(e,7)}OPTION8(e){return this.optionInternal(e,8)}OPTION9(e){return this.optionInternal(e,9)}OR(e){return this.orInternal(e,0)}OR1(e){return this.orInternal(e,1)}OR2(e){return this.orInternal(e,2)}OR3(e){return this.orInternal(e,3)}OR4(e){return this.orInternal(e,4)}OR5(e){return this.orInternal(e,5)}OR6(e){return this.orInternal(e,6)}OR7(e){return this.orInternal(e,7)}OR8(e){return this.orInternal(e,8)}OR9(e){return this.orInternal(e,9)}MANY(e){this.manyInternal(0,e)}MANY1(e){this.manyInternal(1,e)}MANY2(e){this.manyInternal(2,e)}MANY3(e){this.manyInternal(3,e)}MANY4(e){this.manyInternal(4,e)}MANY5(e){this.manyInternal(5,e)}MANY6(e){this.manyInternal(6,e)}MANY7(e){this.manyInternal(7,e)}MANY8(e){this.manyInternal(8,e)}MANY9(e){this.manyInternal(9,e)}MANY_SEP(e){this.manySepFirstInternal(0,e)}MANY_SEP1(e){this.manySepFirstInternal(1,e)}MANY_SEP2(e){this.manySepFirstInternal(2,e)}MANY_SEP3(e){this.manySepFirstInternal(3,e)}MANY_SEP4(e){this.manySepFirstInternal(4,e)}MANY_SEP5(e){this.manySepFirstInternal(5,e)}MANY_SEP6(e){this.manySepFirstInternal(6,e)}MANY_SEP7(e){this.manySepFirstInternal(7,e)}MANY_SEP8(e){this.manySepFirstInternal(8,e)}MANY_SEP9(e){this.manySepFirstInternal(9,e)}AT_LEAST_ONE(e){this.atLeastOneInternal(0,e)}AT_LEAST_ONE1(e){return this.atLeastOneInternal(1,e)}AT_LEAST_ONE2(e){this.atLeastOneInternal(2,e)}AT_LEAST_ONE3(e){this.atLeastOneInternal(3,e)}AT_LEAST_ONE4(e){this.atLeastOneInternal(4,e)}AT_LEAST_ONE5(e){this.atLeastOneInternal(5,e)}AT_LEAST_ONE6(e){this.atLeastOneInternal(6,e)}AT_LEAST_ONE7(e){this.atLeastOneInternal(7,e)}AT_LEAST_ONE8(e){this.atLeastOneInternal(8,e)}AT_LEAST_ONE9(e){this.atLeastOneInternal(9,e)}AT_LEAST_ONE_SEP(e){this.atLeastOneSepFirstInternal(0,e)}AT_LEAST_ONE_SEP1(e){this.atLeastOneSepFirstInternal(1,e)}AT_LEAST_ONE_SEP2(e){this.atLeastOneSepFirstInternal(2,e)}AT_LEAST_ONE_SEP3(e){this.atLeastOneSepFirstInternal(3,e)}AT_LEAST_ONE_SEP4(e){this.atLeastOneSepFirstInternal(4,e)}AT_LEAST_ONE_SEP5(e){this.atLeastOneSepFirstInternal(5,e)}AT_LEAST_ONE_SEP6(e){this.atLeastOneSepFirstInternal(6,e)}AT_LEAST_ONE_SEP7(e){this.atLeastOneSepFirstInternal(7,e)}AT_LEAST_ONE_SEP8(e){this.atLeastOneSepFirstInternal(8,e)}AT_LEAST_ONE_SEP9(e){this.atLeastOneSepFirstInternal(9,e)}RULE(e,n,r=Ev){if(qi(this.definedRulesNames,e)){const o={message:Fu.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),type:Wi.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(o)}this.definedRulesNames.push(e);const i=this.defineRule(e,n,r);return this[e]=i,i}OVERRIDE_RULE(e,n,r=Ev){const i=Nue(e,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(i);const s=this.defineRule(e,n,r);return this[e]=s,s}BACKTRACK(e,n){return function(){this.isBackTrackingStack.push(1);const r=this.saveRecogState();try{return e.apply(this,n),!0}catch(i){if(yv(i))return!1;throw i}finally{this.reloadRecogState(r),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return ule(Rr(this.gastProductionsCache))}}class lhe{initRecognizerEngine(e,n){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=vv,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},wt(n,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 - For Further details.`);if(un(e)){if(Dn(e))throw Error(`A Token Vocabulary cannot be empty. - Note that the first argument for the parser constructor - is no longer a Token vector (since v4.0).`);if(typeof e[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 - For Further details.`)}if(un(e))this.tokensMap=ps(e,(s,o)=>(s[o.name]=o,s),{});else if(wt(e,"modes")&&No(ls(Rr(e.modes)),iue)){const s=ls(Rr(e.modes)),o=ty(s);this.tokensMap=ps(o,(a,c)=>(a[c.name]=c,a),{})}else if(lo(e))this.tokensMap=fi(e);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=oh;const r=wt(e,"modes")?ls(Rr(e.modes)):Rr(e),i=No(r,s=>Dn(s.categoryMatches));this.tokenMatcher=i?vv:Lm,Pm(Rr(this.tokensMap))}defineRule(e,n,r){if(this.selfAnalysisDone)throw Error(`Grammar rule <${e}> may not be defined after the 'performSelfAnalysis' method has been called' -Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);const i=wt(r,"resyncEnabled")?r.resyncEnabled:Ev.resyncEnabled,s=wt(r,"recoveryValueFunc")?r.recoveryValueFunc:Ev.recoveryValueFunc,o=this.ruleShortNameIdx<o.call(this)&&a.call(this)}}else s=e;if(i.call(this)===!0)return s.call(this)}atLeastOneInternal(e,n){const r=this.getKeyForAutomaticLookahead(Pw,e);return this.atLeastOneInternalLogic(e,n,r)}atLeastOneInternalLogic(e,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const o=n.GATE;if(o!==void 0){const a=i;i=()=>o.call(this)&&a.call(this)}}else s=n;if(i.call(this)===!0){let o=this.doSingleRepetition(s);for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s)}else throw this.raiseEarlyExitException(e,ir.REPETITION_MANDATORY,n.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[e,n],i,Pw,e,mue)}atLeastOneSepFirstInternal(e,n){const r=this.getKeyForAutomaticLookahead(A_,e);this.atLeastOneSepFirstInternalLogic(e,n,r)}atLeastOneSepFirstInternalLogic(e,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,a,i,Kk],a,A_,e,Kk)}else throw this.raiseEarlyExitException(e,ir.REPETITION_MANDATORY_WITH_SEPARATOR,n.ERR_MSG)}manyInternal(e,n){const r=this.getKeyForAutomaticLookahead(Lw,e);return this.manyInternalLogic(e,n,r)}manyInternalLogic(e,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const a=n.GATE;if(a!==void 0){const c=i;i=()=>a.call(this)&&c.call(this)}}else s=n;let o=!0;for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s);this.attemptInRepetitionRecovery(this.manyInternal,[e,n],i,Lw,e,pue,o)}manySepFirstInternal(e,n){const r=this.getKeyForAutomaticLookahead(Dw,e);this.manySepFirstInternalLogic(e,n,r)}manySepFirstInternalLogic(e,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,a,i,Xk],a,Dw,e,Xk)}}repetitionSepSecondInternal(e,n,r,i,s){for(;r();)this.CONSUME(n),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,n,r,i,s],r,A_,e,s)}doSingleRepetition(e){const n=this.getLexerPosition();return e.call(this),this.getLexerPosition()>n}orInternal(e,n){const r=this.getKeyForAutomaticLookahead(Y3,n),i=un(e)?e:e.DEF,o=this.getLaFuncFromCache(r).call(this,i);if(o!==void 0)return i[o].ALT.call(this);this.raiseNoAltException(n,e.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){const e=this.LA(1),n=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new Hue(n,e))}}subruleInternal(e,n,r){let i;try{const s=r!==void 0?r.ARGS:void 0;return this.subruleIdx=n,i=e.apply(this,s),this.cstPostNonTerminal(i,r!==void 0&&r.LABEL!==void 0?r.LABEL:e.ruleName),i}catch(s){throw this.subruleInternalError(s,r,e.ruleName)}}subruleInternalError(e,n,r){throw yv(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,n!==void 0&&n.LABEL!==void 0?n.LABEL:r),delete e.partialCstResult),e}consumeInternal(e,n,r){let i;try{const s=this.LA(1);this.tokenMatcher(s,e)===!0?(this.consumeToken(),i=s):this.consumeInternalError(e,s,r)}catch(s){i=this.consumeInternalRecovery(e,n,s)}return this.cstPostTerminal(r!==void 0&&r.LABEL!==void 0?r.LABEL:e.name,i),i}consumeInternalError(e,n,r){let i;const s=this.LA(0);throw r!==void 0&&r.ERR_MSG?i=r.ERR_MSG:i=this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:n,previous:s,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new X3(i,n,s))}consumeInternalRecovery(e,n,r){if(this.recoveryEnabled&&r.name==="MismatchedTokenException"&&!this.isBackTracking()){const i=this.getFollowsForInRuleRecovery(e,n);try{return this.tryInRuleRecovery(e,i)}catch(s){throw s.name===K3?r:s}}else throw r}saveRecogState(){const e=this.errors,n=fi(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:n,CST_STACK:this.CST_STACK}}reloadRecogState(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK}ruleInvocationStateUpdate(e,n,r){this.RULE_OCCURRENCE_STACK.push(r),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(n)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){const e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]}shortRuleNameToFullName(e){return this.shortRuleNameToFull[e]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),oh)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}}class uhe{initErrorHandler(e){this._errors=[],this.errorMessageProvider=wt(e,"errorMessageProvider")?e.errorMessageProvider:Dc.errorMessageProvider}SAVE_ERROR(e){if(yv(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:fi(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return fi(this._errors)}set errors(e){this._errors=e}raiseEarlyExitException(e,n,r){const i=this.getCurrRuleFullName(),s=this.getGAstProductions()[i],a=OA(e,s,n,this.maxLookahead)[0],c=[];for(let u=1;u<=this.maxLookahead;u++)c.push(this.LA(u));const l=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:c,previous:this.LA(0),customUserDescription:r,ruleName:i});throw this.SAVE_ERROR(new Gue(l,this.LA(1),this.LA(0)))}raiseNoAltException(e,n){const r=this.getCurrRuleFullName(),i=this.getGAstProductions()[r],s=IA(e,i,this.maxLookahead),o=[];for(let l=1;l<=this.maxLookahead;l++)o.push(this.LA(l));const a=this.LA(0),c=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:s,actual:o,previous:a,customUserDescription:n,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new Vue(c,this.LA(1),a))}}class hhe{initContentAssist(){}computeContentAssist(e,n){const r=this.gastProductionsCache[e];if(Oc(r))throw Error(`Rule ->${e}<- does not exist in this grammar.`);return D3([r],n,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(e){const n=Oo(e.ruleStack),i=this.getGAstProductions()[n];return new due(i,e).startWalking()}}const $y={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze($y);const Qk=!0,eI=Math.pow(2,Zl)-1,Q3=Fs({name:"RECORDING_PHASE_TOKEN",pattern:zr.NA});Pm([Q3]);const e4=Dm(Q3,`This IToken indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(e4);const fhe={name:`This CSTNode indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}};class dhe{initGastRecorder(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let e=0;e<10;e++){const n=e>0?e:"";this[`CONSUME${n}`]=function(r,i){return this.consumeInternalRecord(r,e,i)},this[`SUBRULE${n}`]=function(r,i){return this.subruleInternalRecord(r,e,i)},this[`OPTION${n}`]=function(r){return this.optionInternalRecord(r,e)},this[`OR${n}`]=function(r){return this.orInternalRecord(r,e)},this[`MANY${n}`]=function(r){this.manyInternalRecord(e,r)},this[`MANY_SEP${n}`]=function(r){this.manySepFirstInternalRecord(e,r)},this[`AT_LEAST_ONE${n}`]=function(r){this.atLeastOneInternalRecord(e,r)},this[`AT_LEAST_ONE_SEP${n}`]=function(r){this.atLeastOneSepFirstInternalRecord(e,r)}}this.consume=function(e,n,r){return this.consumeInternalRecord(n,e,r)},this.subrule=function(e,n,r){return this.subruleInternalRecord(n,e,r)},this.option=function(e,n){return this.optionInternalRecord(n,e)},this.or=function(e,n){return this.orInternalRecord(n,e)},this.many=function(e,n){this.manyInternalRecord(e,n)},this.atLeastOne=function(e,n){this.atLeastOneInternalRecord(e,n)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{const e=this;for(let n=0;n<10;n++){const r=n>0?n:"";delete e[`CONSUME${r}`],delete e[`SUBRULE${r}`],delete e[`OPTION${r}`],delete e[`OR${r}`],delete e[`MANY${r}`],delete e[`MANY_SEP${r}`],delete e[`AT_LEAST_ONE${r}`],delete e[`AT_LEAST_ONE_SEP${r}`]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA})}ACTION_RECORD(e){}BACKTRACK_RECORD(e,n){return()=>!0}LA_RECORD(e){return Sv}topLevelRuleRecord(e,n){try{const r=new Sd({definition:[],name:e});return r.name=e,this.recordingProdStack.push(r),n.call(this),this.recordingProdStack.pop(),r}catch(r){if(r.KNOWN_RECORDER_ERROR!==!0)try{r.message=r.message+` - This error was thrown during the "grammar recording phase" For more info see: - https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw r}throw r}}optionInternalRecord(e,n){return Jd.call(this,hs,e,n)}atLeastOneInternalRecord(e,n){Jd.call(this,Ha,n,e)}atLeastOneSepFirstInternalRecord(e,n){Jd.call(this,Ga,n,e,Qk)}manyInternalRecord(e,n){Jd.call(this,Ur,n,e)}manySepFirstInternalRecord(e,n){Jd.call(this,jo,n,e,Qk)}orInternalRecord(e,n){return phe.call(this,e,n)}subruleInternalRecord(e,n,r){if(xv(n),!e||wt(e,"ruleName")===!1){const a=new Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(e)}> - inside top level rule: <${this.recordingProdStack[0].name}>`);throw a.KNOWN_RECORDER_ERROR=!0,a}const i=Gf(this.recordingProdStack),s=e.ruleName,o=new _s({idx:n,nonTerminalName:s,label:r==null?void 0:r.LABEL,referencedRule:void 0});return i.definition.push(o),this.outputCst?fhe:$y}consumeInternalRecord(e,n,r){if(xv(n),!O3(e)){const o=new Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(e)}> - inside top level rule: <${this.recordingProdStack[0].name}>`);throw o.KNOWN_RECORDER_ERROR=!0,o}const i=Gf(this.recordingProdStack),s=new Qn({idx:n,terminalType:e,label:r==null?void 0:r.LABEL});return i.definition.push(s),e4}}function Jd(t,e,n,r=!1){xv(n);const i=Gf(this.recordingProdStack),s=Hc(e)?e:e.DEF,o=new t({definition:[],idx:n});return r&&(o.separator=e.SEP),wt(e,"MAX_LOOKAHEAD")&&(o.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(o),s.call(this),i.definition.push(o),this.recordingProdStack.pop(),$y}function phe(t,e){xv(e);const n=Gf(this.recordingProdStack),r=un(t)===!1,i=r===!1?t:t.DEF,s=new $o({definition:[],idx:e,ignoreAmbiguities:r&&t.IGNORE_AMBIGUITIES===!0});wt(t,"MAX_LOOKAHEAD")&&(s.maxLookahead=t.MAX_LOOKAHEAD);const o=nT(i,a=>Hc(a.GATE));return s.hasPredicates=o,n.definition.push(s),Tt(i,a=>{const c=new vs({definition:[]});s.definition.push(c),wt(a,"IGNORE_AMBIGUITIES")?c.ignoreAmbiguities=a.IGNORE_AMBIGUITIES:wt(a,"GATE")&&(c.ignoreAmbiguities=!0),this.recordingProdStack.push(c),a.ALT.call(this),this.recordingProdStack.pop()}),$y}function tI(t){return t===0?"":`${t}`}function xv(t){if(t<0||t>eI){const e=new Error(`Invalid DSL Method idx value: <${t}> - Idx value must be a none negative value smaller than ${eI+1}`);throw e.KNOWN_RECORDER_ERROR=!0,e}}class mhe{initPerformanceTracer(e){if(wt(e,"traceInitPerf")){const n=e.traceInitPerf,r=typeof n=="number";this.traceInitMaxIdent=r?n:1/0,this.traceInitPerf=r?n>0:n}else this.traceInitMaxIdent=0,this.traceInitPerf=Dc.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(e,n){if(this.traceInitPerf===!0){this.traceInitIndent++;const r=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${e}>`);const{time:i,value:s}=w3(n),o=i>10?console.warn:console.log;return this.traceInitIndent time: ${i}ms`),this.traceInitIndent--,s}else return n()}}function ghe(t,e){e.forEach(n=>{const r=n.prototype;Object.getOwnPropertyNames(r).forEach(i=>{if(i==="constructor")return;const s=Object.getOwnPropertyDescriptor(r,i);s&&(s.get||s.set)?Object.defineProperty(t.prototype,i,s):t.prototype[i]=n.prototype[i]})})}const Sv=Dm(oh,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(Sv);const Dc=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:P3,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),Ev=Object.freeze({recoveryValueFunc:()=>{},resyncEnabled:!0});var Wi;(function(t){t[t.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",t[t.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",t[t.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",t[t.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",t[t.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",t[t.LEFT_RECURSION=5]="LEFT_RECURSION",t[t.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",t[t.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",t[t.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",t[t.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",t[t.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",t[t.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",t[t.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",t[t.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(Wi||(Wi={}));class Um{static performSelfAnalysis(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let e;this.selfAnalysisDone=!0;const n=this.className;this.TRACE_INIT("toFastProps",()=>{b3(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),Tt(this.definedRulesNames,i=>{const o=this[i].originalGrammarAction;let a;this.TRACE_INIT(`${i} Rule`,()=>{a=this.topLevelRuleRecord(i,o)}),this.gastProductionsCache[i]=a})}finally{this.disableRecording()}});let r=[];if(this.TRACE_INIT("Grammar Resolving",()=>{r=Bue({rules:Rr(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(r)}),this.TRACE_INIT("Grammar Validations",()=>{if(Dn(r)&&this.skipValidations===!1){const i=zue({rules:Rr(this.gastProductionsCache),tokenTypes:Rr(this.tokensMap),errMsgProvider:Fu,grammarName:n}),s=bue({lookaheadStrategy:this.lookaheadStrategy,rules:Rr(this.gastProductionsCache),tokenTypes:Rr(this.tokensMap),grammarName:n});this.definitionErrors=this.definitionErrors.concat(i,s)}}),Dn(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{const i=_le(Rr(this.gastProductionsCache));this.resyncFollows=i}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var i,s;(s=(i=this.lookaheadStrategy).initialize)===null||s===void 0||s.call(i,{rules:Rr(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(Rr(this.gastProductionsCache))})),!Um.DEFER_DEFINITION_ERRORS_HANDLING&&!Dn(this.definitionErrors))throw e=ot(this.definitionErrors,i=>i.message),new Error(`Parser Definition Errors detected: - ${e.join(` -------------------------------- -`)}`)})}constructor(e,n){this.definitionErrors=[],this.selfAnalysisDone=!1;const r=this;if(r.initErrorHandler(n),r.initLexerAdapter(),r.initLooksAhead(n),r.initRecognizerEngine(e,n),r.initRecoverable(n),r.initTreeBuilder(n),r.initContentAssist(),r.initGastRecorder(n),r.initPerformanceTracer(n),wt(n,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. - Please use the flag on the relevant DSL method instead. - See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES - For further details.`);this.skipValidations=wt(n,"skipValidations")?n.skipValidations:Dc.skipValidations}}Um.DEFER_DEFINITION_ERRORS_HANDLING=!1;ghe(Um,[jue,Kue,ohe,ahe,lhe,che,uhe,hhe,dhe,mhe]);class _he extends Um{constructor(e,n=Dc){const r=fi(n);r.outputCst=!0,super(e,r)}}function vhe(t){const e=new yhe,n=Rr(t);return ot(n,r=>e.visitRule(r))}class yhe extends xh{visitRule(e){const n=this.visitEach(e.definition),r=hP(n,s=>s.propertyName),i=ot(r,(s,o)=>{const a=!nT(s,l=>!l.canBeNull);let c=s[0].type;return s.length>1&&(c=ot(s,l=>l.type)),{name:o,type:c,optional:a}});return{name:e.name,properties:i}}visitAlternative(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitOption(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitRepetition(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitRepetitionMandatory(e){return this.visitEach(e.definition)}visitRepetitionMandatoryWithSeparator(e){return this.visitEach(e.definition).concat({propertyName:e.separator.name,canBeNull:!0,type:B0(e.separator)})}visitRepetitionWithSeparator(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0}).concat({propertyName:e.separator.name,canBeNull:!0,type:B0(e.separator)})}visitAlternation(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitTerminal(e){return[{propertyName:e.label||e.terminalType.name,canBeNull:!1,type:B0(e)}]}visitNonTerminal(e){return[{propertyName:e.label||e.nonTerminalName,canBeNull:!1,type:B0(e)}]}visitEachAndOverrideWith(e,n){return ot(this.visitEach(e),r=>fs({},r,n))}visitEach(e){return ls(ot(e,n=>this.visit(n)))}}function B0(t){return t instanceof _s?{kind:"rule",name:t.referencedRule.name}:{kind:"token"}}function xhe(t,e){let n=[];return n=n.concat('import type { CstNode, ICstVisitor, IToken } from "chevrotain";'),n=n.concat(ls(ot(t,r=>She(r)))),e.includeVisitorInterface&&(n=n.concat(The(e.visitorInterfaceName,t))),n.join(` - -`)+` -`}function She(t){const e=Ehe(t),n=whe(t);return[e,n]}function Ehe(t){const e=t4(t.name),n=PA(t.name);return`export interface ${e} extends CstNode { - name: "${t.name}"; - children: ${n}; -}`}function whe(t){return`export type ${PA(t.name)} = { - ${ot(t.properties,n=>bhe(n)).join(` - `)} -};`}function bhe(t){const e=Mhe(t.type);return`${t.name}${t.optional?"?":""}: ${e}[];`}function The(t,e){return`export interface ${t} extends ICstVisitor { - ${ot(e,n=>Ahe(n)).join(` - `)} -}`}function Ahe(t){const e=PA(t.name);return`${t.name}(children: ${e}, param?: IN): OUT;`}function Mhe(t){if(un(t)){const e=ty(ot(t,r=>nI(r)));return"("+ps(e,(r,i)=>r+" | "+i)+")"}else return nI(t)}function nI(t){return t.kind==="token"?"IToken":t4(t.name)}function t4(t){return ZL(t)+"CstNode"}function PA(t){return ZL(t)+"CstChildren"}const Che={includeVisitorInterface:!0,visitorInterfaceName:"ICstNodeVisitor"};function Rhe(t,e){const n=Object.assign(Object.assign({},Che),e),r=vhe(t);return xhe(r,n)}var n4={exports:{}},MS={exports:{}},rI;function Nhe(){return rI||(rI=1,function(t,e){(function(n,r){t.exports=r()})(To,function(){function n(v){return!isNaN(parseFloat(v))&&isFinite(v)}function r(v){return v.charAt(0).toUpperCase()+v.substring(1)}function i(v){return function(){return this[v]}}var s=["isConstructor","isEval","isNative","isToplevel"],o=["columnNumber","lineNumber"],a=["fileName","functionName","source"],c=["args"],l=["evalOrigin"],u=s.concat(o,a,c,l);function h(v){if(v)for(var y=0;y-1&&(u=u.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var h=u.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),p=h.match(/ (\(.+\)$)/);h=p?h.replace(p[0],""):h;var m=this.extractLocation(p?p[1]:h),g=p&&h||void 0,v=["eval",""].indexOf(m[0])>-1?void 0:m[0];return new r({functionName:g,fileName:v,lineNumber:m[1],columnNumber:m[2],source:u})},this)},parseFFOrSafari:function(c){var l=c.stack.split(` -`).filter(function(u){return!u.match(o)},this);return l.map(function(u){if(u.indexOf(" > eval")>-1&&(u=u.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),u.indexOf("@")===-1&&u.indexOf(":")===-1)return new r({functionName:u});var h=/((.*".+"[^@]*)?[^@]*)(?:@)/,p=u.match(h),m=p&&p[1]?p[1]:void 0,g=this.extractLocation(u.replace(h,""));return new r({functionName:m,fileName:g[0],lineNumber:g[1],columnNumber:g[2],source:u})},this)},parseOpera:function(c){return!c.stacktrace||c.message.indexOf(` -`)>-1&&c.message.split(` -`).length>c.stacktrace.split(` -`).length?this.parseOpera9(c):c.stack?this.parseOpera11(c):this.parseOpera10(c)},parseOpera9:function(c){for(var l=/Line (\d+).*script (?:in )?(\S+)/i,u=c.message.split(` -`),h=[],p=2,m=u.length;p/,"$2").replace(/\([^)]*\)/g,"")||void 0,v;m.match(/\(([^)]*)\)/)&&(v=m.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var y=v===void 0||v==="[arguments not available]"?void 0:v.split(",");return new r({functionName:g,args:y,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:u})},this)}}})})(n4);var khe=n4.exports;const Ihe=Bc(khe);function Qc(t){const e={},n={get(){return[!1,void 0]},set(){return[!1,void 0]},tick(){},everytick(){},...t,getcommand(r){return e[r]},command(r,i){return e[r]=i,n}};return n}function xc(t){return Z(t)&&Z(t.x)&&Z(t.y)}function Zr(t,e){switch(e){case st.NORTH:--t.y;break;case st.SOUTH:++t.y;break;case st.WEST:--t.x;break;case st.EAST:++t.x;break}return t}function tf(t,e){const n=e.x-t.x,r=e.y-t.y;if(n<0)return st.WEST;if(n>0)return st.EAST;if(r<0)return st.NORTH;if(r>0)return st.SOUTH}const r4={idle:"IDLE",up:"NORTH",down:"SOUTH",left:"WEST",right:"EAST",by:"BY",at:"AT",flow:"FLOW",seek:"SEEK",rndns:"RNDNS",rndne:"RNDNE",rnd:"RND",cw:"CW",ccw:"CCW",opp:"OPP",rndp:"RNDP",i:"IDLE",u:"NORTH",north:"NORTH",n:"NORTH",d:"SOUTH",south:"SOUTH",s:"SOUTH",l:"WEST",west:"WEST",w:"WEST",r:"EAST",east:"EAST",e:"EAST",edit:"EDIT"};function Tc(t){return cn(t)&&i4(t[0])}function i4(t){return Z(st[t])&&Kt(t)}function Ohe(t){const e=st[t];return Z(e)?e:st.IDLE}function s4(t){if(Kt(t))return r4[$t(t)]}function iI(t){if(Tc(t))return t;if(i4(t))return[t];const e=s4(t);if(Z(e))return[e]}function sI(t){const e=se.words[t],n=iI(e);if(Tc(n))return[n,t+1];const[r,i]=Fi(t),s=iI(r);return Tc(s)?[s,i]:[void 0,t]}function Fw(t){const e=[];let[n,r]=sI(t);for(;Tc(n);){if(e.push(...n),(n[0]==="AT"||n[0]==="BY")&&n.length<2){const[o,a,c]=Ve(se.words,r,[Ie.NUMBER,Ie.NUMBER]);e.push(o,a),r=c}const[i,s]=sI(r);n=i,r=s}return e.length?[e,r]:[void 0,t]}function rd(t){return cn(t)&&typeof t[0]=="string"}function oI(t){const e=se.words[t];if(rd(e))return[e,t+1];const[n,r]=Cv(t),[i,s]=Fi(r,!1);return Kt(i)?[[i,n],s]:[void 0,t]}function wv(t){if(!rd(t))return;const[e]=t;return e}function o4(t){if(!rd(t))return;const[,e]=t,n=Z(e)?wpe(e):void 0;return Z(n)?n:void 0}function a4(t){if(!rd(t))return;const[,e]=t,n=Z(e)?bpe(e):void 0;return Z(n)?n:void 0}const hi=60,Sh=25;var vn=(t=>(t[t.ERROR=0]="ERROR",t[t.LOADER=1]="LOADER",t[t.BOARD=2]="BOARD",t[t.OBJECT=3]="OBJECT",t[t.TERRAIN=4]="TERRAIN",t[t.CHARSET=5]="CHARSET",t[t.PALETTE=6]="PALETTE",t))(vn||{});function c4(t,e){const n=t??zn.ISWALK,r=e??zn.ISWALK;switch(n){case zn.ISWALK:return r!==zn.ISWALK;case zn.ISSWIM:return r!==zn.ISSWIM;case zn.ISSOLID:return!0;case zn.ISBULLET:return r!==zn.ISWALK&&r!==zn.ISSWIM}}function aI(t,e,n){const r=t==null?void 0:t.objects[n];if(Z(r))return r;if(Z(e)){const i=Fm(t,"player"),s={x:e.x??0,y:e.y??0};u4(s,i)}}function Fm(t,e){var r,i;return[...((i=(r=t==null?void 0:t.named)==null?void 0:r[e])==null?void 0:i.values())??[]].map(s=>typeof s=="string"?t==null?void 0:t.objects[s]:t==null?void 0:t.terrain[s]).filter(Z)}function l4(t,e){const n=wv(e),r=o4(e),i=a4(e);return t.filter(s=>!(Z(n)&&GA(s)!==n||Z(r)&&Sfe(s)!==r||Z(i)&&Efe(s)!==i)).filter(Z)}function CS(t,e){return Z(t)?e.map(n=>{var r;if(typeof n=="string"){const i=t.objects[n];if(Z(i))return i;const s=Fm(t,$t(n));if(s.length)return s}else if(xc(n)&&n.x>=0&&n.x=0&&n.y=0;r--){const i=t[r];let s=DA[i];s*=n,e+=s,n*=id}return e}ui.s_to_int=UA;function f4(t){let e=BigInt(0),n=BigInt(1);const r=BigInt(id);for(let i=t.length-1;i>=0;i--){const s=t[i];let o=BigInt(DA[s]);o*=n,e+=o,n*=r}return e}ui.s_to_big_int=f4;function FA(t){if(t===0)return Uc[0];const e=[];for(;t!==0;){const n=t%id,r=Uc[n];e.push(r),t-=n,t/=id}return e.reverse().join("")}ui.int_to_s=FA;function d4(t){const e=BigInt(0),n=BigInt(id);if(t===e)return Uc[0];const r=[];for(;t!==e;){const i=t%n,s=Uc[Number(i)];r.push(s),t/=n}return r.reverse().join("")}ui.big_int_to_s=d4;function p4(t){return t.split("").reverse().join("")}function m4(t){if(t<0)return"-"+m4(-t);let[e,n]=t.toString().split(".");if(!n)return FA(t);let r;n&&([n,r]=n.split("e")),e=M_(e),n=p4(n),n=M_(n);let i=e+"."+n;if(r){switch(i+=".",r[0]){case"+":r=r.slice(1);break;case"-":i+="-",r=r.slice(1);break}r=M_(r),i+=r}return i}ui.num_to_s=m4;function M_(t){const e=+t;return e.toString()===t&&e+1!==e&&e-1!==e?FA(e):":"+d4(BigInt(t))}ui.int_str_to_s=M_;function RS(t){return t[0]===":"?f4(t.substring(1)).toString():UA(t).toString()}function g4(t){if(t[0]==="-")return-g4(t.substr(1));let[e,n,r]=t.split(".");if(!n)return UA(e);e=RS(e),n=RS(n),n=p4(n);let i=e+"."+n;if(r){i+="e";let s=!1;r[0]==="-"&&(s=!0,r=r.slice(1)),r=RS(r),i+=s?-r:+r}return+i}ui.s_to_num=g4;Object.defineProperty(li,"__esModule",{value:!0});li.decodeStr=li.encodeStr=li.decodeBool=li.encodeBool=li.decodeKey=li.decodeNum=li.encodeNum=void 0;const BA=ui;function Uhe(t){return"n|"+(0,BA.num_to_s)(t)}li.encodeNum=Uhe;function Fhe(t){return t=t.replace("n|",""),(0,BA.s_to_num)(t)}li.decodeNum=Fhe;function Bhe(t){return typeof t=="number"?t:(0,BA.s_to_int)(t)}li.decodeKey=Bhe;function zhe(t){return t?"b|T":"b|F"}li.encodeBool=zhe;function Vhe(t){switch(t){case"b|T":return!0;case"b|F":return!1}return!!t}li.decodeBool=Vhe;function Hhe(t){switch(t[0]+t[1]){case"b|":case"o|":case"n|":case"a|":case"s|":t="s|"+t}return t}li.encodeStr=Hhe;function Ghe(t){return t[0]+t[1]==="s|"?t.substr(2):t}li.decodeStr=Ghe;var Is={},Bm={};Object.defineProperty(Bm,"__esModule",{value:!0});Bm.config=void 0;Bm.config={sort_key:!1,error_on_nan:!1,error_on_infinite:!1};Object.defineProperty(Is,"__esModule",{value:!0});Is.addValue=Is.makeInMemoryMemory=Is.makeInMemoryCache=Is.makeInMemoryStore=Is.memToValues=void 0;const Bw=Bm,NS=Mc,kS=li,Whe=ui;function jhe(t){return t.store.toArray()}Is.memToValues=jhe;function _4(){const t=[];return{forEach(e){for(let n=0;n(Hw(),this?this.unpack(e,n):$p.prototype.unpack.call(cI,e,n)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof n=="object"?(eo=n.end||e.length,ue=n.start||0):(ue=0,eo=n>-1?n:e.length),ga=0,Tl=null,ti=null,We=e;try{en=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw We=null,e instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof $p){if(Ln=this,this.structures)return on=this.structures,V0(n);(!on||on.length>0)&&(on=[])}else Ln=cI,(!on||on.length>0)&&(on=[]);return V0(n)}unpackMultiple(e,n){let r,i=0;try{Nl=!0;let s=e.length,o=this?this.unpack(e,s):qy.unpack(e,s);if(n){if(n(o,i,ue)===!1)return;for(;uer.slice(0)));for(let r=0,i=e.length;r=32&&(s.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in n||[])if(r>=0){let i=e[r],s=n[r];s&&(i&&((e.restoreStructures||(e.restoreStructures=[]))[r]=i),e[r]=s)}return this.structures=e}decode(e,n){return this.unpack(e,n)}}function V0(t){try{if(!Ln.trusted&&!Nl){let n=on.sharedLength||0;n=32&&lI?(e=lI(We,ue,eo,Ln),We=null,!(t&&t.lazy)&&e&&(e=e.toJSON()),ue=eo):e=mr(),ti&&(ue=ti.postBundlePosition,ti=null),Nl&&(on.restoreStructures=null),ue==eo)on&&on.restoreStructures&&uI(),on=null,We=null,Cc&&(Cc=null);else{if(ue>eo)throw new Error("Unexpected end of MessagePack data");if(!Nl){let n;try{n=JSON.stringify(e,(r,i)=>typeof i=="bigint"?`${i}n`:i).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return e}catch(e){throw on&&on.restoreStructures&&uI(),Hw(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||ue>eo)&&(e.incomplete=!0),e}}function uI(){for(let t in on.restoreStructures)on[t]=on.restoreStructures[t];on.restoreStructures=null}function mr(){let t=We[ue++];if(t<160)if(t<128){if(t<64)return t;{let e=on[t&63]||Ln.getStructures&&w4()[t&63];return e?(e.read||(e.read=zA(e,t&63)),e.read()):t}}else if(t<144)if(t-=128,Ln.mapsAsObjects){let e={};for(let n=0;n=ue)return Tl.slice(ue-Ks,(ue+=e)-Ks);if(ga==0&&eo<140){let n=e<16?VA(e):b4(e);if(n!=null)return n}return Vw(e)}else{let e;switch(t){case 192:return null;case 193:return ti?(e=mr(),e>0?ti[1].slice(ti.position1,ti.position1+=e):ti[0].slice(ti.position0,ti.position0-=e)):S4;case 194:return!1;case 195:return!0;case 196:if(e=We[ue++],e===void 0)throw new Error("Unexpected end of buffer");return OS(e);case 197:return e=en.getUint16(ue),ue+=2,OS(e);case 198:return e=en.getUint32(ue),ue+=4,OS(e);case 199:return yu(We[ue++]);case 200:return e=en.getUint16(ue),ue+=2,yu(e);case 201:return e=en.getUint32(ue),ue+=4,yu(e);case 202:if(e=en.getFloat32(ue),Ln.useFloat32>2){let n=HA[(We[ue]&127)<<1|We[ue+1]>>7];return ue+=4,(n*e+(e>0?.5:-.5)>>0)/n}return ue+=4,e;case 203:return e=en.getFloat64(ue),ue+=8,e;case 204:return We[ue++];case 205:return e=en.getUint16(ue),ue+=2,e;case 206:return e=en.getUint32(ue),ue+=4,e;case 207:return Ln.int64AsType==="number"?(e=en.getUint32(ue)*4294967296,e+=en.getUint32(ue+4)):Ln.int64AsType==="string"?e=en.getBigUint64(ue).toString():Ln.int64AsType==="auto"?(e=en.getBigUint64(ue),e<=BigInt(2)<=BigInt(-2)<=ue?Tl.slice(ue-Ks,(ue+=e)-Ks):nfe(e);case 218:return e=en.getUint16(ue),ue+=2,ga>=ue?Tl.slice(ue-Ks,(ue+=e)-Ks):rfe(e);case 219:return e=en.getUint32(ue),ue+=4,ga>=ue?Tl.slice(ue-Ks,(ue+=e)-Ks):ife(e);case 220:return e=en.getUint16(ue),ue+=2,fI(e);case 221:return e=en.getUint32(ue),ue+=4,fI(e);case 222:return e=en.getUint16(ue),ue+=2,dI(e);case 223:return e=en.getUint32(ue),ue+=4,dI(e);default:if(t>=224)return t-256;if(t===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+t)}}}const tfe=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function zA(t,e){function n(){if(n.count++>E4){let i=t.read=new Function("r","return function(){return "+(Ln.freezeData?"Object.freeze":"")+"({"+t.map(s=>s==="__proto__"?"__proto_:r()":tfe.test(s)?s+":r()":"["+JSON.stringify(s)+"]:r()").join(",")+"})}")(mr);return t.highByte===0&&(t.read=hI(e,t.read)),i()}let r={};for(let i=0,s=t.length;ifunction(){let n=We[ue++];if(n===0)return e();let r=t<32?-(t+(n<<5)):t+(n<<5),i=on[r]||w4()[r];if(!i)throw new Error("Record id is not defined for "+r);return i.read||(i.read=zA(i,t)),i.read()};function w4(){let t=C4(()=>(We=null,Ln.getStructures()));return on=Ln._mergeStructures(t,on)}var Vw=zm,nfe=zm,rfe=zm,ife=zm;function zm(t){let e;if(t<16&&(e=VA(t)))return e;if(t>64&&zw)return zw.decode(We.subarray(ue,ue+=t));const n=ue+t,r=[];for(e="";ue65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c)}else r.push(i);r.length>=4096&&(e+=Qr.apply(String,r),r.length=0)}return r.length>0&&(e+=Qr.apply(String,r)),e}function fI(t){let e=new Array(t);for(let n=0;n0){ue=e;return}n[r]=i}return Qr.apply(String,n)}function VA(t){if(t<4)if(t<2){if(t===0)return"";{let e=We[ue++];if((e&128)>1){ue-=1;return}return Qr(e)}}else{let e=We[ue++],n=We[ue++];if((e&128)>0||(n&128)>0){ue-=2;return}if(t<3)return Qr(e,n);let r=We[ue++];if((r&128)>0){ue-=3;return}return Qr(e,n,r)}else{let e=We[ue++],n=We[ue++],r=We[ue++],i=We[ue++];if((e&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){ue-=4;return}if(t<6){if(t===4)return Qr(e,n,r,i);{let s=We[ue++];if((s&128)>0){ue-=5;return}return Qr(e,n,r,i,s)}}else if(t<8){let s=We[ue++],o=We[ue++];if((s&128)>0||(o&128)>0){ue-=6;return}if(t<7)return Qr(e,n,r,i,s,o);let a=We[ue++];if((a&128)>0){ue-=7;return}return Qr(e,n,r,i,s,o,a)}else{let s=We[ue++],o=We[ue++],a=We[ue++],c=We[ue++];if((s&128)>0||(o&128)>0||(a&128)>0||(c&128)>0){ue-=8;return}if(t<10){if(t===8)return Qr(e,n,r,i,s,o,a,c);{let l=We[ue++];if((l&128)>0){ue-=9;return}return Qr(e,n,r,i,s,o,a,c,l)}}else if(t<12){let l=We[ue++],u=We[ue++];if((l&128)>0||(u&128)>0){ue-=10;return}if(t<11)return Qr(e,n,r,i,s,o,a,c,l,u);let h=We[ue++];if((h&128)>0){ue-=11;return}return Qr(e,n,r,i,s,o,a,c,l,u,h)}else{let l=We[ue++],u=We[ue++],h=We[ue++],p=We[ue++];if((l&128)>0||(u&128)>0||(h&128)>0||(p&128)>0){ue-=12;return}if(t<14){if(t===12)return Qr(e,n,r,i,s,o,a,c,l,u,h,p);{let m=We[ue++];if((m&128)>0){ue-=13;return}return Qr(e,n,r,i,s,o,a,c,l,u,h,p,m)}}else{let m=We[ue++],g=We[ue++];if((m&128)>0||(g&128)>0){ue-=14;return}if(t<15)return Qr(e,n,r,i,s,o,a,c,l,u,h,p,m,g);let v=We[ue++];if((v&128)>0){ue-=15;return}return Qr(e,n,r,i,s,o,a,c,l,u,h,p,m,g,v)}}}}}function pI(){let t=We[ue++],e;if(t<192)e=t-160;else switch(t){case 217:e=We[ue++];break;case 218:e=en.getUint16(ue),ue+=2;break;case 219:e=en.getUint32(ue),ue+=4;break;default:throw new Error("Expected string")}return zm(e)}function OS(t){return Ln.copyBuffers?Uint8Array.prototype.slice.call(We,ue,ue+=t):We.subarray(ue,ue+=t)}function yu(t){let e=We[ue++];if(ys[e]){let n;return ys[e](We.subarray(ue,n=ue+=t),r=>{ue=r;try{return mr()}finally{ue=n}})}else throw new Error("Unknown extension type "+e)}var mI=new Array(4096);function T4(){let t=We[ue++];if(t>=160&&t<192){if(t=t-160,ga>=ue)return Tl.slice(ue-Ks,(ue+=t)-Ks);if(!(ga==0&&eo<180))return Vw(t)}else return ue--,A4(mr());let e=(t<<5^(t>1?en.getUint16(ue):t>0?We[ue]:0))&4095,n=mI[e],r=ue,i=ue+t-3,s,o=0;if(n&&n.bytes==t){for(;r{let n=mr().map(A4),r=t;e!==void 0&&(t=t<32?-((e<<5)+t):(e<<5)+t,n.highByte=e);let i=on[t];return i&&(i.isShared||Nl)&&((on.restoreStructures||(on.restoreStructures=[]))[t]=i),on[t]=n,n.read=zA(n,r),n.read()};ys[0]=()=>{};ys[0].noBuffer=!0;ys[66]=t=>{let e=t.length,n=BigInt(t[0]&128?t[0]-256:t[0]);for(let r=1;r{let t=mr();return(sfe[t[0]]||Error)(t[1],{cause:t[2]})};ys[105]=t=>{if(Ln.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=en.getUint32(ue-4);Cc||(Cc=new Map);let n=We[ue],r;n>=144&&n<160||n==220||n==221?r=[]:r={};let i={target:r};Cc.set(e,i);let s=mr();return i.used?Object.assign(r,s):(i.target=s,s)};ys[112]=t=>{if(Ln.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=en.getUint32(ue-4),n=Cc.get(e);return n.used=!0,n.target};ys[115]=()=>new Set(mr());const M4=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(t=>t+"Array");let ofe=typeof globalThis=="object"?globalThis:window;ys[116]=t=>{let e=t[0],n=M4[e];if(!n){if(e===16){let r=new ArrayBuffer(t.length-1);return new Uint8Array(r).set(t.subarray(1)),r}throw new Error("Could not find typed array for code "+e)}return new ofe[n](Uint8Array.prototype.slice.call(t,1).buffer)};ys[120]=()=>{let t=mr();return new RegExp(t[0],t[1])};const afe=[];ys[98]=t=>{let e=(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3],n=ue;return ue+=e-t.length,ti=afe,ti=[pI(),pI()],ti.position0=0,ti.position1=0,ti.postBundlePosition=ue,ue=n,mr()};ys[255]=t=>t.length==4?new Date((t[0]*16777216+(t[1]<<16)+(t[2]<<8)+t[3])*1e3):t.length==8?new Date(((t[0]<<22)+(t[1]<<14)+(t[2]<<6)+(t[3]>>2))/1e6+((t[3]&3)*4294967296+t[4]*16777216+(t[5]<<16)+(t[6]<<8)+t[7])*1e3):t.length==12?new Date(((t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3])/1e6+((t[4]&128?-281474976710656:0)+t[6]*1099511627776+t[7]*4294967296+t[8]*16777216+(t[9]<<16)+(t[10]<<8)+t[11])*1e3):new Date("invalid");function C4(t){let e=eo,n=ue,r=Ks,i=ga,s=Tl,o=Cc,a=ti,c=new Uint8Array(We.slice(0,eo)),l=on,u=on.slice(0,on.length),h=Ln,p=Nl,m=t();return eo=e,ue=n,Ks=r,ga=i,Tl=s,Cc=o,ti=a,We=c,Nl=p,on=l,on.splice(0,on.length,...u),Ln=h,en=new DataView(We.buffer,We.byteOffset,We.byteLength),m}function Hw(){We=null,Cc=null,on=null}const HA=new Array(147);for(let t=0;t<256;t++)HA[t]=+("1e"+Math.floor(45.15-t*.30103));var qy=new $p({useRecords:!1});qy.unpack;qy.unpackMultiple;qy.unpack;let cfe=new Float32Array(1);new Uint8Array(cfe.buffer,0,4);let C_;try{C_=new TextEncoder}catch{}let Gw,R4;const Xy=typeof Buffer<"u",H0=Xy?function(t){return Buffer.allocUnsafeSlow(t)}:Uint8Array,N4=Xy?Buffer:Uint8Array,_I=Xy?4294967296:2144337920;let ye,Qd,kn,pe=0,Ni,Zn=null,lfe;const ufe=21760,hfe=/[\u0080-\uFFFF]/,nf=Symbol("record-id");class ffe extends $p{constructor(e){super(e),this.offset=0;let n,r,i,s,o=N4.prototype.utf8Write?function(P,T){return ye.utf8Write(P,T,ye.byteLength-T)}:C_&&C_.encodeInto?function(P,T){return C_.encodeInto(P,ye.subarray(T)).written}:!1,a=this;e||(e={});let c=e&&e.sequential,l=e.structures||e.saveStructures,u=e.maxSharedStructures;if(u==null&&(u=l?32:0),u>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let h=e.maxOwnStructures;h==null&&(h=l?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let p=u>32||h+u>64,m=u+64,g=u+h+64;if(g>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let v=[],y=0,_=0;this.pack=this.encode=function(P,T){if(ye||(ye=new H0(8192),kn=ye.dataView||(ye.dataView=new DataView(ye.buffer,0,8192)),pe=0),Ni=ye.length-10,Ni-pe<2048?(ye=new H0(ye.length),kn=ye.dataView||(ye.dataView=new DataView(ye.buffer,0,ye.length)),Ni=ye.length-10,pe=0):pe=pe+7&2147483640,n=pe,T&vfe&&(pe+=T&255),s=a.structuredClone?new Map:null,a.bundleStrings&&typeof P!="string"?(Zn=[],Zn.size=1/0):Zn=null,i=a.structures,i){i.uninitialized&&(i=a._mergeStructures(a.getStructures()));let V=i.sharedLength||0;if(V>u)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let B=0;Bj.offset>Y.offset?1:-1),z=B.length,W=-1;for(;V&&z>0;){let j=B[--z].offset+n;jV.position+n?W>=0&&(W+=6):(W>=0&&(kn.setUint32(V.position+n,kn.getUint32(V.position+n)+W),W=-1),V=V.previous,z++)}W>=0&&V&&kn.setUint32(V.position+n,kn.getUint32(V.position+n)+W),pe+=B.length*6,pe>Ni&&C(pe),a.offset=pe;let K=pfe(ye.subarray(n,pe),B);return s=null,K}return a.offset=pe,T&gfe?(ye.start=n,ye.end=pe,ye):ye.subarray(n,pe)}catch(V){throw H=V,V}finally{if(i&&(S(),r&&a.saveStructures)){let V=i.sharedLength||0,B=ye.subarray(n,pe),z=mfe(i,a);if(!H)return a.saveStructures(z,z.isCompatible)===!1?a.pack(P,T):(a.lastNamedStructuresLength=V,ye.length>1073741824&&(ye=null),B)}ye.length>1073741824&&(ye=null),T&_fe&&(pe=n)}};const S=()=>{_<10&&_++;let P=i.sharedLength||0;if(i.length>P&&!c&&(i.length=P),y>1e4)i.transitions=null,_=0,y=0,v.length>0&&(v=[]);else if(v.length>0&&!c){for(let T=0,H=v.length;T{var T=P.length;T<16?ye[pe++]=144|T:T<65536?(ye[pe++]=220,ye[pe++]=T>>8,ye[pe++]=T&255):(ye[pe++]=221,kn.setUint32(pe,T),pe+=4);for(let H=0;H{pe>Ni&&(ye=C(pe));var T=typeof P,H;if(T==="string"){let V=P.length;if(Zn&&V>=4&&V<4096){if((Zn.size+=V)>ufe){let K,j=(Zn[0]?Zn[0].length*3+Zn[1].length:0)+10;pe+j>Ni&&(ye=C(pe+j));let Y;Zn.position?(Y=Zn,ye[pe]=200,pe+=3,ye[pe++]=98,K=pe-n,pe+=4,xI(n,b,0),kn.setUint16(K+n-3,pe-n-K)):(ye[pe++]=214,ye[pe++]=98,K=pe-n,pe+=4),Zn=["",""],Zn.previous=Y,Zn.size=0,Zn.position=K}let W=hfe.test(P);Zn[W?0:1]+=P,ye[pe++]=193,b(W?-V:V);return}let B;V<32?B=1:V<256?B=2:V<65536?B=3:B=5;let z=V*3;if(pe+z>Ni&&(ye=C(pe+z)),V<64||!o){let W,K,j,Y=pe+B;for(W=0;W>6|192,ye[Y++]=K&63|128):(K&64512)===55296&&((j=P.charCodeAt(W+1))&64512)===56320?(K=65536+((K&1023)<<10)+(j&1023),W++,ye[Y++]=K>>18|240,ye[Y++]=K>>12&63|128,ye[Y++]=K>>6&63|128,ye[Y++]=K&63|128):(ye[Y++]=K>>12|224,ye[Y++]=K>>6&63|128,ye[Y++]=K&63|128);H=Y-pe-B}else H=o(P,pe+B);H<32?ye[pe++]=160|H:H<256?(B<2&&ye.copyWithin(pe+2,pe+1,pe+1+H),ye[pe++]=217,ye[pe++]=H):H<65536?(B<3&&ye.copyWithin(pe+3,pe+2,pe+2+H),ye[pe++]=218,ye[pe++]=H>>8,ye[pe++]=H&255):(B<5&&ye.copyWithin(pe+5,pe+3,pe+3+H),ye[pe++]=219,kn.setUint32(pe,H),pe+=4),pe+=H}else if(T==="number")if(P>>>0===P)P<32||P<128&&this.useRecords===!1||P<64&&!this.randomAccessStructure?ye[pe++]=P:P<256?(ye[pe++]=204,ye[pe++]=P):P<65536?(ye[pe++]=205,ye[pe++]=P>>8,ye[pe++]=P&255):(ye[pe++]=206,kn.setUint32(pe,P),pe+=4);else if(P>>0===P)P>=-32?ye[pe++]=256+P:P>=-128?(ye[pe++]=208,ye[pe++]=P+256):P>=-32768?(ye[pe++]=209,kn.setInt16(pe,P),pe+=2):(ye[pe++]=210,kn.setInt32(pe,P),pe+=4);else{let V;if((V=this.useFloat32)>0&&P<4294967296&&P>=-2147483648){ye[pe++]=202,kn.setFloat32(pe,P);let B;if(V<4||(B=P*HA[(ye[pe]&127)<<1|ye[pe+1]>>7])>>0===B){pe+=4;return}else pe--}ye[pe++]=203,kn.setFloat64(pe,P),pe+=8}else if(T==="object"||T==="function")if(!P)ye[pe++]=192;else{if(s){let B=s.get(P);if(B){if(!B.id){let z=s.idsToInsert||(s.idsToInsert=[]);B.id=z.push(B)}ye[pe++]=214,ye[pe++]=112,kn.setUint32(pe,B.id),pe+=4;return}else s.set(P,{offset:pe-n})}let V=P.constructor;if(V===Object)O(P);else if(V===Array)E(P);else if(V===Map)if(this.mapAsEmptyObject)ye[pe++]=128;else{H=P.size,H<16?ye[pe++]=128|H:H<65536?(ye[pe++]=222,ye[pe++]=H>>8,ye[pe++]=H&255):(ye[pe++]=223,kn.setUint32(pe,H),pe+=4);for(let[B,z]of P)b(B),b(z)}else{for(let B=0,z=Gw.length;B(ye=j,j=null,pe+=re,pe>Ni&&C(pe),{target:ye,targetView:kn,position:pe-re}),b)}finally{j&&(ye=j,kn=Y,pe=ge,Ni=ye.length-10)}Q&&(Q.length+pe>Ni&&C(Q.length+pe),pe=dfe(Q,ye,pe,K.type));return}}if(Array.isArray(P))E(P);else{if(P.toJSON){const B=P.toJSON();if(B!==P)return b(B)}if(T==="function")return b(this.writeFunction&&this.writeFunction(P));O(P)}}}else if(T==="boolean")ye[pe++]=P?195:194;else if(T==="bigint"){if(P=-(BigInt(1)<0)ye[pe++]=207,kn.setBigUint64(pe,P);else if(this.largeBigIntToFloat)ye[pe++]=203,kn.setFloat64(pe,Number(P));else{if(this.largeBigIntToString)return b(P.toString());if(this.useBigIntExtension&&P-(BigInt(2)**BigInt(1023))){ye[pe++]=199,pe++,ye[pe++]=66;let V=[],B;do{let z=P&BigInt(255);B=(z&BigInt(128))===(P>=BigInt(8)}while(!((P===BigInt(0)||P===BigInt(-1))&&B));ye[pe-2]=V.length;for(let z=V.length;z>0;)ye[pe++]=Number(V[--z]);return}else throw new RangeError(P+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}pe+=8}else if(T==="undefined")this.encodeUndefinedAsNil?ye[pe++]=192:(ye[pe++]=212,ye[pe++]=0,ye[pe++]=0);else throw new Error("Unknown type: "+T)},N=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?P=>{let T;if(this.skipValues){T=[];for(let B in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(B))&&!this.skipValues.includes(P[B])&&T.push(B)}else T=Object.keys(P);let H=T.length;H<16?ye[pe++]=128|H:H<65536?(ye[pe++]=222,ye[pe++]=H>>8,ye[pe++]=H&255):(ye[pe++]=223,kn.setUint32(pe,H),pe+=4);let V;if(this.coercibleKeyAsNumber)for(let B=0;B{ye[pe++]=222;let T=pe-n;pe+=2;let H=0;for(let V in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(V))&&(b(V),b(P[V]),H++);if(H>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');ye[T+++n]=H>>8,ye[T+n]=H&255},R=this.useRecords===!1?N:e.progressiveRecords&&!p?P=>{let T,H=i.transitions||(i.transitions=Object.create(null)),V=pe++-n,B;for(let z in P)if(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(z)){if(T=H[z],T)H=T;else{let W=Object.keys(P),K=H;H=i.transitions;let j=0;for(let Y=0,ge=W.length;Y{let T,H=i.transitions||(i.transitions=Object.create(null)),V=0;for(let z in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(z))&&(T=H[z],T||(T=H[z]=Object.create(null),V++),H=T);let B=H[nf];B?B>=96&&p?(ye[pe++]=((B-=96)&31)+96,ye[pe++]=B>>5):ye[pe++]=B:I(H,H.__keys__||Object.keys(P),V);for(let z in P)(typeof P.hasOwnProperty!="function"||P.hasOwnProperty(z))&&b(P[z])},M=typeof this.useRecords=="function"&&this.useRecords,O=M?P=>{M(P)?R(P):N(P)}:R,C=P=>{let T;if(P>16777216){if(P-n>_I)throw new Error("Packed buffer would be larger than maximum buffer size");T=Math.min(_I,Math.round(Math.max((P-n)*(P>67108864?1.25:2),4194304)/4096)*4096)}else T=(Math.max(P-n<<2,ye.length-1)>>12)+1<<12;let H=new H0(T);return kn=H.dataView||(H.dataView=new DataView(H.buffer,0,T)),P=Math.min(P,ye.length),ye.copy?ye.copy(H,0,n,P):H.set(ye.slice(n,P)),pe-=n,n=0,Ni=H.length-10,ye=H},I=(P,T,H)=>{let V=i.nextId;V||(V=64),V=g&&(V=m),i.nextId=V+1);let B=T.highByte=V>=96&&p?V-96>>5:-1;P[nf]=V,P.__keys__=T,i[V-64]=T,V=0?(ye[pe++]=(V&31)+96,ye[pe++]=B):ye[pe++]=V):(B>=0?(ye[pe++]=213,ye[pe++]=114,ye[pe++]=(V&31)+96,ye[pe++]=B):(ye[pe++]=212,ye[pe++]=114,ye[pe++]=V),H&&(y+=_*H),v.length>=h&&(v.shift()[nf]=0),v.push(P),b(T))},U=(P,T,H,V)=>{let B=ye,z=pe,W=Ni,K=n;ye=Qd,pe=0,n=0,ye||(Qd=ye=new H0(8192)),Ni=ye.length-10,I(P,T,V),Qd=ye;let j=pe;if(ye=B,pe=z,Ni=W,n=K,j>1){let Y=pe+j-1;Y>Ni&&C(Y);let ge=H+n;ye.copyWithin(ge+j,ge+1,pe),ye.set(Qd.slice(0,j),ge),pe=Y}else ye[H+n]=Qd[0]},L=P=>{let T=lfe(P,ye,n,pe,i,C,(H,V,B)=>{if(B)return r=!0;pe=V;let z=ye;return b(H),S(),z!==ye?{position:pe,targetView:kn,target:ye}:pe},this);if(T===0)return O(P);pe=T}}useBuffer(e){ye=e,ye.dataView||(ye.dataView=new DataView(ye.buffer,ye.byteOffset,ye.byteLength)),pe=0}set position(e){pe=e}get position(){return pe}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}}R4=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,x4];Gw=[{pack(t,e,n){let r=t.getTime()/1e3;if((this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:i,targetView:s,position:o}=e(6);i[o++]=214,i[o++]=255,s.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:i,targetView:s,position:o}=e(10);i[o++]=215,i[o++]=255,s.setUint32(o,t.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),s.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),n(this.onInvalidDate());let{target:i,targetView:s,position:o}=e(3);i[o++]=212,i[o++]=255,i[o++]=255}else{let{target:i,targetView:s,position:o}=e(15);i[o++]=199,i[o++]=12,i[o++]=255,s.setUint32(o,t.getMilliseconds()*1e6),s.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(t,e,n){if(this.setAsEmptyObject)return e(0),n({});let r=Array.from(t),{target:i,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(i[s++]=212,i[s++]=115,i[s++]=0),n(r)}},{pack(t,e,n){let{target:r,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),n([t.name,t.message,t.cause])}},{pack(t,e,n){let{target:r,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),n([t.source,t.flags])}},{pack(t,e){this.moreTypes?vI(t,16,e):yI(Xy?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let n=t.constructor;n!==N4&&this.moreTypes?vI(t,M4.indexOf(n.name),e):yI(t,e)}},{pack(t,e){let{target:n,position:r}=e(1);n[r]=193}}];function vI(t,e,n,r){let i=t.byteLength;if(i+1<256){var{target:s,position:o}=n(4+i);s[o++]=199,s[o++]=i+1}else if(i+1<65536){var{target:s,position:o}=n(5+i);s[o++]=200,s[o++]=i+1>>8,s[o++]=i+1&255}else{var{target:s,position:o,targetView:a}=n(7+i);s[o++]=201,a.setUint32(o,i+1),o+=4}s[o++]=116,s[o++]=e,t.buffer||(t=new Uint8Array(t)),s.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),o)}function yI(t,e){let n=t.byteLength;var r,i;if(n<256){var{target:r,position:i}=e(n+2);r[i++]=196,r[i++]=n}else if(n<65536){var{target:r,position:i}=e(n+3);r[i++]=197,r[i++]=n>>8,r[i++]=n&255}else{var{target:r,position:i,targetView:s}=e(n+5);r[i++]=198,s.setUint32(i,n),i+=4}r.set(t,i)}function dfe(t,e,n,r){let i=t.length;switch(i){case 1:e[n++]=212;break;case 2:e[n++]=213;break;case 4:e[n++]=214;break;case 8:e[n++]=215;break;case 16:e[n++]=216;break;default:i<256?(e[n++]=199,e[n++]=i):i<65536?(e[n++]=200,e[n++]=i>>8,e[n++]=i&255):(e[n++]=201,e[n++]=i>>24,e[n++]=i>>16&255,e[n++]=i>>8&255,e[n++]=i&255)}return e[n++]=r,e.set(t,n),n+=i,n}function pfe(t,e){let n,r=e.length*6,i=t.length-r;for(;n=e.pop();){let s=n.offset,o=n.id;t.copyWithin(s+r,s,i),r-=6;let a=s+r;t[a++]=214,t[a++]=105,t[a++]=o>>24,t[a++]=o>>16&255,t[a++]=o>>8&255,t[a++]=o&255,i=s}return t}function xI(t,e,n){if(Zn.length>0){kn.setUint32(Zn.position+t,pe+n-Zn.position-t),Zn.stringsPosition=pe-t;let r=Zn;Zn=null,e(r[0]),e(r[1])}}function mfe(t,e){return t.isCompatible=n=>{let r=!n||(e.lastNamedStructuresLength||0)===n.length;return r||e._mergeStructures(n),r},t}let k4=new ffe({useRecords:!1});k4.pack;k4.pack;const gfe=512,_fe=1024,vfe=2048;function SI(){return{id:fr()}}function yfe(){return new Array(hi*Sh).map(()=>{})}function xfe(t=JW){const e={terrain:yfe(),objects:{},id:""};return t(e)}function GA(t){var e;return $t((t==null?void 0:t.name)??((e=t==null?void 0:t.kinddata)==null?void 0:e.name)??"object")}function Sfe(t){var e;return(t==null?void 0:t.color)??((e=t==null?void 0:t.kinddata)==null?void 0:e.color)??wn.BLACK}function Efe(t){var e;return(t==null?void 0:t.bg)??((e=t==null?void 0:t.kinddata)==null?void 0:e.bg)??wn.BLACK}function bv(t,e){if(!Z(t)||!oo(e))return;const{color:n,bg:r}=Tpe(e);Z(n)&&(t.color=n),Z(r)&&(t.bg=r)}function wfe(t,e){if(!Z(t)||!Z(e)||!Z(e.x)||!Z(e.y)||e.x<0||e.x>=hi||e.y<0||e.y>=Sh)return;const n={...e},r=e.x+e.y*hi;return t.terrain[r]=n,e}function bfe(t,e){if(!Z(t)||!Z(e))return;const n={...e,id:e.id??fr()};return t.objects[n.id]=n,n}function I4(t,e,n){return wfe(t,{...e,kind:n})}function O4(t,e,n,r){return bfe(t,{...e,id:void 0,kind:n})}function Tv(t,e){if(t)return t.objects[e]}function Ww(t,e,n,r,i){if(!Z(t)||!Z(e))return{x:0,y:0};const s={x:e.x??0,y:e.y??0},o={x:e.lx??s.x,y:e.ly??s.y},a=tf(o,s),c=hi-1,l=Sh-1;for(let u=0;u(t[t.CATEGORY=0]="CATEGORY",t[t.COLLISION=1]="COLLISION",t[t.COLOR=2]="COLOR",t[t.KIND=3]="KIND",t[t.DIR=4]="DIR",t[t.NUMBER=5]="NUMBER",t[t.STRING=6]="STRING",t[t.NUMBER_OR_STRING=7]="NUMBER_OR_STRING",t[t.MAYBE_CATEGORY=8]="MAYBE_CATEGORY",t[t.MAYBE_COLLISION=9]="MAYBE_COLLISION",t[t.MAYBE_COLOR=10]="MAYBE_COLOR",t[t.MAYBE_KIND=11]="MAYBE_KIND",t[t.MAYBE_DIR=12]="MAYBE_DIR",t[t.MAYBE_NUMBER=13]="MAYBE_NUMBER",t[t.MAYBE_STRING=14]="MAYBE_STRING",t[t.MAYBE_NUMBER_OR_STRING=15]="MAYBE_NUMBER_OR_STRING",t[t.ANY=16]="ANY",t))(Ie||{});function Jr(t,e){throw new Error(`Invalid arg, expected: ${t} but got ${JSON.stringify(e)}`)}function Ve(t,e,n){var o,a,c,l;const r=se.words;se.words=t;const i=[];let s=e;for(let u=0;u(wI(1,t,e),0)).command("synth",(t,e)=>{for(let n=1;n<=8;++n)sa(n,e);return 0}).command("synth1",(t,e)=>(sa(1,e),0)).command("synth2",(t,e)=>(sa(2,e),0)).command("synth3",(t,e)=>(sa(3,e),0)).command("synth4",(t,e)=>(sa(4,e),0)).command("synth5",(t,e)=>(sa(5,e),0)).command("synth6",(t,e)=>(sa(6,e),0)).command("synth7",(t,e)=>(sa(7,e),0)).command("synth8",(t,e)=>(sa(8,e),0)).command("bgplay",(t,e)=>(wI(0,t,e),0)).command("bgsynth",(t,e)=>(sa(0,e),0)).command("tts",(t,e)=>{const[n,r]=Ve(e,0,[Ie.STRING,Ie.MAYBE_STRING]);return E9("audio",r??"",n),0}),WA=Uy(32,126).map(t=>String.fromCharCode(t));function tn(t){return Fs({...t,name:`token_${t.name}`})}function po(t,e=!1){return tn(e?{name:t,pattern:new RegExp(t.toLowerCase(),"i"),longer_alt:ji,group:zr.SKIPPED}:{name:t,pattern:new RegExp(t.toLowerCase(),"i"),longer_alt:ji})}const qp=tn({name:"newline",line_breaks:!0,start_chars_hint:[` -`,"\r"],pattern:/\n|\r\n?/}),Rfe=tn({name:"whitespace",pattern:/ +/,group:zr.SKIPPED}),Nfe=tn({name:"whitespace",pattern:/\s+/,line_breaks:!0,group:zr.SKIPPED}),jA=tn({name:"stat",pattern:/@.*/,start_chars_hint:["@"]}),uf=tn({name:"command",pattern:/#/,start_chars_hint:["#"]});let B4=!1;function kfe(t,e,n){if(!B4)return null;const[r]=n.slice(-1);if(r&&r.tokenType!==qp)return null;let i=e;for(;t[i]===" ";)i++;if("@#/?':!".includes(t[i]))return null;let s=e+1;for(;s"@#/?':!".includes(t)===!1)}),V4=tn({name:"comment",pattern:/'.*/,start_chars_hint:["'"]}),H4=tn({name:"label",pattern:/:[^;:\n]*/,start_chars_hint:[":"]}),G4=tn({name:"hyperlink",pattern:/!/,start_chars_hint:["!"]}),W4=tn({name:"hyperlinktext",pattern:/;[^;\n]*/,start_chars_hint:[";"]}),ji=tn({name:"stringliteral",pattern:/[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/,start_chars_hint:WA}),j4=tn({name:"stringliteraldouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),$4=tn({name:"numberliteral",pattern:/-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?/}),q4=tn({name:"iseq",pattern:/=|is|eq|equal/,longer_alt:ji}),X4=tn({name:"isnoteq",pattern:/!=|not ?eq|not ?equal/,longer_alt:ji}),K4=tn({name:"islessthan",pattern:/<|below/,longer_alt:ji}),Y4=tn({name:"isgreaterthan",pattern:/>|above/,longer_alt:ji}),Z4=tn({name:"islessthanorequal",pattern:/<=|below ?or ?eq|below ?or ?equal/,longer_alt:ji}),J4=tn({name:"isgreaterthanorequal",pattern:/>=|above ?or ?eq|above ?or ?equal/,longer_alt:ji}),$w=tn({name:"or",pattern:/or/i,longer_alt:ji}),qw=tn({name:"not",pattern:/not/i,longer_alt:ji}),Xw=tn({name:"and",pattern:/and/i,longer_alt:ji}),Kw=tn({name:"plus",pattern:/\+/}),Yw=tn({name:"minus",pattern:/-/}),Q4=tn({name:"power",pattern:/\*\*/}),eF=tn({name:"multiply",pattern:/\*/}),Zw=tn({name:"divide",pattern:/\//}),tF=tn({name:"moddivide",pattern:/%/}),nF=tn({name:"floordivide",pattern:/%%/}),rF=tn({name:"query",pattern:/\?/}),iF=tn({name:"lparen",pattern:/\(/,push_mode:"ignore_newlines"}),sF=tn({name:"rparen",pattern:/\)/,pop_mode:!0}),oF=tn({name:"command_play",pattern:/(play|bgplay) .*/,start_chars_hint:WA,longer_alt:ji}),aF=po("debugger"),Jw=po("if"),N_=po("do"),Ife=po("to",!0),Qw=po("done"),Ofe=po("then",!0),eb=po("else"),cF=po("while"),lF=po("repeat"),uF=po("waitfor"),hF=tn({name:"foreach",pattern:/foreach|for/,longer_alt:ji}),fF=po("break"),dF=po("continue");function pF(t){return[...t,$4,q4,X4,Z4,K4,J4,Y4,$w,qw,Xw,Kw,Yw,Q4,eF,Zw,nF,tF,rF,iF,sF,j4,ji]}const mF=pF([z4,jA,oF,uf,V4,H4,G4,W4,qp,Rfe,fF,dF,aF,Qw,N_,eb,hF,Jw,lF,Ofe,Ife,uF,cF]),Lfe=new zr({defaultMode:"use_newlines",modes:{use_newlines:mF,ignore_newlines:pF([Nfe])}},{skipValidations:!Ra,ensureOptimizations:Ra});function gF(t){B4=!0;const e=Lfe.tokenize(t||` -`),[n]=(cn(e.tokens)?e.tokens:[]).slice(-1);return n&&n.tokenType.name!=="Newline"&&e.tokens.push(Dm(qp,` -`,n.startOffset,n.endOffset??NaN,n.startLine??NaN,n.endLine??NaN,n.startColumn??NaN,n.endColumn??NaN)),e}function _F(t,e=!0){const[n,...r]=t;switch($t(n)){default:return e?{type:dt.OBJECT,values:t}:{type:dt.CONST,values:t};case"loader":return{type:dt.LOADER,values:r};case"board":return{type:dt.BOARD,values:r};case"object":return{type:dt.OBJECT,values:r};case"terrain":return{type:dt.TERRAIN,values:r};case"charset":return{type:dt.CHARSET,values:r};case"palette":return{type:dt.PALETTE,values:r};case"rn":case"range":return{type:dt.RANGE,values:r};case"sl":case"select":return{type:dt.SELECT,values:r};case"nm":case"number":return{type:dt.NUMBER,values:r};case"tx":case"text":return{type:dt.TEXT,values:r};case"ln":case"link":return{type:dt.LINK,values:r};case"hk":case"hotkey":return{type:dt.HOTKEY,values:r};case"scroll":return{type:dt.SCROLL,values:r};case"copyit":return{type:dt.COPYIT,values:r}}}function Js(t){switch(t){case dt.LOADER:return"loader";case dt.BOARD:return"board";case dt.OBJECT:return"object";case dt.TERRAIN:return"terrain";case dt.CHARSET:return"charset";case dt.PALETTE:return"palette";case dt.CONST:return"const";case dt.RANGE:return"range";case dt.SELECT:return"select";case dt.NUMBER:return"number";case dt.TEXT:return"text";case dt.LINK:return"link";case dt.HOTKEY:return"hotkey";case dt.SCROLL:return"scroll";case dt.COPYIT:return"copyit"}}function Pfe(t,e){return{id:fr(),code:t,...e}}function Dfe(t){const e={...$A(t)};return Object.keys(e).forEach(n=>{switch(n){case"type":case"name":delete e[n];break}}),e}function $A(t){var r;if(!Z(t))return{};if(Z((r=t.stats)==null?void 0:r.type))return t.stats;t.stats={};const e=gF(t.code);let n=!0;for(let i=0;ii.id===e||n===Sc(i))}function SF(t,e,n){if(!Z(t))return;const r=$t(n);return t.pages.find(s=>qA(s)===e&&(s.id===n||r===Sc(s)))}function Ufe(t,e){if(!Z(t)||!Z(e))return!1;const n=Vm(t,e.id);return Z(n)?!1:(t.pages.push(e),!0)}function Ffe(t,e){const n=Vm(t,e);if(Z(t)&&Z(n)){const r=$t(e);return t.pages=t.pages.filter(i=>i.id!==e&&r!==Sc(i)),n}}function Fc(t,e){if(Z(e)&&Z(e.kind))return Z(e.kinddata)||(e.kinddata=Z(e.id)?XA(t,e.kind):EF(t,e.kind)),e.kinddata}function Bfe(t,e){const n=Fc(t,e);return{char:(e==null?void 0:e.char)??(n==null?void 0:n.char)??1,color:(e==null?void 0:e.color)??(n==null?void 0:n.color)??wn.WHITE,bg:(e==null?void 0:e.bg)??(n==null?void 0:n.bg)??wn.ONBORROW}}function XA(t,e){const n=e??"",r=SF(t,vn.OBJECT,n);if(Z(r)){const i=yF(r);return{...Ob(i),name:n,code:r.code}}}function EF(t,e){const n=e??"",r=SF(t,vn.TERRAIN,n);if(Z(r)){const i=yF(r);return{...Ob(i),name:n,code:r.code}}}function zfe(t,e){return t?(t.flags[e]=t.flags[e]??{},t.flags[e]):{}}function Vfe(t,e){t&&delete t.flags[e]}function Hfe(t,e,n,r){const i=Tv(e,(n==null?void 0:n.id)??"");if(!Z(t)||!Z(e)||!Z(i)||!Z(i.x)||!Z(i.y)||!Z(e.lookup)||r.x<0||r.x>=hi||r.y<0||r.y>=Sh||i.x-r.x===0&&i.y-r.y===0)return!0;const s=r.x+r.y*hi,o=Fc(t,i),a=i.collision??(o==null?void 0:o.collision),c=Tv(e,e.lookup[s]??"");if(Z(c))return!0;const l=e.terrain[s];if(Z(l)){const u=Fc(t,l),h=l.collision??(u==null?void 0:u.collision);if(c4(a,h))return!0}return!1}function Gfe(t,e,n,r){const i=Tv(e,(n==null?void 0:n.id)??"");if(!Z(t)||!Z(e)||!Z(i)||!Z(i.x)||!Z(i.y)||!Z(e.lookup)||r.x<0||r.x>=hi||r.y<0||r.y>=Sh)return{kind:"edge",collision:zn.ISSOLID,x:r.x,y:r.y};if(i.x-r.x===0&&i.y-r.y===0)return;const s=i.x+i.y*hi,o=r.x+r.y*hi,a=Fc(t,i),c=i.collision??(a==null?void 0:a.collision),l=Tv(e,e.lookup[o]??"");if(Z(l))return{...l};const u=e.terrain[o];if(Z(u)){const h=Fc(t,u),p=u.collision??(h==null?void 0:h.collision);if(c4(c,p))return{...u,x:r.x,y:r.y}}i.x=r.x,i.y=r.y,Z(i.removed)||(e.lookup[s]=void 0,e.lookup[o]=i.id??"")}function od(t,e){const n=Fc(t,e);return Z(e==null?void 0:e.id)&&Z(e.x)&&Z(e.y)?$t(e.name??(n==null?void 0:n.name)??"object"):$t((e==null?void 0:e.name)??(n==null?void 0:n.name)??"terrain")}function tb(t,e,n,r){if(!Z(t)||!Z(e)||!Z(e.named)||!Z(n))return;const i=od(t,n);e.named[i]||(e.named[i]=new Set),e.named[i].add((n==null?void 0:n.id)??r??"")}function Wfe(t,e,n){if(!(!Z(t)||!Z(e)||!Z(e.lookup)||!Z(n==null?void 0:n.id))&&!Z(n.removed)){const r=n.x??0,i=n.y??0;e.lookup[r+i*hi]=n.id}}function nb(t,e){if(!Z(t)||!Z(e)||Z(e.lookup)&&Z(e.named))return;const n=new Array(hi*Sh).fill(void 0),r={},i=Object.values(e.objects);for(let a=0;a=hi&&(s=0,++o)}e.lookup=n,e.named=r}function KA(t,e,n){return od(t,e)!=="player"&&Z(e)?(e.removed=n,!0):!1}function Ky(t,e,n){var r;if(Z(t)&&Z(e)&&Z(n==null?void 0:n.id)){if(Z(e.lookup)&&Z(n.x)&&Z(n.y)){const s=n.x+n.y*hi;e.lookup[s]===n.id&&e.lookup.splice(s,1)}const i=od(t,n);Z((r=e.named)==null?void 0:r[i])&&Z(n.id)&&e.named[i].delete(n.id)}}function jfe(t,e,n,r){if(Z(t)&&Z(e)&&Z(n)){const[i,s]=n,o=XA(t,i);if(Z(o)&&Z(o.name)){const a=O4(e,r,i);return bv(a,s),tb(t,e,a),a}}}function rb(t,e,n,r){if(Z(t)&&Z(e)&&Z(n)){const[i,s]=n,o=EF(t,i);if(Z(o)){const c=I4(e,r,i);bv(c,s);const l=r.x+r.y*hi;return tb(t,e,c,l),c}const a=XA(t,i);if(Z(a)&&Z(a.name)){const c=O4(e,r,i);return bv(c,s),Wfe(t,e,c),tb(t,e,c),c}}}function W0(t,e,n,r){const i=Kt(e)?e:e.id,s=Kt(e)?void 0:{x:e.x??0,y:e.y??0},o=Kt(n)?n:n.id,a=i??s;Z(o)&&Z(a)&&t.send(o,r,a)}function $fe(t,e,n,r){Z(n==null?void 0:n.id)?(n.headless=!0,Ky(t,e,n)):I4(e,r,"empty")}function TI(t,e,n,r,i){const s=Gfe(e,n,r,i);if(Z(s)){W0(t,s,t.id(),"thud"),r.kind===Mr.PLAYER?W0(t,t.id(),s,"touch"):r.collision===zn.ISBULLET?W0(t,t.id(),s,"shot"):W0(t,t.id(),s,"bump");const o=Fc(e,s);return(s.destructible??(o==null?void 0:o.destructible))&&$fe(e,n,s,i),!1}return!0}function AI(t,e,n){if(!xc(se.element))return 0;const[r,i]=Ve(e,0,[Ie.DIR,Ie.MAYBE_KIND]),s=i??["bullet"],o=jfe(se.book,se.board,s,{x:se.element.x,y:se.element.y});if(Z(o)){o.arg=n,o.collision=zn.ISBULLET,o.stepx=r.x-se.element.x,o.stepy=r.y-se.element.y;const a=Fc(se.book,o),c=o.code??(a==null?void 0:a.code)??"";xpe(se.book,se.board,o,c,1),o.x===se.element.x&&o.y===se.element.y?o.headless=!0:t.bucket(o.id)}return t.yield(),0}const qfe=Qc().command("change",(t,e)=>{if(!Z(se.book)||!Z(se.board))return 0;const[n,r]=Ve(e,0,[Ie.KIND,Ie.KIND]);nb(se.book,se.board);const i=wv(n)??"",s=Fm(se.board,i),o=l4(s,n),a=wv(r),c=o4(r),l=a4(r);return o.forEach(u=>{if(od(se.book,u)===a)Z(c)&&(u.color=c),Z(l)&&(u.bg=l);else{if(Z(u.id)&&(Ky(se.book,se.board,u),!KA(se.book,u,se.timestamp)))return;xc(u)&&rb(se.book,se.board,r,u)}}),0}).command("put",(t,e)=>{if(!Z(se.book)||!Z(se.board))return 0;const[n,r]=Ve(e,0,[Ie.DIR,Ie.KIND]);return nb(se.book,se.board),rb(se.book,se.board,r,n),0}).command("shootwith",(t,e)=>{const[n,r]=Ve(e,0,[Ie.ANY]);return AI(t,e.slice(r),n)}).command("shoot",AI).command("throwstar",()=>0),Xfe=Qc().command("send",(t,e)=>{const[n,r]=Ve(e,0,[Ie.STRING,Ie.ANY]);switch(n){case"helpmenu":gc("cli","H E L P"),rn("cli","#help controls","zss controls and inputs"),Bn("cli","!helpcontrols;read help controls"),Bn("cli",""),rn("cli","#help text","text formatting"),Bn("cli","!helptext;read help text"),Bn("cli",""),rn("cli","#help developer","developer commands"),Bn("cli","!helpdeveloper;read help developer"),Bn("cli",""),rn("cli","#help player","player settings"),Bn("cli","!helpplayer;read help player"),lc("cli","keyboard input"),rn("cli","?","open console"),rn("cli","esc","close console"),rn("cli","tab","move console"),rn("cli","up / down arrow keys","navigate console items"),rn("cli","left / right arrow keys","change console items"),rn("cli","enter","interact with console items"),rn("cli","alt + arrow keys","skip words and console lines"),rn("cli",`${$ce} + up / down arrow keys`,"input history");break;case"helpcontrols":gc("cli","zss controls and inputs"),lc("cli","keyboard input"),rn("cli","arrow keys","move"),rn("cli","shift + arrow keys","shoot"),rn("cli","enter","ok / accept"),rn("cli","escape","cancel / close"),rn("cli","tab","menu / action"),lc("cli","mouse input"),gn("cli","todo ???"),lc("cli","controller input"),rn("cli","left stick","move"),rn("cli","right stick","aim"),rn("cli","a","ok / accept"),rn("cli","b","cancel / close"),rn("cli","y","menu / action"),rn("cli","x","shoot"),rn("cli","triggers","shoot");break;case"helptext":gc("cli","text formatting"),lc("cli","typography"),gn("cli","plain text"),gn("cli","$centering text"),gn("cli",'"\\"@quoted strings for special chars\\""'),gn("cli","$$0-255 for ascii chars $159$176$240"),gn("cli",`use color names like ${As("red","$$red")} to change foreground color`),gn("cli",`use color names like ${_k("ongreen","$$ongreen")} to change background color`),gn("cli",`use clear ${_k("onclear","to change background to")} transparent`),lc("cli","hyperlinks"),gn("cli",`${As("white",'"!hotkey"')} message shortcut;${As("gray","Label")}`),gn("cli",`${As("white",'"!range"')} flag [labelmin] [labelmax];${As("gray","Input Label")}`),gn("cli",`${As("white",'"!select"')} flag ...list of values;${As("gray","Input Label")}`),gn("cli",`${As("white",'"!number"')} flag [minvalue] [maxvalue];${As("gray","Input Label")}`),gn("cli",`${As("white",'"!text"')} flag;${As("gray","Input Label")}`),gn("cli",`${As("white",'"!copyit"')} flag;${As("gray","Input Label")}`);break;case"helpdeveloper":gc("cli","developer commands"),rn("cli","#books","list books in memory"),rn("cli","#pages","list pages in opened book"),rn("cli","@[pagetype:]page name","create & edit a new codepage in the currently opened book"),rn("cli","#trash","list books and pages from open book you can delete"),rn("cli","#save","flush state to register");break;case"helpplayer":gc("cli","player settings"),gn("cli","todo");break;default:ro("$2",`${n} ${r??""}`);break}return 0}).command("stat",(t,e)=>{let n;const[r,...i]=e.map(ni),s=i.join(" ");switch($t(r)){case Js(dt.LOADER):n=Eu(Mr.CONTENT,s,vn.LOADER);break;default:n=Eu(Mr.CONTENT,[r,...i].join(" "),vn.OBJECT);break;case Js(dt.BOARD):n=Eu(Mr.CONTENT,s,vn.BOARD);break;case Js(dt.OBJECT):n=Eu(Mr.CONTENT,s,vn.OBJECT);break;case Js(dt.TERRAIN):n=Eu(Mr.CONTENT,s,vn.TERRAIN);break;case Js(dt.CHARSET):n=Eu(Mr.CONTENT,s,vn.CHARSET);break;case Js(dt.PALETTE):n=Eu(Mr.CONTENT,s,vn.PALETTE);break}return Z(n)&&t.command("pageopen",n.id),0}).command("text",(t,e)=>{const n=e.map(ni).join(" ");return ro("$2",n),0}).command("hyperlink",(t,e)=>{const[n,...r]=e,i=ni(n),s=r.map(ni).join(" ");return ro("$2",`!${s};${i}`),0}).command("dev",()=>(Tu("cli"),v9("cli",se.player),0)).command("share",()=>(Tu("cli"),y9("cli",se.player),0)).command("bookcreate",(t,e)=>{const[n]=Ve(e,0,[Ie.MAYBE_STRING]),r=HF(n);return Z(r)&&t.command("bookopen",r.id),0}).command("bookopen",(t,e)=>{const[n]=Ve(e,0,[Ie.STRING]),r=ad(n);return Z(r)?(gn("cli",`opened [book] ${r.name}`),lb(Mr.MAIN,r.id),t.command("pages")):Vn("cli","bookopen",`book ${n} not found`,se.player),0}).command("booktrash",(t,e)=>{const[n]=Ve(e,0,[Ie.STRING]),r=dp(Mr.MAIN),i=ad(n);return Z(i)&&(r===i&&lb(Mr.MAIN,""),vpe(n),gn("cli",`trashed [book] ${i.name}`),Tu("cli"),t.command("pages")),0}).command("pageopen",(t,e)=>{const[n]=Ve(e,0,[Ie.STRING]),r=Rc(Mr.MAIN);if(!Z(r))return 0;const i=Vm(r,n);if(Z(i)){const s=Sc(i),o=G0(i);gn("cli",`opened [${o}] ${s}`),FU(mL(r.id,i.id),i.code);const a=G0(i);M9("cli",r.id,i.id,a,`${s} - ${r.name}`,se.player)}else Vn("cli","pageopen",`page ${n} not found`,se.player);return 0}).command("pagetrash",(t,e)=>{const[n]=Ve(e,0,[Ie.STRING]),r=Rc(Mr.MAIN),i=Ffe(r,n);if(Z(n)){const s=Sc(i),o=G0(i);gn("cli",`trashed [${o}] ${s}`),Tu("cli"),t.command("pages")}return 0}).command("help",(t,e)=>{const n=e.map(ni).join(" ")||"menu";return t.command(`help${n}`),0}).command("books",()=>{lc("cli","books");const t=dp(Mr.MAIN);rn("cli","main",`${(t==null?void 0:t.name)??"empty"} $GREEN${(t==null?void 0:t.id)??""}`);const e=dp(Mr.CONTENT);rn("cli","content",`${(e==null?void 0:e.name)??"empty"} ${(e==null?void 0:e.id)??""}`),wA("cli",7);const n=cb();return n.length?n.forEach(r=>{Bn("cli",`!bookopen ${r.id};${r.name}`)}):gn("cli","no books found"),Bn("cli","!bookcreate;create a new book"),0}).command("pages",()=>{lc("cli","pages");const t=Rc(Mr.MAIN);return Z(t)&&(rn("cli","main",`${t.name} $GREEN${t.id}`),t.pages.length?t.pages.forEach(e=>{const n=Sc(e),r=G0(e);Bn("cli",`!pageopen ${e.id};[${r}] ${n}`)}):(Bn("cli",""),gn("cli","no pages found"),gn("cli","use @ to create a page"),gn("cli","@board name of board"),gn("cli","@object name of object"),gn("cli","@terrain name of terrain"),gn("cli","You can omit the type and it will default to object"),gn("cli","@object name of object"),gn("cli","@name of object"))),0}).command("trash",()=>{lc("cli","$REDTRASH"),gn("cli","books");const t=cb();t.length&&(t.forEach(n=>{Bn("cli",`!booktrash ${n.id};$REDTRASH ${n.name}`)}),Bn("cli",""));const e=dp(Mr.MAIN);return Z(e)&&(gn("cli",`pages in open ${e.name} book`),e.pages.forEach(n=>{const r=Sc(n);Bn("cli",`!pagetrash ${n.id};$REDTRASH ${r}`)}),Bn("cli","")),0}).command("save",()=>(Tu("cli"),0)).command("savewith",(t,e)=>{const[n]=Ve(e,0,[Ie.STRING]);return Tu("cli",n),0}).command("nuke",()=>(S9("cli"),0));function Kfe(t){const e=L4[t];if(Z(e))return e;const n=U4[t];if(Z(n))return n;const r=Jy[t];if(Z(r))return r;const i=r4[t];if(Z(i))return i}const Yfe=Qc({get(t,e){const n=Kfe(e);return Z(n)?[!0,n]:[!1,void 0]}}),Zfe=new Set(["inputmove","inputalt","inputctrl","inputshift","inputok","inputcancel","inputmenu"]),MI=new Set(["player","pushable","collision","destructible","p1","p2","p3","cycle","stepx","stepy","sender","arg"]),Jfe=["NORTH","SOUTH","WEST","EAST"];function Qfe(t){const e=Xp(t);if(cn(e.inputqueue)||(e.inputqueue=[],e.inputcurrent=0),mt(e.inputcurrent)&&e.inputcurrent>0)return;const[n]=e.inputqueue,[r=Ue.NONE,i=0]=n??[Ue.NONE,0];switch(e.inputmove=[],e.inputok=0,e.inputcancel=0,e.inputmenu=0,e.inputalt=i&QU?1:0,e.inputctrl=i&e3?1:0,e.inputshift=i&t3?1:0,r){case Ue.MOVE_UP:case Ue.MOVE_DOWN:case Ue.MOVE_LEFT:case Ue.MOVE_RIGHT:e.inputmove=[Jfe[r-Ue.MOVE_UP]];break;case Ue.OK_BUTTON:e.inputok=1;break;case Ue.CANCEL_BUTTON:e.inputcancel=1;break;case Ue.MENU_BUTTON:e.inputmenu=1;break}e.inputcurrent=r,e.inputqueue=e.inputqueue.filter(s=>{const[o]=s;return o!==Ue.NONE&&o!==r})}const ede=Qc({get(t,e){var s;se.isplayer&&Zfe.has(e)&&Qfe(t.id());const n=(s=se.element)==null?void 0:s[e];if(Z(n)||MI.has(e))return[!0,n];const i=Xp(se.player)[e];return[Z(i),i]},set(t,e,n){var s;const r=(s=se.element)==null?void 0:s[e];if(Z(r)||MI.has(e))return Z(se.element)&&(se.element[e]=n),[!0,n];const i=Xp(se.player);return i[e]=n,[!0,n]},everytick(t){var e,n;Z((e=se.element)==null?void 0:e.x)&&Z(se.element.y)&&Z(se.element.stepx)&&Z(se.element.stepy)&&TI(t,se.book,se.board,se.element,{x:se.element.x+se.element.stepx,y:se.element.y+se.element.stepy})===!1&&(se.element.stepx=0,se.element.stepy=0),(n=se.element)!=null&&n.headless&&t.command("die")}}).command("become",(t,e)=>{var i,s;const n={x:((i=se.element)==null?void 0:i.x)??0,y:((s=se.element)==null?void 0:s.y)??0},[r]=Ve(e,0,[Ie.KIND]);return nb(se.book,se.board),Ky(se.book,se.board,se.element),KA(se.book,se.element,se.timestamp)&&rb(se.book,se.board,r,n),t.endofprogram(),0}).command("bind",()=>0).command("char",(t,e)=>{const[n]=Ve(e,0,[Ie.NUMBER]);return Z(se.element)&&(se.element.char=n),0}).command("color",(t,e)=>{const[n]=Ve(e,0,[Ie.COLOR]);return Z(se.element)&&Z(n)&&bv(se.element,n),0}).command("go",(t,e)=>{if(Z(se.element)){const[n]=Ve(e,0,[Ie.DIR]);if(TI(t,se.book,se.board,se.element,n),t.yield(),se.element.x===n.x&&se.element.y===n.y)return 0}return 1}).command("try",(t,e)=>{const[,n]=Ve(e,0,[Ie.DIR]);return t.command("go",...e)&&n{if(!Z(se.element))return 0;const[n]=Ve(e,0,[Ie.DIR]),r=se.element.x??0,i=se.element.y??0;return se.element.stepx=n.x-r,se.element.stepy=n.y-i,0}),tde=Qc().command("clear",(t,e)=>(e.forEach(n=>t.set(ni(n),0)),0)).command("set",(t,e)=>{const[n,r]=Ve(e,0,[Ie.STRING,Ie.ANY]);return t.set(n,r),0}).command("take",(t,e)=>{const[n,r,i]=Ve(e,0,[Ie.STRING,Ie.MAYBE_NUMBER]),s=t.get(n),o=r??1;if(!mt(s))return 1;const a=s-o;return a<0?(i{const[n,r,i]=Ve(e,0,[Ie.STRING,Ie.MAYBE_NUMBER]),s=t.get(n),o=mt(s)?s:0,a=r??1;if(!mt(a))return 0;const c=s===void 0?1:0;return c&&i0&&y<_.lastIndexOf(" ")?c.low.call(g):g})},sentence:function(m,g,v){return m=l.lower(m).replace(a.sentence,function(y,_,S){return _+c.up.call(S)}),g&&g.forEach(function(y){m=m.replace(new RegExp("\\b"+l.lower(y)+"\\b","g"),c.cap)}),v&&v.forEach(function(y){m=m.replace(new RegExp("(\\b"+l.lower(y)+"\\. +)(\\w)"),function(_,S,E){return S+c.low.call(E)})}),m}};u.squish=u.pascal,l.default=l;for(var h in u)l.type(h,u[h]);var p=typeof p=="function"?p:function(){};p(t.exports?t.exports=l:this.Case=l)}).call(To)})(wF);var nde=wF.exports;const rde=Bc(nde),El={};function ide(t){return{player:t,layers:[],panels:[],reset:!0,focus:"scroll"}}function bF(t){t.text=[],Object.values(El[t.id]??{}).forEach(e=>e==null?void 0:e()),El[t.id]={}}function TF(t){const e=t.panels.find(n=>n.name===t.focus);if(!e){const n={id:fr(),name:t.focus,edge:Si.RIGHT,size:20,text:[]};return t.panels.push(n),t.reset=!1,n}return e}const sde=new Set(["hk","hotkey","rn","range","sl","select","nm","number","tx","text"]),ode=new Set(["rn","range","sl","select","nm","number","tx","text"]),ade=new Set(["tx","text"]),cde={rn:1,range:1,sl:0,select:0,nm:0,number:0,tx:"",text:""},CI={};let lde=t=>{let e=CI[t];return Z(e)||(CI[t]=e=ide(t)),e};function Yy(t){return lde(t)}function ude(t,e,n){Object.values(El).forEach(r=>{if(r[e]!==void 0){const i=xd(t.id(),e);mt(n)&&Rl(i,n),Kt(n)&&fae(i,n)}})}function hde(t){let e="";const n=Yy(t);return n.panels=n.panels.filter(r=>{if(r.edge===Si.SCROLL){const[i]=r.text;return Kt(i)&&r.text.length===1&&(e=i),r.text.length>1}return!0}),e}function LS(t,e,n,r,i){const s=Yy(t),o=r,a=i??rde.capital(e),c=s.panels.find(l=>l.name===a);if(c)s.reset=!0,s.focus=a,mt(o)&&(c.size=o);else switch(n){case Si.START:break;case Si.LEFT:case Si.RIGHT:case Si.TOP:case Si.BOTTOM:case Si.SCROLL:{const l={id:fr(),name:a,edge:n,size:o??rce[n],text:[]};s.panels.push(l),s.focus=a;break}}}function fde(t,e){const n=Yy(t),r=TF(n);n.reset&&(n.reset=!1,bF(r)),r.text.push(e)}function dde(t,e,n,r,i){const s=Yy(t),o=TF(s);s.reset&&(s.reset=!1,bF(o));const a=$t(r),c=[e.id(),n,...sde.has(a)?[a]:["hyperlink",r],...i],l=c[2];if(ode.has(l)){const u=`${c[3]??""}`;El[o.id]=El[o.id]??{};const h=e.get(u)??cde[l];if(El[o.id][u]===void 0){const p=xd(e.id(),u);mt(h)&&hae(p,h),Kt(h)&&FU(p,h),ade.has(l)?El[o.id][u]=pae(p,m=>{Z(m)&&m!==e.get(u)&&e.set(u,m)}):El[o.id][u]=dae(p,m=>{Z(m)&&m!==e.get(u)&&e.set(u,m)})}}o.text.push(c)}const pde=Qc({get(){return[!1,void 0]},set(t,e,n){return ude(t,e,n),[!1,void 0]},tick(){var e;const t=((e=se.element)==null?void 0:e.name)??"scroll";LS(se.player,"scroll",Si.SCROLL,void 0,t)},everytick(){const t=hde(se.player);if(t&&Z(se.element)){se.element.tickertext=t,se.element.tickertime=se.timestamp;const e=Bfe(se.book,se.element);ro(`$${wn[e.color]}$${e.char}`,t)}}}).command("send",(t,e)=>{var u,h;const[n,r]=Ve(e,0,[Ie.STRING,Ie.ANY]),[i,s]=n.split(":"),o=Z(s)?i:"self",a=s??i;function c(p){p.forEach(m=>{Z(m.id)&&t.send(m.id,a,r)})}const l=$t(o);switch(l){case"all":for(const p of Object.keys(((u=se.board)==null?void 0:u.objects)??{}))t.send(p,a,r);break;case"self":t.message({id:fr(),sender:t.id(),target:a,data:r});break;case"others":for(const p of Object.keys(((h=se.board)==null?void 0:h.objects)??{}))p!==t.id()&&t.send(p,a,r);break;default:{c(CS(se.board,[o]));const p=t.get(l);cn(p)?c(CS(se.board,p)):c(CS(se.board,[p]));break}}return 0}).command("stat",(t,e)=>{const n=_F(e.map(ni));switch(n.type){case dt.OBJECT:Z(se.element)&&(se.element.name=n.values.join(" "));break}return 0}).command("text",(t,e)=>{const n=e.map(ni).join("");return fde(se.player,n),0}).command("hyperlink",(t,e)=>{const[n,r,...i]=e,s=ni(n),o=ni(r);return dde(se.player,t,s,o,i),0}).command("gadget",(t,e)=>{const[n]=Ve(e,0,[Ie.STRING]),r=nce[$t(n)];if(r===Si.SCROLL){const[i,s]=Ve(e,1,[Ie.MAYBE_STRING,Ie.MAYBE_NUMBER]);LS(se.player,n,r,s,i)}else if(Z(r)){const[i,s]=Ve(e,1,[Ie.MAYBE_NUMBER,Ie.MAYBE_STRING]);LS(se.player,n,r,i,s)}return 0}),mde=Qc().command("idle",t=>(t.yield(),0)).command("end",t=>(t.endofprogram(),0)).command("endwith",(t,e)=>{const[n]=Ve(e,0,[Ie.ANY]);return t.set("arg",n),t.command("end")}).command("lock",t=>(t.lock(t.id()),0)).command("restore",(t,e)=>(t.restore(ni(e[0])),0)).command("unlock",t=>(t.unlock(),0)).command("zap",(t,e)=>(t.zap(ni(e[0])),0)).command("cycle",(t,e)=>{if(Z(se.element)){const[n]=Ve(e,0,[Ie.NUMBER]);se.element.cycle=Cn(Math.round(n),1,255)}return 0}).command("die",t=>{var e;return(e=se.element)!=null&&e.headless&&Ky(se.book,se.board,se.element),KA(se.book,se.element,se.timestamp),t.endofprogram(),0}).command("endgame",()=>(I9("element",se.player),0)).command("run",(t,e)=>{const[n]=Ve(e,0,[Ie.STRING]);return Mv(n),0}).command("runwith",(t,e)=>{const[n,r]=Ve(e,0,[Ie.ANY,Ie.STRING]);return t.set("arg",n),Mv(r),0});function RI(t,e){if(!Z(t))return;const n=$t(e),r=n.endsWith("le");switch(n){case"float32":case"float32le":{const i=t.dataview.getFloat32(t.cursor,r);return t.cursor+=4,i}case"float64":case"float64le":{const i=t.dataview.getFloat64(t.cursor,r);return t.cursor+=8,i}case"int8":case"int8le":{const i=t.dataview.getInt8(t.cursor);return t.cursor+=1,i}case"int16":case"int16le":{const i=t.dataview.getInt16(t.cursor,r);return t.cursor+=2,i}case"int32":case"int32le":{const i=t.dataview.getInt32(t.cursor,r);return t.cursor+=4,i}case"int64":case"int64le":{const i=t.dataview.getBigInt64(t.cursor,r);return t.cursor+=8,i}case"uint8":case"uint8le":{const i=t.dataview.getUint8(t.cursor);return t.cursor+=1,i}case"uint16":case"uint16le":{const i=t.dataview.getUint16(t.cursor,r);return t.cursor+=2,i}case"uint32":case"uint32le":{const i=t.dataview.getUint32(t.cursor,r);return t.cursor+=4,i}case"uint64":case"uint64le":{const i=t.dataview.getBigUint64(t.cursor,r);return t.cursor+=8,i}}}const gde=(t,e)=>{const n=WF(t.id());if(!Z(n))return 0;const[r]=Ve(e,0,[Ie.STRING]),i=$t(r);switch(i){case"seek":{const[s]=Ve(e,1,[Ie.NUMBER]);n.cursor=s;break}case"float32":case"float32le":case"float64":case"float64le":case"int8":case"int8le":case"int16":case"int16le":case"int32":case"int32le":case"int64":case"int64le":case"uint8":case"uint8le":case"uint16":case"uint16le":case"uint32":case"uint32le":case"uint64":case"uint64le":{const[s]=Ve(e,1,[Ie.STRING]);t.set(s,RI(n,i));break}case"text":{const[s,o]=Ve(e,1,[Ie.STRING,Ie.STRING]),a=RI(n,s);if(mt(a)&&Kt(o)){const c=new Uint8Array(n.bytes.buffer,n.cursor,a),u=new TextDecoder("utf-8").decode(c);t.set(o,u),n.cursor+=a}break}}return 0},_de=Qc({get(t,e){const n=WF(t.id());if(Z(n))switch($t(e)){case"filename":return[Z(n.filename),n.filename];case"cursor":return[Z(n.cursor),n.cursor]}return[!1,void 0]}}).command("send",(t,e)=>{const[n,r]=Ve(e,0,[Ie.STRING,Ie.ANY]);return t.message({id:fr(),sender:t.id(),target:n,data:r}),0}).command("stat",()=>0).command("text",(t,e)=>{const n=e.map(ni).join(" ");return ro("$2",n),0}).command("hyperlink",(t,e)=>{const[n,...r]=e,i=ni(n),s=r.map(ni).join(" ");return ro("$2",`!${s};${i}`),0}).command("load",(t,e)=>{const n=e.map(ni).join(" "),r=t.get(n)??n;return Rc(Mr.CONTENT,r),0}).command("reload",(t,e)=>{const n=e.map(ni).join(" "),r=t.get(n)??n,i=Rc(Mr.CONTENT,r);return i.pages=[],0}).command("bin",gde);var YA=(t=>(t[t.ERROR=0]="ERROR",t[t.CLI=1]="CLI",t[t.LOADER=2]="LOADER",t[t.CODE_PAGE=3]="CODE_PAGE",t))(YA||{});const vde={audio:Cfe,board:qfe,cli:Xfe,const:Yfe,element:ede,flags:tde,gadget:pde,lifecycle:mde,loader:_de},PS=["const","flags","audio","board","lifecycle","element"],yde={0:[],1:["cli",...PS],2:["loader",...PS],3:["gadget",...PS]},xde={0:new Map,1:new Map,2:new Map,3:new Map};function Hm(t){return(yde[t]??[]).map(n=>vde[n]).filter(Z)}function Sde(t,e){const n=xde[t];if(!n.has(e)){let r;const i=Hm(t);for(let s=0;s>>=RF,i>0&&(r|=Mde),n+=Tde.encode(r);while(i>0);return n};var Gm={};(function(t){function e(R,M,O){if(M in R)return R[M];if(arguments.length===3)return O;throw new Error('"'+M+'" is a required argument.')}t.getArg=e;const n=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(R){const M=R.match(n);return M?{scheme:M[1],auth:M[2],host:M[3],port:M[4],path:M[5]}:null}t.urlParse=i;function s(R){let M="";return R.scheme&&(M+=R.scheme+":"),M+="//",R.auth&&(M+=R.auth+"@"),R.host&&(M+=R.host),R.port&&(M+=":"+R.port),R.path&&(M+=R.path),M}t.urlGenerate=s;const o=32;function a(R){const M=[];return function(O){for(let I=0;Io&&M.pop(),C}}const c=a(function(M){let O=M;const C=i(M);if(C){if(!C.path)return M;O=C.path}const I=t.isAbsolute(O),U=[];let L=0,P=0;for(;;)if(L=P,P=O.indexOf("/",L),P===-1){U.push(O.slice(L));break}else for(U.push(O.slice(L,P));P=0;P--){const H=U[P];H==="."?U.splice(P,1):H===".."?T++:T>0&&(H===""?(U.splice(P+1,T),T=0):(U.splice(P,2),T--))}return O=U.join("/"),O===""&&(O=I?"/":"."),C?(C.path=O,s(C)):O});t.normalize=c;function l(R,M){R===""&&(R="."),M===""&&(M=".");const O=i(M),C=i(R);if(C&&(R=C.path||"/"),O&&!O.scheme)return C&&(O.scheme=C.scheme),s(O);if(O||M.match(r))return M;if(C&&!C.host&&!C.path)return C.host=M,s(C);const I=M.charAt(0)==="/"?M:c(R.replace(/\/+$/,"")+"/"+M);return C?(C.path=I,s(C)):I}t.join=l,t.isAbsolute=function(R){return R.charAt(0)==="/"||n.test(R)};function u(R,M){R===""&&(R="."),R=R.replace(/\/$/,"");let O=0;for(;M.indexOf(R+"/")!==0;){const C=R.lastIndexOf("/");if(C<0||(R=R.slice(0,C),R.match(/^([^\/]+:\/)?\/*$/)))return M;++O}return Array(O+1).join("../")+M.substr(R.length+1)}t.relative=u;const h=function(){return!("__proto__"in Object.create(null))}();function p(R){return R}function m(R){return v(R)?"$"+R:R}t.toSetString=h?p:m;function g(R){return v(R)?R.slice(1):R}t.fromSetString=h?p:g;function v(R){if(!R)return!1;const M=R.length;if(M<9||R.charCodeAt(M-1)!==95||R.charCodeAt(M-2)!==95||R.charCodeAt(M-3)!==111||R.charCodeAt(M-4)!==116||R.charCodeAt(M-5)!==111||R.charCodeAt(M-6)!==114||R.charCodeAt(M-7)!==112||R.charCodeAt(M-8)!==95||R.charCodeAt(M-9)!==95)return!1;for(let O=M-10;O>=0;O--)if(R.charCodeAt(O)!==36)return!1;return!0}function y(R,M,O){let C=S(R.source,M.source);return C!==0||(C=R.originalLine-M.originalLine,C!==0)||(C=R.originalColumn-M.originalColumn,C!==0||O)||(C=R.generatedColumn-M.generatedColumn,C!==0)||(C=R.generatedLine-M.generatedLine,C!==0)?C:S(R.name,M.name)}t.compareByOriginalPositions=y;function _(R,M,O){let C=R.generatedLine-M.generatedLine;return C!==0||(C=R.generatedColumn-M.generatedColumn,C!==0||O)||(C=S(R.source,M.source),C!==0)||(C=R.originalLine-M.originalLine,C!==0)||(C=R.originalColumn-M.originalColumn,C!==0)?C:S(R.name,M.name)}t.compareByGeneratedPositionsDeflated=_;function S(R,M){return R===M?0:R===null?1:M===null?-1:R>M?1:-1}function E(R,M){let O=R.generatedLine-M.generatedLine;return O!==0||(O=R.generatedColumn-M.generatedColumn,O!==0)||(O=S(R.source,M.source),O!==0)||(O=R.originalLine-M.originalLine,O!==0)||(O=R.originalColumn-M.originalColumn,O!==0)?O:S(R.name,M.name)}t.compareByGeneratedPositionsInflated=E;function b(R){return JSON.parse(R.replace(/^\)]}'[^\n]*\n/,""))}t.parseSourceMapInput=b;function N(R,M,O){if(M=M||"",R&&(R[R.length-1]!=="/"&&M[0]!=="/"&&(R+="/"),M=R+M),O){const C=i(O);if(!C)throw new Error("sourceMapURL could not be parsed");if(C.path){const I=C.path.lastIndexOf("/");I>=0&&(C.path=C.path.substring(0,I+1))}M=l(s(C),M)}return c(M)}t.computeSourceURL=N})(Gm);var ZA={};let Rde=class kF{constructor(){this._array=[],this._set=new Map}static fromArray(e,n){const r=new kF;for(let i=0,s=e.length;i=0)return n;throw new Error('"'+e+'" is not in the set.')}at(e){if(e>=0&&en||r==n&&s>=i||OF.compareByGeneratedPositionsInflated(t,e)<=0}let kde=class{constructor(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}unsortedForEach(e,n){this._array.forEach(e,n)}add(e){Nde(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))}toArray(){return this._sorted||(this._array.sort(OF.compareByGeneratedPositionsInflated),this._sorted=!0),this._array}};IF.MappingList=kde;const ep=MF,wr=Gm,j0=ZA.ArraySet,Ide=IF.MappingList;let LF=class PF{constructor(e){e||(e={}),this._file=wr.getArg(e,"file",null),this._sourceRoot=wr.getArg(e,"sourceRoot",null),this._skipValidation=wr.getArg(e,"skipValidation",!1),this._sources=new j0,this._names=new j0,this._mappings=new Ide,this._sourcesContents=null}static fromSourceMap(e){const n=e.sourceRoot,r=new PF({file:e.file,sourceRoot:n});return e.eachMapping(function(i){const s={generated:{line:i.generatedLine,column:i.generatedColumn}};i.source!=null&&(s.source=i.source,n!=null&&(s.source=wr.relative(n,s.source)),s.original={line:i.originalLine,column:i.originalColumn},i.name!=null&&(s.name=i.name)),r.addMapping(s)}),e.sources.forEach(function(i){let s=i;n!==null&&(s=wr.relative(n,i)),r._sources.has(s)||r._sources.add(s);const o=e.sourceContentFor(i);o!=null&&r.setSourceContent(i,o)}),r}addMapping(e){const n=wr.getArg(e,"generated"),r=wr.getArg(e,"original",null);let i=wr.getArg(e,"source",null),s=wr.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,i,s),i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),s!=null&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:i,name:s})}setSourceContent(e,n){let r=e;this._sourceRoot!=null&&(r=wr.relative(this._sourceRoot,r)),n!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[wr.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[wr.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))}applySourceMap(e,n,r){let i=n;if(n==null){if(e.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);i=e.file}const s=this._sourceRoot;s!=null&&(i=wr.relative(s,i));const o=this._mappings.toArray().length>0?new j0:this._sources,a=new j0;this._mappings.unsortedForEach(function(c){if(c.source===i&&c.originalLine!=null){const h=e.originalPositionFor({line:c.originalLine,column:c.originalColumn});h.source!=null&&(c.source=h.source,r!=null&&(c.source=wr.join(r,c.source)),s!=null&&(c.source=wr.relative(s,c.source)),c.originalLine=h.line,c.originalColumn=h.column,h.name!=null&&(c.name=h.name))}const l=c.source;l!=null&&!o.has(l)&&o.add(l);const u=c.name;u!=null&&!a.has(u)&&a.add(u)},this),this._sources=o,this._names=a,e.sources.forEach(function(c){const l=e.sourceContentFor(c);l!=null&&(r!=null&&(c=wr.join(r,c)),s!=null&&(c=wr.relative(s,c)),this.setSourceContent(c,l))},this)}_validateMapping(e,n,r,i){if(n&&typeof n.line!="number"&&typeof n.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!n&&!r&&!i)){if(!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:i}))}}_serializeMappings(){let e=0,n=1,r=0,i=0,s=0,o=0,a="",c,l,u,h;const p=this._mappings.toArray();for(let m=0,g=p.length;m0){if(!wr.compareByGeneratedPositionsInflated(l,p[m-1]))continue;c+=","}c+=ep.encode(l.generatedColumn-e),e=l.generatedColumn,l.source!=null&&(h=this._sources.indexOf(l.source),c+=ep.encode(h-o),o=h,c+=ep.encode(l.originalLine-1-i),i=l.originalLine-1,c+=ep.encode(l.originalColumn-r),r=l.originalColumn,l.name!=null&&(u=this._names.indexOf(l.name),c+=ep.encode(u-s),s=u)),a+=c}return a}_generateSourcesContent(e,n){return e.map(function(r){if(!this._sourcesContents)return null;n!=null&&(r=wr.relative(n,r));const i=wr.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null},this)}toJSON(){const e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e}toString(){return JSON.stringify(this.toJSON())}};LF.prototype._version=3;AF.SourceMapGenerator=LF;var DF={};(function(t){t.GREATEST_LOWER_BOUND=1,t.LEAST_UPPER_BOUND=2;function e(n,r,i,s,o,a){const c=Math.floor((r-n)/2)+n,l=o(i,s[c],!0);return l===0?c:l>0?r-c>1?e(c,r,i,s,o,a):a==t.LEAST_UPPER_BOUND?r1?e(n,c,i,s,o,a):a==t.LEAST_UPPER_BOUND?c:n<0?-1:n}t.search=function(r,i,s,o){if(i.length===0)return-1;let a=e(-1,i.length,r,i,s,o||t.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&s(i[a],i[a-1],!0)===0;)--a;return a}})(DF);var up={exports:{}};const Ode={},Lde=Object.freeze(Object.defineProperty({__proto__:null,default:Ode},Symbol.toStringTag,{value:"Module"})),II=JB(Lde),Pde=(function(){return typeof window<"u"&&this===window}).call();if(Pde){let t=null;up.exports=function(){if(typeof t=="string")return fetch(t).then(n=>n.arrayBuffer());if(t instanceof ArrayBuffer)return Promise.resolve(t);throw new Error("You must provide the string URL or ArrayBuffer contents of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer")},up.exports.initialize=e=>t=e}else{const t=II,e=II;up.exports=function(){return new Promise((r,i)=>{const s=e.join(__dirname,"mappings.wasm");t.readFile(s,null,(o,a)=>{if(o){i(o);return}r(a.buffer)})})},up.exports.initialize=n=>{console.debug("SourceMapConsumer.initialize is a no-op when running in node.js")}}var UF=up.exports;const Dde=UF;function Ude(){this.generatedLine=0,this.generatedColumn=0,this.lastGeneratedColumn=null,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}let tp=null;var Fde=function(){if(tp)return tp;const e=[];return tp=Dde().then(n=>WebAssembly.instantiate(n,{env:{mapping_callback(r,i,s,o,a,c,l,u,h,p){const m=new Ude;m.generatedLine=r+1,m.generatedColumn=i,s&&(m.lastGeneratedColumn=o-1),a&&(m.source=c,m.originalLine=l+1,m.originalColumn=u,h&&(m.name=p)),e[e.length-1](m)},start_all_generated_locations_for(){console.time("all_generated_locations_for")},end_all_generated_locations_for(){console.timeEnd("all_generated_locations_for")},start_compute_column_spans(){console.time("compute_column_spans")},end_compute_column_spans(){console.timeEnd("compute_column_spans")},start_generated_location_for(){console.time("generated_location_for")},end_generated_location_for(){console.timeEnd("generated_location_for")},start_original_location_for(){console.time("original_location_for")},end_original_location_for(){console.timeEnd("original_location_for")},start_parse_mappings(){console.time("parse_mappings")},end_parse_mappings(){console.timeEnd("parse_mappings")},start_sort_by_generated_location(){console.time("sort_by_generated_location")},end_sort_by_generated_location(){console.timeEnd("sort_by_generated_location")},start_sort_by_original_location(){console.time("sort_by_original_location")},end_sort_by_original_location(){console.timeEnd("sort_by_original_location")}}})).then(n=>({exports:n.instance.exports,withMappingCallback:(r,i)=>{e.push(r);try{i()}finally{e.pop()}}})).then(null,n=>{throw tp=null,n}),tp};const _t=Gm,DS=DF,Av=ZA.ArraySet,Bde=UF,zde=Fde,JA=Symbol("smcInternal");class dr{constructor(e,n){return e==JA?Promise.resolve(this):Hde(e,n)}static initialize(e){Bde.initialize(e["lib/mappings.wasm"])}static fromSourceMap(e,n){return Gde(e,n)}static async with(e,n,r){const i=await new dr(e,n);try{return await r(i)}finally{i.destroy()}}_parseMappings(e,n){throw new Error("Subclasses must implement _parseMappings")}eachMapping(e,n,r){throw new Error("Subclasses must implement eachMapping")}allGeneratedPositionsFor(e){throw new Error("Subclasses must implement allGeneratedPositionsFor")}destroy(){throw new Error("Subclasses must implement destroy")}}dr.prototype._version=3;dr.GENERATED_ORDER=1;dr.ORIGINAL_ORDER=2;dr.GREATEST_LOWER_BOUND=1;dr.LEAST_UPPER_BOUND=2;class Wm extends dr{constructor(e,n){return super(JA).then(r=>{let i=e;typeof e=="string"&&(i=_t.parseSourceMapInput(e));const s=_t.getArg(i,"version");let o=_t.getArg(i,"sources");const a=_t.getArg(i,"names",[]);let c=_t.getArg(i,"sourceRoot",null);const l=_t.getArg(i,"sourcesContent",null),u=_t.getArg(i,"mappings"),h=_t.getArg(i,"file",null);if(s!=r._version)throw new Error("Unsupported version: "+s);return c&&(c=_t.normalize(c)),o=o.map(String).map(_t.normalize).map(function(p){return c&&_t.isAbsolute(c)&&_t.isAbsolute(p)?_t.relative(c,p):p}),r._names=Av.fromArray(a.map(String),!0),r._sources=Av.fromArray(o,!0),r._absoluteSources=r._sources.toArray().map(function(p){return _t.computeSourceURL(c,p,n)}),r.sourceRoot=c,r.sourcesContent=l,r._mappings=u,r._sourceMapURL=n,r.file=h,r._computedColumnSpans=!1,r._mappingsPtr=0,r._wasm=null,zde().then(p=>(r._wasm=p,r))})}_findSourceIndex(e){let n=e;if(this.sourceRoot!=null&&(n=_t.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);for(let r=0;r{a.source!==null&&(a.source=this._sources.at(a.source),a.source=_t.computeSourceURL(o,a.source,this._sourceMapURL),a.name!==null&&(a.name=this._names.at(a.name))),e.call(i,a)},()=>{switch(s){case dr.GENERATED_ORDER:this._wasm.exports.by_generated_location(this._getMappingsPtr());break;case dr.ORIGINAL_ORDER:this._wasm.exports.by_original_location(this._getMappingsPtr());break;default:throw new Error("Unknown order of iteration.")}})}allGeneratedPositionsFor(e){let n=_t.getArg(e,"source");const r=_t.getArg(e,"line"),i=e.column||0;if(n=this._findSourceIndex(n),n<0)return[];if(r<1)throw new Error("Line numbers must be >= 1");if(i<0)throw new Error("Column numbers must be >= 0");const s=[];return this._wasm.withMappingCallback(o=>{let a=o.lastGeneratedColumn;this._computedColumnSpans&&a===null&&(a=1/0),s.push({line:o.generatedLine,column:o.generatedColumn,lastColumn:a})},()=>{this._wasm.exports.all_generated_locations_for(this._getMappingsPtr(),n,r-1,"column"in e,i)}),s}destroy(){this._mappingsPtr!==0&&(this._wasm.exports.free_mappings(this._mappingsPtr),this._mappingsPtr=0)}computeColumnSpans(){this._computedColumnSpans||(this._wasm.exports.compute_column_spans(this._getMappingsPtr()),this._computedColumnSpans=!0)}originalPositionFor(e){const n={generatedLine:_t.getArg(e,"line"),generatedColumn:_t.getArg(e,"column")};if(n.generatedLine<1)throw new Error("Line numbers must be >= 1");if(n.generatedColumn<0)throw new Error("Column numbers must be >= 0");let r=_t.getArg(e,"bias",dr.GREATEST_LOWER_BOUND);r==null&&(r=dr.GREATEST_LOWER_BOUND);let i;if(this._wasm.withMappingCallback(s=>i=s,()=>{this._wasm.exports.original_location_for(this._getMappingsPtr(),n.generatedLine-1,n.generatedColumn,r)}),i&&i.generatedLine===n.generatedLine){let s=_t.getArg(i,"source",null);s!==null&&(s=this._sources.at(s),s=_t.computeSourceURL(this.sourceRoot,s,this._sourceMapURL));let o=_t.getArg(i,"name",null);return o!==null&&(o=this._names.at(o)),{source:s,line:_t.getArg(i,"originalLine",null),column:_t.getArg(i,"originalColumn",null),name:o}}return{source:null,line:null,column:null,name:null}}hasContentsOfAllSources(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1}sourceContentFor(e,n){if(!this.sourcesContent)return null;const r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];let i=e;this.sourceRoot!=null&&(i=_t.relative(this.sourceRoot,i));let s;if(this.sourceRoot!=null&&(s=_t.urlParse(this.sourceRoot))){const o=i.replace(/^file:\/\//,"");if(s.scheme=="file"&&this._sources.has(o))return this.sourcesContent[this._sources.indexOf(o)];if((!s.path||s.path=="/")&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(n)return null;throw new Error('"'+i+'" is not in the SourceMap.')}generatedPositionFor(e){let n=_t.getArg(e,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};const r={source:n,originalLine:_t.getArg(e,"line"),originalColumn:_t.getArg(e,"column")};if(r.originalLine<1)throw new Error("Line numbers must be >= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");let i=_t.getArg(e,"bias",dr.GREATEST_LOWER_BOUND);i==null&&(i=dr.GREATEST_LOWER_BOUND);let s;if(this._wasm.withMappingCallback(o=>s=o,()=>{this._wasm.exports.generated_location_for(this._getMappingsPtr(),r.source,r.originalLine-1,r.originalColumn,i)}),s&&s.source===r.source){let o=s.lastGeneratedColumn;return this._computedColumnSpans&&o===null&&(o=1/0),{line:_t.getArg(s,"generatedLine",null),column:_t.getArg(s,"generatedColumn",null),lastColumn:o}}return{line:null,column:null,lastColumn:null}}}Wm.prototype.consumer=dr;class Vde extends dr{constructor(e,n){return super(JA).then(r=>{let i=e;typeof e=="string"&&(i=_t.parseSourceMapInput(e));const s=_t.getArg(i,"version"),o=_t.getArg(i,"sections");if(s!=r._version)throw new Error("Unsupported version: "+s);r._sources=new Av,r._names=new Av,r.__generatedMappings=null,r.__originalMappings=null,r.__generatedMappingsUnsorted=null,r.__originalMappingsUnsorted=null;let a={line:-1,column:0};return Promise.all(o.map(c=>{if(c.url)throw new Error("Support for url field in sections not implemented.");const l=_t.getArg(c,"offset"),u=_t.getArg(l,"line"),h=_t.getArg(l,"column");if(u({generatedOffset:{generatedLine:u+1,generatedColumn:h+1},consumer:m}))})).then(c=>(r._sections=c,r))})}get _generatedMappings(){return this.__generatedMappings||this._sortGeneratedMappings(),this.__generatedMappings}get _originalMappings(){return this.__originalMappings||this._sortOriginalMappings(),this.__originalMappings}get _generatedMappingsUnsorted(){return this.__generatedMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappingsUnsorted}get _originalMappingsUnsorted(){return this.__originalMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappingsUnsorted}_sortGeneratedMappings(){const e=this._generatedMappingsUnsorted;e.sort(_t.compareByGeneratedPositionsDeflated),this.__generatedMappings=e}_sortOriginalMappings(){const e=this._originalMappingsUnsorted;e.sort(_t.compareByOriginalPositions),this.__originalMappings=e}get sources(){const e=[];for(let n=0;na.push(c));for(let c=0;c= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");const i=[];let s=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",_t.compareByOriginalPositions,DS.LEAST_UPPER_BOUND);if(s>=0){let o=this._originalMappings[s];if(e.column===void 0){const a=o.originalLine;for(;o&&o.originalLine===a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:_t.getArg(o,"generatedLine",null),column:_t.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}else{const a=o.originalColumn;for(;o&&o.originalLine===n&&o.originalColumn==a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:_t.getArg(o,"generatedLine",null),column:_t.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}}return i}destroy(){for(let e=0;e=0;n--)this.prepend(e[n]);else if(e[rf]||typeof e=="string")this.children.unshift(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this}walk(e){let n;for(let r=0,i=this.children.length;r0){for(n=[],r=0;r{this.MANY(()=>this.SUBRULE(this.line))}));vt(this,"line",this.RULED("line",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt)},{ALT:()=>this.CONSUME(qp)}])}));vt(this,"stmt",this.RULED("stmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.short_commands)),this.MANY(()=>this.SUBRULE(this.commands))}}])}));vt(this,"inline",this.RULED("inline",()=>{this.SUBRULE(this.instmt)}));vt(this,"instmt",this.RULED("instmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}])}));vt(this,"stmt_label",this.RULED("stmt_label",()=>{this.CONSUME(H4)}));vt(this,"stmt_stat",this.RULED("stmt_stat",()=>{this.CONSUME(jA)}));vt(this,"stmt_text",this.RULED("stmt_text",()=>{this.OR([{ALT:()=>this.CONSUME(z4)}])}));vt(this,"stmt_comment",this.RULED("stmt_comment",()=>{this.CONSUME(V4)}));vt(this,"stmt_hyperlink",this.RULED("stmt_hyperlink",()=>{this.CONSUME(G4),this.SUBRULE(this.words),this.CONSUME(W4)}));vt(this,"stmt_command",this.RULED("stmt_command",()=>{this.CONSUME(uf),this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}));vt(this,"short_commands",this.RULED("short_commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)}])}));vt(this,"commands",this.RULED("commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.words)},{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)},{ALT:()=>this.SUBRULE(this.command_play)},{ALT:()=>this.SUBRULE(this.structured_cmd)}])}));vt(this,"structured_cmd",this.RULED("structured_cmd",()=>{this.OR([{ALT:()=>this.SUBRULE(this.command_debugger)},{ALT:()=>this.SUBRULE(this.command_if)},{ALT:()=>this.SUBRULE(this.command_while)},{ALT:()=>this.SUBRULE(this.command_repeat)},{ALT:()=>this.SUBRULE(this.command_waitfor)},{ALT:()=>this.SUBRULE(this.command_foreach)},{ALT:()=>this.SUBRULE(this.command_break)},{ALT:()=>this.SUBRULE(this.command_continue)}])}));vt(this,"short_go",this.RULED("short_go",()=>{this.CONSUME(Zw),this.SUBRULE(this.words)}));vt(this,"short_try",this.RULED("short_try",()=>{this.CONSUME(rF),this.SUBRULE(this.words)}));vt(this,"command_debugger",this.RULED("command_debugger",()=>{this.CONSUME(aF)}));vt(this,"command_if",this.RULED("command_if",()=>{this.CONSUME(Jw),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_if_block))}));vt(this,"command_if_block",this.RULED("command_if_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(N_),this.MANY(()=>this.SUBRULE(this.line)),this.MANY2({GATE:this.BACKTRACK(this.command_else_if),DEF:()=>this.SUBRULE(this.command_else_if)}),this.OPTION(()=>this.SUBRULE(this.command_else)),this.MANY3(()=>this.CONSUME3(qp)),this.CONSUME4(uf),this.CONSUME4(Qw)}}])}));vt(this,"command_block",this.RULED("command_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(N_),this.MANY(()=>this.SUBRULE(this.line)),this.CONSUME(uf),this.CONSUME(Qw)}}])}));vt(this,"command_fork",this.RULED("command_fork",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(N_),this.MANY({GATE:this.BACKTRACK(this.line),DEF:()=>this.SUBRULE(this.line)})}}])}));vt(this,"command_else_if",this.RULED("command_else_if",()=>{this.CONSUME(uf),this.CONSUME(eb),this.CONSUME(Jw),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_fork))}));vt(this,"command_else",this.RULED("command_else",()=>{this.CONSUME(uf),this.CONSUME(eb),this.OPTION(()=>this.SUBRULE(this.command_fork))}));vt(this,"command_while",this.RULED("command_while",()=>{this.CONSUME(cF),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));vt(this,"command_repeat",this.RULED("command_repeat",()=>{this.CONSUME(lF),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));vt(this,"command_waitfor",this.RULED("command_waitfor",()=>{this.CONSUME(uF),this.SUBRULE(this.words)}));vt(this,"command_foreach",this.RULED("command_foreach",()=>{this.CONSUME(hF),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));vt(this,"command_break",this.RULED("command_break",()=>{this.CONSUME(fF)}));vt(this,"command_continue",this.RULED("command_continue",()=>{this.CONSUME(dF)}));vt(this,"command_play",this.RULED("command_play",()=>{this.CONSUME(oF)}));vt(this,"expr",this.RULED("expr",()=>{this.SUBRULE1(this.and_test),this.MANY(()=>{this.CONSUME($w),this.SUBRULE2(this.and_test)})}));vt(this,"and_test",this.RULED("and_test",()=>{this.SUBRULE1(this.not_test),this.MANY(()=>{this.CONSUME(Xw),this.SUBRULE2(this.not_test)})}));vt(this,"not_test",this.RULED("not_test",()=>{this.OR([{ALT:()=>{this.CONSUME(qw),this.SUBRULE1(this.not_test)}},{ALT:()=>this.SUBRULE2(this.comparison)}])}));vt(this,"comparison",this.RULED("comparison",()=>{this.SUBRULE1(this.arith_expr),this.MANY(()=>{this.SUBRULE(this.comp_op),this.SUBRULE2(this.arith_expr)})}));vt(this,"comp_op",this.RULED("comp_op",()=>{this.OR([{ALT:()=>this.CONSUME(q4)},{ALT:()=>this.CONSUME(X4)},{ALT:()=>this.CONSUME(K4)},{ALT:()=>this.CONSUME(Y4)},{ALT:()=>this.CONSUME(Z4)},{ALT:()=>this.CONSUME(J4)}])}));vt(this,"expr_value",this.RULED("expr_value",()=>{this.SUBRULE1(this.and_test_value),this.MANY(()=>{this.CONSUME($w),this.SUBRULE2(this.and_test_value)})}));vt(this,"and_test_value",this.RULED("and_test_value",()=>{this.SUBRULE1(this.not_test_value),this.MANY(()=>{this.CONSUME(Xw),this.SUBRULE2(this.not_test_value)})}));vt(this,"not_test_value",this.RULED("not_test_value",()=>{this.OR([{ALT:()=>{this.CONSUME(qw),this.SUBRULE1(this.not_test_value)}},{ALT:()=>this.SUBRULE2(this.arith_expr)}])}));vt(this,"arith_expr",this.RULED("arith_expr",()=>{this.SUBRULE1(this.term),this.MANY(()=>this.SUBRULE2(this.arith_expr_item))}));vt(this,"arith_expr_item",this.RULED("arith_expr_item",()=>{this.OR([{ALT:()=>this.CONSUME(Kw)},{ALT:()=>this.CONSUME(Yw)}]),this.SUBRULE(this.term)}));vt(this,"term",this.RULED("term",()=>{this.SUBRULE1(this.factor),this.MANY(()=>this.SUBRULE2(this.term_item))}));vt(this,"term_item",this.RULED("term_item",()=>{this.OR([{ALT:()=>this.CONSUME(eF)},{ALT:()=>this.CONSUME(Zw)},{ALT:()=>this.CONSUME(tF)},{ALT:()=>this.CONSUME(nF)}]),this.SUBRULE(this.factor)}));vt(this,"factor",this.RULED("factor",()=>{this.OR1([{ALT:()=>{this.OR2([{ALT:()=>this.CONSUME(Kw)},{ALT:()=>this.CONSUME(Yw)}]),this.SUBRULE(this.factor)}},{ALT:()=>this.SUBRULE(this.power)}])}));vt(this,"power",this.RULED("power",()=>{this.SUBRULE(this.token),this.OPTION(()=>{this.CONSUME(Q4),this.SUBRULE(this.factor)})}));vt(this,"words",this.RULED("words",()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.expr))}));vt(this,"token",this.RULED("token",()=>{this.OR([{ALT:()=>this.CONSUME(j4)},{ALT:()=>this.CONSUME(ji)},{ALT:()=>this.CONSUME($4)},{ALT:()=>{this.CONSUME(iF),this.SUBRULE(this.expr),this.CONSUME(sF)}}])}));this.performSelfAnalysis()}PEEK(n,r,...i){console.info(n,i.map(s=>[s.image,s.tokenType]),r)}RULED(n,r,i){const s=Kde.some(o=>n.includes(o));return this.RULE(n,()=>{const a=(OI++).toString().padStart(3),c=s?"font-weight: bold;":"";if(LI&&!this.RECORDING_PHASE){const l=[this.LA(1),this.LA(2),this.LA(3)].map(u=>`[${u.tokenType.name} ${u.image.replaceAll(` -`,"\\n")}]`);console.info(`${a}%c> ${n} ${l.join(" ")}`,c)}r(),LI&&!this.RECORDING_PHASE&&console.info(`${a}%c< ${n} `,c),OI--},i)}}const yf=new Yde;if(Fre){const t=yf.getGAstProductions(),e=Rhe(t);console.info(e)}const Zde=yf.getBaseCstVisitorConstructor();var Ke=(t=>(t[t.PROGRAM=0]="PROGRAM",t[t.API=1]="API",t[t.LINE=2]="LINE",t[t.MARK=3]="MARK",t[t.GOTO=4]="GOTO",t[t.COUNT=5]="COUNT",t[t.TEXT=6]="TEXT",t[t.LABEL=7]="LABEL",t[t.HYPERLINK=8]="HYPERLINK",t[t.STAT=9]="STAT",t[t.MOVE=10]="MOVE",t[t.COMMAND=11]="COMMAND",t[t.LITERAL=12]="LITERAL",t[t.IF=13]="IF",t[t.IF_CHECK=14]="IF_CHECK",t[t.IF_BLOCK=15]="IF_BLOCK",t[t.ELSE_IF=16]="ELSE_IF",t[t.ELSE=17]="ELSE",t[t.WHILE=18]="WHILE",t[t.BREAK=19]="BREAK",t[t.CONTINUE=20]="CONTINUE",t[t.REPEAT=21]="REPEAT",t[t.WAITFOR=22]="WAITFOR",t[t.FOREACH=23]="FOREACH",t[t.OR=24]="OR",t[t.AND=25]="AND",t[t.NOT=26]="NOT",t[t.COMPARE=27]="COMPARE",t[t.COMPARE_ITEM=28]="COMPARE_ITEM",t[t.OPERATOR=29]="OPERATOR",t[t.OPERATOR_ITEM=30]="OPERATOR_ITEM",t[t.EXPR=31]="EXPR",t))(Ke||{}),Mu=(t=>(t[t.IS_EQ=0]="IS_EQ",t[t.IS_NOT_EQ=1]="IS_NOT_EQ",t[t.IS_LESS_THAN=2]="IS_LESS_THAN",t[t.IS_GREATER_THAN=3]="IS_GREATER_THAN",t[t.IS_LESS_THAN_OR_EQ=4]="IS_LESS_THAN_OR_EQ",t[t.IS_GREATER_THAN_OR_EQ=5]="IS_GREATER_THAN_OR_EQ",t))(Mu||{}),oa=(t=>(t[t.EMPTY=0]="EMPTY",t[t.PLUS=1]="PLUS",t[t.MINUS=2]="MINUS",t[t.POWER=3]="POWER",t[t.MULTIPLY=4]="MULTIPLY",t[t.DIVIDE=5]="DIVIDE",t[t.MOD_DIVIDE=6]="MOD_DIVIDE",t[t.FLOOR_DIVIDE=7]="FLOOR_DIVIDE",t[t.UNI_PLUS=8]="UNI_PLUS",t[t.UNI_MINUS=9]="UNI_MINUS",t))(oa||{}),k_=(t=>(t[t.NUMBER=0]="NUMBER",t[t.STRING=1]="STRING",t[t.TEMPLATE=2]="TEMPLATE",t))(k_||{});function Jde(t){return!!(t!=null&&t.tokenType)}function uc(t,e){const[n]=t??[];return((n==null?void 0:n.image)??e).trimStart().replaceAll(/^"|"$/g,"")}class Qde extends Zde{constructor(){super();vt(this,"unique",0);Ra&&this.validateVisitor()}getnodelocation(n){const r=Object.values(n).flat().filter(i=>!!i).map(i=>i&&Jde(i)?{startLine:i.startLine,startColumn:i.startColumn,startOffset:i.startOffset,endLine:i.endLine,endColumn:i.endColumn,endOffset:i.endOffset}:i!=null&&i.location?{...i.location}:{startLine:0,startColumn:0,startOffset:0,endLine:0,endColumn:0,endOffset:0}).filter(i=>i.startLine!==0&&i.endLine!==0);return{startLine:Math.min(...r.map(i=>i.startLine??1)),startColumn:Math.min(...r.map(i=>i.startColumn??1)),startOffset:Math.min(...r.map(i=>i.startOffset??1)),endLine:Math.max(...r.map(i=>i.endLine??1)),endColumn:Math.max(...r.map(i=>i.endColumn??1)),endOffset:Math.max(...r.map(i=>i.endOffset??1))}}createcodenode(n,r){return[{...r,...this.getnodelocation(n),lineindex:0}]}createstringnode(n,r){return this.createcodenode(n,{type:12,literal:1,value:r})}createmarknode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:3,id:r,comment:i}))}creategotonode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:4,id:r,comment:i}))}createlinenode(n,r){return this.createcodenode(n,{type:2,stmts:r})}createapinode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:1,words:i,method:r}))}createlogicnode(n,r,i,s){return this.createlinenode(n,this.createcodenode(n,{type:14,skip:i,words:s,method:r}))}createcountnode(n){return this.createcodenode(n,{type:5,index:this.unique++})}go(n){return Array.isArray(n)?n.map(r=>this.visit(r)).flat():Z(n)?[this.visit(n)].flat():[]}program(n){return this.unique=0,this.createcodenode(n,{type:0,lines:[this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:"restart"})),this.go(n.line)].flat()})}line(n){return n.stmt?this.go(n.stmt):[]}stmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.short_commands?[this.go(n.short_commands),this.go(n.commands)].flat():[]}inline(n){return this.go(n.instmt)}instmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.commands?this.go(n.commands):[]}stmt_label(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:uc(n.token_label,":").slice(1).trim()}))}stmt_stat(n){return this.createlinenode(n,this.createcodenode(n,{type:9,value:uc(n.token_stat,"@").slice(1)}))}stmt_text(n){return this.createlinenode(n,this.createcodenode(n,{type:6,value:uc(n.token_text,"")}))}stmt_comment(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!1,name:uc(n.token_comment,"'").slice(1).trim()}))}stmt_hyperlink(n){return this.createlinenode(n,this.createcodenode(n,{type:8,link:this.go(n.words),text:uc(n.token_hyperlinktext,";").slice(1)}))}stmt_command(n){return n.commands?this.go(n.commands):[]}short_commands(n){return n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):[]}commands(n){return n.words?this.createlinenode(n,this.createcodenode(n,{type:11,words:this.go(n.words)})):n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):n.command_play?this.go(n.command_play):n.structured_cmd?this.go(n.structured_cmd):[]}structured_cmd(n){return n.command_if?this.go(n.command_if):n.command_while?this.go(n.command_while):n.command_repeat?this.go(n.command_repeat):n.command_waitfor?this.go(n.command_waitfor):n.command_foreach?this.go(n.command_foreach):n.command_break?this.go(n.command_break):n.command_continue?this.go(n.command_continue):[]}short_go(n){return n.token_divide?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!0,words:this.go(n.words)})):[]}short_try(n){return n.token_query?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!1,words:this.go(n.words)})):[]}command_if(n){const[r]=this.createlogicnode(n,"if","",this.go(n.words)),[i]=this.go(n.command_if_block)??[];return this.createcodenode(n,{type:13,check:r,block:i})}command_if_block(n){const r=fr(),i=fr();return this.createcodenode(n,{type:15,skip:r,done:i,lines:[this.go(n.inline),this.go(n.line),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"alt logic")].flat(),altlines:[this.go(n.command_else_if),this.go(n.command_else),this.createmarknode(n,i,"end of if")].flat()})}command_block(n){return[this.go(n.inline),this.go(n.line)].flat()}command_fork(n){return[this.go(n.inline),this.go(n.line)].flat()}command_else_if(n){const r=fr(),i=fr();return this.createcodenode(n,{type:16,done:i,lines:[this.createlogicnode(n,"if",r,this.go(n.words)),this.go(n.command_fork),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"skip")].flat()})}command_else(n){return this.createcodenode(n,{type:17,lines:this.go(n.command_fork)})}command_while(n){const r=fr(),i=fr();return this.createcodenode(n,{type:18,loop:r,done:i,lines:[this.createmarknode(n,r,"start of while"),this.createlogicnode(n,"if",i,this.go(n.words)),this.go(n.command_block),this.creategotonode(n,r,"loop of while"),this.createmarknode(n,i,"end of while")].flat()})}command_repeat(n){const r=fr(),i=fr(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:21,loop:r,done:i,lines:[this.createapinode(n,"repeatstart",o),this.createmarknode(n,r,"start of repeat"),this.createlogicnode(n,"repeat",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of repeat"),this.createmarknode(n,i,"end of repeat")].flat()})}command_foreach(n){const r=fr(),i=fr(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:23,loop:r,done:i,lines:[this.createapinode(n,"foreachstart",o),this.createmarknode(n,r,"start of foreach"),this.createlogicnode(n,"foreach",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of foreach"),this.createmarknode(n,i,"end of foreach")].flat()})}command_waitfor(n){return this.createcodenode(n,{type:22,words:this.go(n.words)})}command_break(n){return this.createcodenode(n,{type:19,goto:0})}command_continue(n){return this.createcodenode(n,{type:20,goto:0})}command_play(n){const r=uc(n.token_command_play,""),i=r.replace("bgplay","").replace("play","").trim(),s=r.includes("bgplay");return this.createlinenode(n,this.createcodenode(n,{type:11,words:[this.createstringnode(n,s?"bgplay":"play"),this.createstringnode(n,i)].flat()}))}expr(n){return n.and_test.length===1?this.go(n.and_test):this.createcodenode(n,{type:24,items:this.go(n.and_test)})}and_test(n){return n.not_test.length===1?this.go(n.not_test):this.createcodenode(n,{type:25,items:this.go(n.not_test)})}not_test(n){return n.comparison?this.go(n.comparison):n.not_test?this.createcodenode(n,{type:26,items:this.go(n.not_test)}):[]}comparison(n){if(n.arith_expr.length===1)return this.go(n.arith_expr);const[r,i]=this.go(n.arith_expr),[s]=this.go(n.comp_op);return this.createcodenode(n,{type:27,lhs:r,compare:s,rhs:i})}comp_op(n){return n.token_iseq?this.createcodenode(n,{type:28,method:0}):n.token_isnoteq?this.createcodenode(n,{type:28,method:1}):n.token_islessthan?this.createcodenode(n,{type:28,method:2}):n.token_isgreaterthan?this.createcodenode(n,{type:28,method:3}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:4}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:5}):[]}expr_value(n){return n.and_test_value.length===1?this.go(n.and_test_value):this.createcodenode(n,{type:24,items:this.go(n.and_test_value)})}and_test_value(n){return n.not_test_value.length===1?this.go(n.not_test_value):this.createcodenode(n,{type:25,items:this.go(n.not_test_value)})}not_test_value(n){return n.arith_expr?this.go(n.arith_expr):n.not_test_value?this.createcodenode(n,{type:26,items:this.go(n.not_test_value)}):[]}arith_expr(n){const r=this.go(n.term);return n.arith_expr_item?this.createcodenode(n,{type:29,lhs:r[0],items:this.go(n.arith_expr_item)}):r}arith_expr_item(n){return this.createcodenode(n,{type:30,operator:n.token_plus?1:2,rhs:this.go(n.term)[0]})}term(n){return n.term_item?this.createcodenode(n,{type:29,lhs:this.go(n.factor)[0],items:this.go(n.term_item)}):this.go(n.factor)}term_item(n){let r=0;return n.token_multiply&&(r=4),n.token_divide&&(r=5),n.token_moddivide&&(r=6),n.token_floordivide&&(r=7),this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})}factor(n){if(n.power)return this.go(n.power);let r=0;return n.token_plus&&(r=8),n.token_minus&&(r=9),this.createcodenode(n,{type:29,lhs:void 0,items:this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})})}power(n){const r=this.go(n.token);return n.factor?this.createcodenode(n,{type:29,lhs:r[0],items:this.createcodenode(n,{type:30,operator:3,rhs:this.go(n.factor)[0]})}):r}words(n){return this.go(n.expr)}token(n){if(n.token_stringliteraldouble){const r=uc(n.token_stringliteraldouble,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:2,value:r})}if(n.token_stringliteral){const r=uc(n.token_stringliteral,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:1,value:r})}if(n.token_numberliteral){const r=parseFloat(uc(n.token_numberliteral,"0"));return this.createcodenode(n,{type:12,literal:0,value:r})}return n.token_lparen?this.createcodenode(n,{type:31,words:this.go(n.expr)}):[]}}const epe=new Qde,rs={labels:{},internal:0,lineindex:0,linelookup:{},isfirststat:!1},Zy="zss.js";function sn(t,e){return new Xde(t.startLine??1,t.startColumn??1,Zy,e)}function sb(t){return t.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function US(t){return`'${sb(t)}'`}function I_(t){if(t.startsWith('"'))return I_(t.replaceAll(/(^"|"$)/g,""));const e=Qy(t);return e.errors.length?t:`['${e.tokens.map(r=>r.tokenType===rM?`', api.get('${sb(r.image.substring(1))}'), '`:sb(r.image)).join("")}'].join('')`}function xu(t){return t.filter(e=>e!==void 0).map(xn)}function PI(t){return sn(t,"")}function tpe(t,e){const n=[];return t.forEach(r=>{n.push(r,e)}),n.pop(),n}function Cr(t,e,n){return sn(t,[`api.${e}(`,...tpe(n,", "),")"])}function npe(t){if(t.type===Ke.COMPARE&&t.compare.type===Ke.COMPARE_ITEM)switch(t.compare.method){case Mu.IS_EQ:return Cr(t,"isEq",[xn(t.lhs),xn(t.rhs)]);case Mu.IS_NOT_EQ:return Cr(t,"isNotEq",[xn(t.lhs),xn(t.rhs)]);case Mu.IS_LESS_THAN:return Cr(t,"isLessThan",[xn(t.lhs),xn(t.rhs)]);case Mu.IS_GREATER_THAN:return Cr(t,"isGreaterThan",[xn(t.lhs),xn(t.rhs)]);case Mu.IS_LESS_THAN_OR_EQ:return Cr(t,"isLessThanOrEq",[xn(t.lhs),xn(t.rhs)]);case Mu.IS_GREATER_THAN_OR_EQ:return Cr(t,"isGreaterThanOrEq",[xn(t.lhs),xn(t.rhs)])}return sn(t,"")}function Su(t,e,n){return t.prepend(`api.${e}(`),t.add([", ",xn(n),")"])}function DI(t,e,n){return t.prepend(`api.${e}(`),t.add([xn(n),")"])}function rpe(t,e){if(t.type===Ke.OPERATOR_ITEM)switch(t.operator){case oa.PLUS:return Su(e,"opPlus",t.rhs);case oa.MINUS:return Su(e,"opMinus",t.rhs);case oa.POWER:return Su(e,"opPower",t.rhs);case oa.MULTIPLY:return Su(e,"opMultiply",t.rhs);case oa.DIVIDE:return Su(e,"opDivide",t.rhs);case oa.MOD_DIVIDE:return Su(e,"opModDivide",t.rhs);case oa.FLOOR_DIVIDE:return Su(e,"opFloorDivide",t.rhs);case oa.UNI_PLUS:return DI(e,"opUniPlus",t.rhs);case oa.UNI_MINUS:return DI(e,"opUniMinus",t.rhs)}return sn(t,"")}function ipe(t){if(t.type===Ke.OPERATOR){const e=t.lhs?xn(t.lhs):sn(t,"");return t.items.forEach(n=>rpe(n,e)),e}return sn(t,"")}function q0(t,e){return sn(t,[Cr(t,"jump",[`${e}`]),"; continue;"])}function hc(t){return rs.linelookup[t??""]??-1}function ob(t,e){rs.linelookup[t]=e}function hp(t,e,n){for(let r=0;rr.add(xn(i))),BF(n.altlines,Ke.ELSE_IF,hc(n.done)),n.altlines.forEach(i=>r.add(xn(i))),r}return sn(t,xn(t.check))}case Ke.IF_CHECK:{const n=hc(t.skip);return n===-1?sn(t,[" ",Cr(t,t.method,xu(t.words)),`; -`]):sn(t,[" if (!",Cr(t,t.method,xu(t.words)),") { ",q0(t,n),` } -`])}case Ke.ELSE_IF:case Ke.ELSE:{const n=sn(t,"");return t.lines.forEach(r=>n.add(xn(r))),n}case Ke.WHILE:{const n=hc(t.loop),r=hc(t.done),i=sn(t,"");return hp(t.lines,Ke.IF_CHECK,t.done),t.lines.forEach(s=>{switch(s.type){case Ke.BREAK:s.goto=r;break;case Ke.CONTINUE:s.goto=n;break}i.add(xn(s))}),i}case Ke.REPEAT:{const n=hc(t.loop),r=hc(t.done),i=sn(t,"");return hp(t.lines,Ke.IF_CHECK,t.done),t.lines.forEach(s=>{switch(s.type){case Ke.BREAK:s.goto=r;break;case Ke.CONTINUE:s.goto=n;break}i.add(xn(s))}),i}case Ke.WAITFOR:{const n=sn(t,"");return n.add([" if (!",Cr(t,"if",xu(t.words)),`) { api.i(${t.lineindex-1}); } -`]),n}case Ke.FOREACH:{const n=hc(t.loop),r=hc(t.done),i=sn(t,"");return hp(t.lines,Ke.IF_CHECK,t.done),t.lines.forEach(s=>{switch(s.type){case Ke.BREAK:s.goto=r;break;case Ke.CONTINUE:s.goto=n;break}i.add(xn(s))}),i}case Ke.BREAK:return sn(t,[" ",q0(t,t.goto),` -`]);case Ke.CONTINUE:return sn(t,[" ",q0(t,t.goto),` -`]);case Ke.OR:return Cr(t,"or",t.items.map(xn));case Ke.AND:return Cr(t,"and",t.items.map(xn));case Ke.NOT:return Cr(t,"not",t.items.map(xn));case Ke.COMPARE:return npe(t);case Ke.OPERATOR:return ipe(t);case Ke.EXPR:return Cr(t,"expr",t.words.map(xn));default:return console.error("",t.type,t),PI(t)}}function aa(t){if(Z(t))switch(t.type===Ke.LINE&&++rs.lineindex,t.lineindex=rs.lineindex,t.type){case Ke.PROGRAM:t.lines.forEach(aa);break;case Ke.LINE:t.stmts.forEach(aa);break;case Ke.MARK:ob(t.id,t.lineindex);break;case Ke.IF:aa(t.check),aa(t.block);break;case Ke.IF_BLOCK:t.lines.forEach(aa),t.altlines.forEach(aa);break;case Ke.ELSE_IF:t.lines.forEach(aa);break;case Ke.ELSE:case Ke.WHILE:case Ke.REPEAT:case Ke.FOREACH:t.lines.forEach(aa);break;case Ke.MOVE:case Ke.COMMAND:case Ke.WAITFOR:case Ke.IF_CHECK:t.words.forEach(aa);break}}function spe(t){return rs.labels={},rs.internal=1,rs.lineindex=0,rs.isfirststat=!0,aa(t),{...xn(t).toStringWithSourceMap({file:`${Zy}.map`}),...rs}}const ope={HALT_AT_COUNT:256};function ape(t){return cn(t)?t.length>0?1:0:t??0}function ni(t){return`${t??""}`}function cpe(t){return`${t}_chip`}function lpe(t,e,n){var c,l;const r=cpe(t),i=Xp(r);let s;cn(i.lb)||(i.lb=Ob(Object.entries(n.labels??{})),i.lk="",i.mg=void 0,i.ec=1,i.lc=0,i.ys=0,i.ps=0,i.es=(((c=n.errors)==null?void 0:c.length)??0)!==0?1:0);function o(u,h){se.words=h;const p=Sde(e,u);return Z(p)?p(a,h):u!=="send"?o("send",[u,...h]):0}const a={halt(){_pe(r)},id(){return t},senderid(u=t){return`vm:${u??t}`},set(u,h){const[p,m]=wde(e,a,u,h);if(p)return m},get(u){const[h,p]=Ede(e,a,u);if(h)return p},bucket(u){const h=a.get("bucket");cn(h)?h.push(u):a.set("bucket",[u])},tick(u){const h=mt(i.ps)?i.ps:0,p=h%u===0;if(i.ps=h+1,p===!1)return!1;if(a.shouldtick()===!1)return NI(e,a),!1;i.lc=0,i.ys=0,se.get=a.get,bde(e,a);try{const m=s==null?void 0:s.next();m!=null&&m.done&&(Vn("chip","crash","generator logic unexpectedly exited"),i.es=1)}catch(m){Vn("chip","crash",m.message),i.es=1}return NI(e,a),!0},isended(){return i.es===1},shouldtick(){return i.es===0||a.hm()!==0},shouldhalt(){return mt(i.lc)?++i.lc>ope.HALT_AT_COUNT:!0},hm(){if(cn(i.mg)&&cn(i.lb)){const[,u]=i.mg;if(Z(u))for(let h=0;hmt(g)&&g>0)??0}}return 0},yield(){i.ys=1},jump(u){i.ec=u},sy(){return!!i.ys||a.shouldhalt()},emit(u,h,p){Yt.emit(u,a.senderid(),h,p)},send(u,h,p,m){Yt.emit(`${a.senderid(u)}:${h}`,t,p,m)},lock(u){i.lk=u},unlock(){i.lk=""},message(u){i.lk&&u.sender!==i.lk||(i.mg=[u.id,u.target,u.data,u.sender,u.player])},zap(u){if(cn(i.lb))for(let h=0;hv>0);g>=0&&(m[g]*=-1)}}},restore(u){if(cn(i.lb))for(let h=0;hm.fileName===Zy);return{line:(p==null?void 0:p.lineNumber)??0,column:(p==null?void 0:p.columnNumber)??0}},text(u){return o("text",[u])},stat(...u){return o("stat",u)},hyperlink(...u){return o("hyperlink",u)},command(...u){if(u.length===0)return 0;const[h,...p]=u;return o(ni(h),p)},if(...u){const[h,p]=Ve(u,0,[Ie.ANY]),m=ape(h);return m&&p0,v=i[p];return g&&cn(v)&&a.command(...v),g?1:0},foreachstart(u,...h){const[p,m,g,v]=Ve(h,0,[Ie.STRING,Ie.NUMBER,Ie.NUMBER,Ie.MAYBE_NUMBER]);let y=Math.min(m,g),_=Math.max(m,g);const S=(v??0)||1;if(S<0){const E=y;y=_,_=E}return a.set(p,y-S),0},foreach(u,...h){const[p,m,g,v,y]=Ve(h,0,[Ie.STRING,Ie.NUMBER,Ie.NUMBER,Ie.MAYBE_NUMBER]);let _=Math.min(m,g),S=Math.max(m,g);const E=(v??0)||1;if(E<0){const R=_;_=S,S=R}let b=a.get(p);!mt(b)||b<_||b>S?b=_:b+=E;const N=b<=S?1:0;return N&&(a.set(p,b),ym?1:0},isLessThanOrEq(u,h){const[p]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return p<=m?1:0},isGreaterThanOrEq(u,h){const[p]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return p>=m?1:0},opPlus(u,h){const[p]=Ve([u],0,[Ie.ANY]),[m]=Ve([h],0,[Ie.ANY]);return p+m},opMinus(u,h){const[p]=Ve([u],0,[Ie.ANY]),[m]=Ve([h],0,[Ie.ANY]);return p-m},opPower(u,h){const[p]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return Math.pow(p,m)},opMultiply(u,h){const[p]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return p*m},opDivide(u,h){const[p]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return p/m},opModDivide(u,h){const[p]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return p%m},opFloorDivide(u,h){const[p]=Ve([u],0,[Ie.NUMBER]),[m]=Ve([h],0,[Ie.NUMBER]);return Math.floor(p/m)},opUniPlus(u){const[h]=Ve([u],0,[Ie.NUMBER]);return+h},opUniMinus(u){const[h]=Ve([u],0,[Ie.NUMBER]);return-h}};return s=(l=n.code)==null?void 0:l.call(n,a),a}function X0(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var upe={exports:{}};/*! - -JSZip v3.10.1 - A JavaScript class for generating and reading zip files - - -(c) 2009-2016 Stuart Knightley -Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. - -JSZip uses the library pako released under the MIT license : -https://github.com/nodeca/pako/blob/main/LICENSE -*/(function(t,e){(function(n){t.exports=n()})(function(){return function n(r,i,s){function o(l,u){if(!i[l]){if(!r[l]){var h=typeof X0=="function"&&X0;if(!u&&h)return h(l,!0);if(a)return a(l,!0);var p=new Error("Cannot find module '"+l+"'");throw p.code="MODULE_NOT_FOUND",p}var m=i[l]={exports:{}};r[l][0].call(m.exports,function(g){var v=r[l][1][g];return o(v||g)},m,m.exports,n,r,i,s)}return i[l].exports}for(var a=typeof X0=="function"&&X0,c=0;c>2,m=(3&l)<<4|u>>4,g=1>6:64,v=2>4,u=(15&p)<<4|(m=a.indexOf(c.charAt(v++)))>>2,h=(3&m)<<6|(g=a.indexOf(c.charAt(v++))),S[y++]=l,m!==64&&(S[y++]=u),g!==64&&(S[y++]=h);return S}},{"./support":30,"./utils":32}],2:[function(n,r,i){var s=n("./external"),o=n("./stream/DataWorker"),a=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function l(u,h,p,m,g){this.compressedSize=u,this.uncompressedSize=h,this.crc32=p,this.compression=m,this.compressedContent=g}l.prototype={getContentWorker:function(){var u=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},l.createWorkerFrom=function(u,h,p){return u.pipe(new a).pipe(new c("uncompressedSize")).pipe(h.compressWorker(p)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=l},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,i){var s=n("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,i){var s=n("./utils"),o=function(){for(var a,c=[],l=0;l<256;l++){a=l;for(var u=0;u<8;u++)a=1&a?3988292384^a>>>1:a>>>1;c[l]=a}return c}();r.exports=function(a,c){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(l,u,h,p){var m=o,g=p+h;l^=-1;for(var v=p;v>>8^m[255&(l^u[v])];return-1^l}(0|c,a,a.length,0):function(l,u,h,p){var m=o,g=p+h;l^=-1;for(var v=p;v>>8^m[255&(l^u.charCodeAt(v))];return-1^l}(0|c,a,a.length,0):0}},{"./utils":32}],5:[function(n,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(n,r,i){var s=null;s=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:s}},{lie:37}],7:[function(n,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=n("pako"),a=n("./utils"),c=n("./stream/GenericWorker"),l=s?"uint8array":"array";function u(h,p){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=p,this.meta={}}i.magic="\b\0",a.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(l,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(p){h.push({data:p,meta:h.meta})}},i.compressWorker=function(h){return new u("Deflate",h)},i.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,i){function s(m,g){var v,y="";for(v=0;v>>=8;return y}function o(m,g,v,y,_,S){var E,b,N=m.file,R=m.compression,M=S!==l.utf8encode,O=a.transformTo("string",S(N.name)),C=a.transformTo("string",l.utf8encode(N.name)),I=N.comment,U=a.transformTo("string",S(I)),L=a.transformTo("string",l.utf8encode(I)),P=C.length!==N.name.length,T=L.length!==I.length,H="",V="",B="",z=N.dir,W=N.date,K={crc32:0,compressedSize:0,uncompressedSize:0};g&&!v||(K.crc32=m.crc32,K.compressedSize=m.compressedSize,K.uncompressedSize=m.uncompressedSize);var j=0;g&&(j|=8),M||!P&&!T||(j|=2048);var Y=0,ge=0;z&&(Y|=16),_==="UNIX"?(ge=798,Y|=function(re,we){var Ae=re;return re||(Ae=we?16893:33204),(65535&Ae)<<16}(N.unixPermissions,z)):(ge=20,Y|=function(re){return 63&(re||0)}(N.dosPermissions)),E=W.getUTCHours(),E<<=6,E|=W.getUTCMinutes(),E<<=5,E|=W.getUTCSeconds()/2,b=W.getUTCFullYear()-1980,b<<=4,b|=W.getUTCMonth()+1,b<<=5,b|=W.getUTCDate(),P&&(V=s(1,1)+s(u(O),4)+C,H+="up"+s(V.length,2)+V),T&&(B=s(1,1)+s(u(U),4)+L,H+="uc"+s(B.length,2)+B);var Q="";return Q+=` -\0`,Q+=s(j,2),Q+=R.magic,Q+=s(E,2),Q+=s(b,2),Q+=s(K.crc32,4),Q+=s(K.compressedSize,4),Q+=s(K.uncompressedSize,4),Q+=s(O.length,2),Q+=s(H.length,2),{fileRecord:h.LOCAL_FILE_HEADER+Q+O+H,dirRecord:h.CENTRAL_FILE_HEADER+s(ge,2)+Q+s(U.length,2)+"\0\0\0\0"+s(Y,4)+s(y,4)+O+H+U}}var a=n("../utils"),c=n("../stream/GenericWorker"),l=n("../utf8"),u=n("../crc32"),h=n("../signature");function p(m,g,v,y){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=v,this.encodeFileName=y,this.streamFiles=m,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(p,c),p.prototype.push=function(m){var g=m.meta.percent||0,v=this.entriesCount,y=this._sources.length;this.accumulate?this.contentBuffer.push(m):(this.bytesWritten+=m.data.length,c.prototype.push.call(this,{data:m.data,meta:{currentFile:this.currentFile,percent:v?(g+100*(v-y-1))/v:100}}))},p.prototype.openedSource=function(m){this.currentSourceOffset=this.bytesWritten,this.currentFile=m.file.name;var g=this.streamFiles&&!m.file.dir;if(g){var v=o(m,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:v.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(m){this.accumulate=!1;var g=this.streamFiles&&!m.file.dir,v=o(m,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(v.dirRecord),g)this.push({data:function(y){return h.DATA_DESCRIPTOR+s(y.crc32,4)+s(y.compressedSize,4)+s(y.uncompressedSize,4)}(m),meta:{percent:100}});else for(this.push({data:v.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var m=this.bytesWritten,g=0;g=this.index;c--)l=(l<<8)+this.byteAt(c);return this.index+=a,l},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},r.exports=o},{"../utils":32}],19:[function(n,r,i){var s=n("./Uint8ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,i){var s=n("./DataReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(n,r,i){var s=n("./ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,i){var s=n("../utils"),o=n("../support"),a=n("./ArrayReader"),c=n("./StringReader"),l=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var p=s.getTypeOf(h);return s.checkSupport(p),p!=="string"||o.uint8array?p==="nodebuffer"?new l(h):o.uint8array?new u(s.transformTo("uint8array",h)):new a(s.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,i){var s=n("./GenericWorker"),o=n("../utils");function a(c){s.call(this,"ConvertWorker to "+c),this.destType=c}o.inherits(a,s),a.prototype.processChunk=function(c){this.push({data:o.transformTo(this.destType,c.data),meta:c.meta})},r.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,i){var s=n("./GenericWorker"),o=n("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(a,s),a.prototype.processChunk=function(c){this.streamInfo.crc32=o(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(c){o.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}s.inherits(a,o),a.prototype.processChunk=function(c){if(c){var l=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=l+c.data.length}o.prototype.processChunk.call(this,c)},r.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(c){o.call(this,"DataWorker");var l=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){l.dataIsReady=!0,l.data=u,l.max=u&&u.length||0,l.type=s.getTypeOf(u),l.isPaused||l._tickAndRepeat()},function(u){l.error(u)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,l=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,l);break;case"uint8array":c=this.data.subarray(this.index,l);break;case"array":case"nodebuffer":c=this.data.slice(this.index,l)}return this.index=l,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var c=0;c "+o:o}},r.exports=s},{}],29:[function(n,r,i){var s=n("../utils"),o=n("./ConvertWorker"),a=n("./GenericWorker"),c=n("../base64"),l=n("../support"),u=n("../external"),h=null;if(l.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(g,v){return new u.Promise(function(y,_){var S=[],E=g._internalType,b=g._outputType,N=g._mimeType;g.on("data",function(R,M){S.push(R),v&&v(M)}).on("error",function(R){S=[],_(R)}).on("end",function(){try{var R=function(M,O,C){switch(M){case"blob":return s.newBlob(s.transformTo("arraybuffer",O),C);case"base64":return c.encode(O);default:return s.transformTo(M,O)}}(b,function(M,O){var C,I=0,U=null,L=0;for(C=0;C"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!n("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,i){for(var s=n("./utils"),o=n("./support"),a=n("./nodejsUtils"),c=n("./stream/GenericWorker"),l=new Array(256),u=0;u<256;u++)l[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;l[254]=l[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function p(){c.call(this,"utf-8 encode")}i.utf8encode=function(m){return o.nodebuffer?a.newBufferFrom(m,"utf-8"):function(g){var v,y,_,S,E,b=g.length,N=0;for(S=0;S>>6:(y<65536?v[E++]=224|y>>>12:(v[E++]=240|y>>>18,v[E++]=128|y>>>12&63),v[E++]=128|y>>>6&63),v[E++]=128|63&y);return v}(m)},i.utf8decode=function(m){return o.nodebuffer?s.transformTo("nodebuffer",m).toString("utf-8"):function(g){var v,y,_,S,E=g.length,b=new Array(2*E);for(v=y=0;v>10&1023,b[y++]=56320|1023&_)}return b.length!==y&&(b.subarray?b=b.subarray(0,y):b.length=y),s.applyFromCharCode(b)}(m=s.transformTo(o.uint8array?"uint8array":"array",m))},s.inherits(h,c),h.prototype.processChunk=function(m){var g=s.transformTo(o.uint8array?"uint8array":"array",m.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var v=g;(g=new Uint8Array(v.length+this.leftOver.length)).set(this.leftOver,0),g.set(v,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var y=function(S,E){var b;for((E=E||S.length)>S.length&&(E=S.length),b=E-1;0<=b&&(192&S[b])==128;)b--;return b<0||b===0?E:b+l[S[b]]>E?b:E}(g),_=g;y!==g.length&&(o.uint8array?(_=g.subarray(0,y),this.leftOver=g.subarray(y,g.length)):(_=g.slice(0,y),this.leftOver=g.slice(y,g.length))),this.push({data:i.utf8decode(_),meta:m.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=h,s.inherits(p,c),p.prototype.processChunk=function(m){this.push({data:i.utf8encode(m.data),meta:m.meta})},i.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,i){var s=n("./support"),o=n("./base64"),a=n("./nodejsUtils"),c=n("./external");function l(v){return v}function u(v,y){for(var _=0;_>8;this.dir=!!(16&this.externalFileAttributes),m==0&&(this.dosPermissions=63&this.externalFileAttributes),m==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var m=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=m.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=m.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=m.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=m.readInt(4))}},readExtraFields:function(m){var g,v,y,_=m.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});m.index+4<_;)g=m.readInt(2),v=m.readInt(2),y=m.readData(v),this.extraFields[g]={id:g,length:v,value:y};m.setIndex(_)},handleUTF8:function(){var m=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=l.utf8decode(this.fileName),this.fileCommentStr=l.utf8decode(this.fileComment);else{var g=this.findExtraFieldUnicodePath();if(g!==null)this.fileNameStr=g;else{var v=o.transformTo(m,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(v)}var y=this.findExtraFieldUnicodeComment();if(y!==null)this.fileCommentStr=y;else{var _=o.transformTo(m,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(_)}}},findExtraFieldUnicodePath:function(){var m=this.extraFields[28789];if(m){var g=s(m.value);return g.readInt(1)!==1||c(this.fileName)!==g.readInt(4)?null:l.utf8decode(g.readData(m.length-5))}return null},findExtraFieldUnicodeComment:function(){var m=this.extraFields[25461];if(m){var g=s(m.value);return g.readInt(1)!==1||c(this.fileComment)!==g.readInt(4)?null:l.utf8decode(g.readData(m.length-5))}return null}},r.exports=p},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,r,i){function s(g,v,y){this.name=g,this.dir=y.dir,this.date=y.date,this.comment=y.comment,this.unixPermissions=y.unixPermissions,this.dosPermissions=y.dosPermissions,this._data=v,this._dataBinary=y.binary,this.options={compression:y.compression,compressionOptions:y.compressionOptions}}var o=n("./stream/StreamHelper"),a=n("./stream/DataWorker"),c=n("./utf8"),l=n("./compressedObject"),u=n("./stream/GenericWorker");s.prototype={internalStream:function(g){var v=null,y="string";try{if(!g)throw new Error("No output type specified.");var _=(y=g.toLowerCase())==="string"||y==="text";y!=="binarystring"&&y!=="text"||(y="string"),v=this._decompressWorker();var S=!this._dataBinary;S&&!_&&(v=v.pipe(new c.Utf8EncodeWorker)),!S&&_&&(v=v.pipe(new c.Utf8DecodeWorker))}catch(E){(v=new u("error")).error(E)}return new o(v,y,"")},async:function(g,v){return this.internalStream(g).accumulate(v)},nodeStream:function(g,v){return this.internalStream(g||"nodebuffer").toNodejsStream(v)},_compressWorker:function(g,v){if(this._data instanceof l&&this._data.compression.magic===g.magic)return this._data.getCompressedWorker();var y=this._decompressWorker();return this._dataBinary||(y=y.pipe(new c.Utf8EncodeWorker)),l.createWorkerFrom(y,g,v)},_decompressWorker:function(){return this._data instanceof l?this._data.getContentWorker():this._data instanceof u?this._data:new a(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],p=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},m=0;m>>6:(m<65536?p[y++]=224|m>>>12:(p[y++]=240|m>>>18,p[y++]=128|m>>>12&63),p[y++]=128|m>>>6&63),p[y++]=128|63&m);return p},i.buf2binstring=function(h){return u(h,h.length)},i.binstring2buf=function(h){for(var p=new s.Buf8(h.length),m=0,g=p.length;m>10&1023,S[g++]=56320|1023&v)}return u(S,g)},i.utf8border=function(h,p){var m;for((p=p||h.length)>h.length&&(p=h.length),m=p-1;0<=m&&(192&h[m])==128;)m--;return m<0||m===0?p:m+c[h[m]]>p?m:p}},{"./common":41}],43:[function(n,r,i){r.exports=function(s,o,a,c){for(var l=65535&s|0,u=s>>>16&65535|0,h=0;a!==0;){for(a-=h=2e3>>1:o>>>1;a[c]=o}return a}();r.exports=function(o,a,c,l){var u=s,h=l+c;o^=-1;for(var p=l;p>>8^u[255&(o^a[p])];return-1^o}},{}],46:[function(n,r,i){var s,o=n("../utils/common"),a=n("./trees"),c=n("./adler32"),l=n("./crc32"),u=n("./messages"),h=0,p=4,m=0,g=-2,v=-1,y=4,_=2,S=8,E=9,b=286,N=30,R=19,M=2*b+1,O=15,C=3,I=258,U=I+C+1,L=42,P=113,T=1,H=2,V=3,B=4;function z(A,ie){return A.msg=u[ie],ie}function W(A){return(A<<1)-(4A.avail_out&&(te=A.avail_out),te!==0&&(o.arraySet(A.output,ie.pending_buf,ie.pending_out,te,A.next_out),A.next_out+=te,ie.pending_out+=te,A.total_out+=te,A.avail_out-=te,ie.pending-=te,ie.pending===0&&(ie.pending_out=0))}function Y(A,ie){a._tr_flush_block(A,0<=A.block_start?A.block_start:-1,A.strstart-A.block_start,ie),A.block_start=A.strstart,j(A.strm)}function ge(A,ie){A.pending_buf[A.pending++]=ie}function Q(A,ie){A.pending_buf[A.pending++]=ie>>>8&255,A.pending_buf[A.pending++]=255&ie}function re(A,ie){var te,X,$=A.max_chain_length,ne=A.strstart,ae=A.prev_length,G=A.nice_match,D=A.strstart>A.w_size-U?A.strstart-(A.w_size-U):0,ee=A.window,he=A.w_mask,ce=A.prev,_e=A.strstart+I,ze=ee[ne+ae-1],Oe=ee[ne+ae];A.prev_length>=A.good_match&&($>>=2),G>A.lookahead&&(G=A.lookahead);do if(ee[(te=ie)+ae]===Oe&&ee[te+ae-1]===ze&&ee[te]===ee[ne]&&ee[++te]===ee[ne+1]){ne+=2,te++;do;while(ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ee[++ne]===ee[++te]&&ne<_e);if(X=I-(_e-ne),ne=_e-I,aeD&&--$!=0);return ae<=A.lookahead?ae:A.lookahead}function we(A){var ie,te,X,$,ne,ae,G,D,ee,he,ce=A.w_size;do{if($=A.window_size-A.lookahead-A.strstart,A.strstart>=ce+(ce-U)){for(o.arraySet(A.window,A.window,ce,ce,0),A.match_start-=ce,A.strstart-=ce,A.block_start-=ce,ie=te=A.hash_size;X=A.head[--ie],A.head[ie]=ce<=X?X-ce:0,--te;);for(ie=te=ce;X=A.prev[--ie],A.prev[ie]=ce<=X?X-ce:0,--te;);$+=ce}if(A.strm.avail_in===0)break;if(ae=A.strm,G=A.window,D=A.strstart+A.lookahead,ee=$,he=void 0,he=ae.avail_in,ee=C)for(ne=A.strstart-A.insert,A.ins_h=A.window[ne],A.ins_h=(A.ins_h<=C&&(A.ins_h=(A.ins_h<=C)if(X=a._tr_tally(A,A.strstart-A.match_start,A.match_length-C),A.lookahead-=A.match_length,A.match_length<=A.max_lazy_match&&A.lookahead>=C){for(A.match_length--;A.strstart++,A.ins_h=(A.ins_h<=C&&(A.ins_h=(A.ins_h<=C&&A.match_length<=A.prev_length){for($=A.strstart+A.lookahead-C,X=a._tr_tally(A,A.strstart-1-A.prev_match,A.prev_length-C),A.lookahead-=A.prev_length-1,A.prev_length-=2;++A.strstart<=$&&(A.ins_h=(A.ins_h<A.pending_buf_size-5&&(te=A.pending_buf_size-5);;){if(A.lookahead<=1){if(we(A),A.lookahead===0&&ie===h)return T;if(A.lookahead===0)break}A.strstart+=A.lookahead,A.lookahead=0;var X=A.block_start+te;if((A.strstart===0||A.strstart>=X)&&(A.lookahead=A.strstart-X,A.strstart=X,Y(A,!1),A.strm.avail_out===0)||A.strstart-A.block_start>=A.w_size-U&&(Y(A,!1),A.strm.avail_out===0))return T}return A.insert=0,ie===p?(Y(A,!0),A.strm.avail_out===0?V:B):(A.strstart>A.block_start&&(Y(A,!1),A.strm.avail_out),T)}),new Le(4,4,8,4,Ae),new Le(4,5,16,8,Ae),new Le(4,6,32,32,Ae),new Le(4,4,16,16,Ee),new Le(8,16,32,32,Ee),new Le(8,16,128,128,Ee),new Le(8,32,128,256,Ee),new Le(32,128,258,1024,Ee),new Le(32,258,258,4096,Ee)],i.deflateInit=function(A,ie){return De(A,ie,S,15,8,0)},i.deflateInit2=De,i.deflateReset=it,i.deflateResetKeep=qe,i.deflateSetHeader=function(A,ie){return A&&A.state?A.state.wrap!==2?g:(A.state.gzhead=ie,m):g},i.deflate=function(A,ie){var te,X,$,ne;if(!A||!A.state||5>8&255),ge(X,X.gzhead.time>>16&255),ge(X,X.gzhead.time>>24&255),ge(X,X.level===9?2:2<=X.strategy||X.level<2?4:0),ge(X,255&X.gzhead.os),X.gzhead.extra&&X.gzhead.extra.length&&(ge(X,255&X.gzhead.extra.length),ge(X,X.gzhead.extra.length>>8&255)),X.gzhead.hcrc&&(A.adler=l(A.adler,X.pending_buf,X.pending,0)),X.gzindex=0,X.status=69):(ge(X,0),ge(X,0),ge(X,0),ge(X,0),ge(X,0),ge(X,X.level===9?2:2<=X.strategy||X.level<2?4:0),ge(X,3),X.status=P);else{var ae=S+(X.w_bits-8<<4)<<8;ae|=(2<=X.strategy||X.level<2?0:X.level<6?1:X.level===6?2:3)<<6,X.strstart!==0&&(ae|=32),ae+=31-ae%31,X.status=P,Q(X,ae),X.strstart!==0&&(Q(X,A.adler>>>16),Q(X,65535&A.adler)),A.adler=1}if(X.status===69)if(X.gzhead.extra){for($=X.pending;X.gzindex<(65535&X.gzhead.extra.length)&&(X.pending!==X.pending_buf_size||(X.gzhead.hcrc&&X.pending>$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),j(A),$=X.pending,X.pending!==X.pending_buf_size));)ge(X,255&X.gzhead.extra[X.gzindex]),X.gzindex++;X.gzhead.hcrc&&X.pending>$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),X.gzindex===X.gzhead.extra.length&&(X.gzindex=0,X.status=73)}else X.status=73;if(X.status===73)if(X.gzhead.name){$=X.pending;do{if(X.pending===X.pending_buf_size&&(X.gzhead.hcrc&&X.pending>$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),j(A),$=X.pending,X.pending===X.pending_buf_size)){ne=1;break}ne=X.gzindex$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),ne===0&&(X.gzindex=0,X.status=91)}else X.status=91;if(X.status===91)if(X.gzhead.comment){$=X.pending;do{if(X.pending===X.pending_buf_size&&(X.gzhead.hcrc&&X.pending>$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),j(A),$=X.pending,X.pending===X.pending_buf_size)){ne=1;break}ne=X.gzindex$&&(A.adler=l(A.adler,X.pending_buf,X.pending-$,$)),ne===0&&(X.status=103)}else X.status=103;if(X.status===103&&(X.gzhead.hcrc?(X.pending+2>X.pending_buf_size&&j(A),X.pending+2<=X.pending_buf_size&&(ge(X,255&A.adler),ge(X,A.adler>>8&255),A.adler=0,X.status=P)):X.status=P),X.pending!==0){if(j(A),A.avail_out===0)return X.last_flush=-1,m}else if(A.avail_in===0&&W(ie)<=W(te)&&ie!==p)return z(A,-5);if(X.status===666&&A.avail_in!==0)return z(A,-5);if(A.avail_in!==0||X.lookahead!==0||ie!==h&&X.status!==666){var G=X.strategy===2?function(D,ee){for(var he;;){if(D.lookahead===0&&(we(D),D.lookahead===0)){if(ee===h)return T;break}if(D.match_length=0,he=a._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++,he&&(Y(D,!1),D.strm.avail_out===0))return T}return D.insert=0,ee===p?(Y(D,!0),D.strm.avail_out===0?V:B):D.last_lit&&(Y(D,!1),D.strm.avail_out===0)?T:H}(X,ie):X.strategy===3?function(D,ee){for(var he,ce,_e,ze,Oe=D.window;;){if(D.lookahead<=I){if(we(D),D.lookahead<=I&&ee===h)return T;if(D.lookahead===0)break}if(D.match_length=0,D.lookahead>=C&&0D.lookahead&&(D.match_length=D.lookahead)}if(D.match_length>=C?(he=a._tr_tally(D,1,D.match_length-C),D.lookahead-=D.match_length,D.strstart+=D.match_length,D.match_length=0):(he=a._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++),he&&(Y(D,!1),D.strm.avail_out===0))return T}return D.insert=0,ee===p?(Y(D,!0),D.strm.avail_out===0?V:B):D.last_lit&&(Y(D,!1),D.strm.avail_out===0)?T:H}(X,ie):s[X.level].func(X,ie);if(G!==V&&G!==B||(X.status=666),G===T||G===V)return A.avail_out===0&&(X.last_flush=-1),m;if(G===H&&(ie===1?a._tr_align(X):ie!==5&&(a._tr_stored_block(X,0,0,!1),ie===3&&(K(X.head),X.lookahead===0&&(X.strstart=0,X.block_start=0,X.insert=0))),j(A),A.avail_out===0))return X.last_flush=-1,m}return ie!==p?m:X.wrap<=0?1:(X.wrap===2?(ge(X,255&A.adler),ge(X,A.adler>>8&255),ge(X,A.adler>>16&255),ge(X,A.adler>>24&255),ge(X,255&A.total_in),ge(X,A.total_in>>8&255),ge(X,A.total_in>>16&255),ge(X,A.total_in>>24&255)):(Q(X,A.adler>>>16),Q(X,65535&A.adler)),j(A),0=te.w_size&&(ne===0&&(K(te.head),te.strstart=0,te.block_start=0,te.insert=0),ee=new o.Buf8(te.w_size),o.arraySet(ee,ie,he-te.w_size,te.w_size,0),ie=ee,he=te.w_size),ae=A.avail_in,G=A.next_in,D=A.input,A.avail_in=he,A.next_in=0,A.input=ie,we(te);te.lookahead>=C;){for(X=te.strstart,$=te.lookahead-(C-1);te.ins_h=(te.ins_h<>>=C=O>>>24,E-=C,(C=O>>>16&255)===0)H[u++]=65535&O;else{if(!(16&C)){if(!(64&C)){O=b[(65535&O)+(S&(1<>>=C,E-=C),E<15&&(S+=T[c++]<>>=C=O>>>24,E-=C,!(16&(C=O>>>16&255))){if(!(64&C)){O=N[(65535&O)+(S&(1<>>=C,E-=C,(C=u-h)>3,S&=(1<<(E-=I<<3))-1,s.next_in=c,s.next_out=u,s.avail_in=c>>24&255)+(L>>>8&65280)+((65280&L)<<8)+((255&L)<<24)}function S(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function E(L){var P;return L&&L.state?(P=L.state,L.total_in=L.total_out=P.total=0,L.msg="",P.wrap&&(L.adler=1&P.wrap),P.mode=g,P.last=0,P.havedict=0,P.dmax=32768,P.head=null,P.hold=0,P.bits=0,P.lencode=P.lendyn=new s.Buf32(v),P.distcode=P.distdyn=new s.Buf32(y),P.sane=1,P.back=-1,p):m}function b(L){var P;return L&&L.state?((P=L.state).wsize=0,P.whave=0,P.wnext=0,E(L)):m}function N(L,P){var T,H;return L&&L.state?(H=L.state,P<0?(T=0,P=-P):(T=1+(P>>4),P<48&&(P&=15)),P&&(P<8||15=B.wsize?(s.arraySet(B.window,P,T-B.wsize,B.wsize,0),B.wnext=0,B.whave=B.wsize):(H<(V=B.wsize-B.wnext)&&(V=H),s.arraySet(B.window,P,T-H,V,B.wnext),(H-=V)?(s.arraySet(B.window,P,T-H,H,0),B.wnext=H,B.whave=B.wsize):(B.wnext+=V,B.wnext===B.wsize&&(B.wnext=0),B.whave>>8&255,T.check=a(T.check,ne,2,0),Y=j=0,T.mode=2;break}if(T.flags=0,T.head&&(T.head.done=!1),!(1&T.wrap)||(((255&j)<<8)+(j>>8))%31){L.msg="incorrect header check",T.mode=30;break}if((15&j)!=8){L.msg="unknown compression method",T.mode=30;break}if(Y-=4,A=8+(15&(j>>>=4)),T.wbits===0)T.wbits=A;else if(A>T.wbits){L.msg="invalid window size",T.mode=30;break}T.dmax=1<>8&1),512&T.flags&&(ne[0]=255&j,ne[1]=j>>>8&255,T.check=a(T.check,ne,2,0)),Y=j=0,T.mode=3;case 3:for(;Y<32;){if(W===0)break e;W--,j+=H[B++]<>>8&255,ne[2]=j>>>16&255,ne[3]=j>>>24&255,T.check=a(T.check,ne,4,0)),Y=j=0,T.mode=4;case 4:for(;Y<16;){if(W===0)break e;W--,j+=H[B++]<>8),512&T.flags&&(ne[0]=255&j,ne[1]=j>>>8&255,T.check=a(T.check,ne,2,0)),Y=j=0,T.mode=5;case 5:if(1024&T.flags){for(;Y<16;){if(W===0)break e;W--,j+=H[B++]<>>8&255,T.check=a(T.check,ne,2,0)),Y=j=0}else T.head&&(T.head.extra=null);T.mode=6;case 6:if(1024&T.flags&&(W<(re=T.length)&&(re=W),re&&(T.head&&(A=T.head.extra_len-T.length,T.head.extra||(T.head.extra=new Array(T.head.extra_len)),s.arraySet(T.head.extra,H,B,re,A)),512&T.flags&&(T.check=a(T.check,H,re,B)),W-=re,B+=re,T.length-=re),T.length))break e;T.length=0,T.mode=7;case 7:if(2048&T.flags){if(W===0)break e;for(re=0;A=H[B+re++],T.head&&A&&T.length<65536&&(T.head.name+=String.fromCharCode(A)),A&&re>9&1,T.head.done=!0),L.adler=T.check=0,T.mode=12;break;case 10:for(;Y<32;){if(W===0)break e;W--,j+=H[B++]<>>=7&Y,Y-=7&Y,T.mode=27;break}for(;Y<3;){if(W===0)break e;W--,j+=H[B++]<>>=1)){case 0:T.mode=14;break;case 1:if(I(T),T.mode=20,P!==6)break;j>>>=2,Y-=2;break e;case 2:T.mode=17;break;case 3:L.msg="invalid block type",T.mode=30}j>>>=2,Y-=2;break;case 14:for(j>>>=7&Y,Y-=7&Y;Y<32;){if(W===0)break e;W--,j+=H[B++]<>>16^65535)){L.msg="invalid stored block lengths",T.mode=30;break}if(T.length=65535&j,Y=j=0,T.mode=15,P===6)break e;case 15:T.mode=16;case 16:if(re=T.length){if(W>>=5,Y-=5,T.ndist=1+(31&j),j>>>=5,Y-=5,T.ncode=4+(15&j),j>>>=4,Y-=4,286>>=3,Y-=3}for(;T.have<19;)T.lens[ae[T.have++]]=0;if(T.lencode=T.lendyn,T.lenbits=7,te={bits:T.lenbits},ie=l(0,T.lens,0,19,T.lencode,0,T.work,te),T.lenbits=te.bits,ie){L.msg="invalid code lengths set",T.mode=30;break}T.have=0,T.mode=19;case 19:for(;T.have>>16&255,He=65535&$,!((Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>>=Ee,Y-=Ee,T.lens[T.have++]=He;else{if(He===16){for(X=Ee+2;Y>>=Ee,Y-=Ee,T.have===0){L.msg="invalid bit length repeat",T.mode=30;break}A=T.lens[T.have-1],re=3+(3&j),j>>>=2,Y-=2}else if(He===17){for(X=Ee+3;Y>>=Ee)),j>>>=3,Y-=3}else{for(X=Ee+7;Y>>=Ee)),j>>>=7,Y-=7}if(T.have+re>T.nlen+T.ndist){L.msg="invalid bit length repeat",T.mode=30;break}for(;re--;)T.lens[T.have++]=A}}if(T.mode===30)break;if(T.lens[256]===0){L.msg="invalid code -- missing end-of-block",T.mode=30;break}if(T.lenbits=9,te={bits:T.lenbits},ie=l(u,T.lens,0,T.nlen,T.lencode,0,T.work,te),T.lenbits=te.bits,ie){L.msg="invalid literal/lengths set",T.mode=30;break}if(T.distbits=6,T.distcode=T.distdyn,te={bits:T.distbits},ie=l(h,T.lens,T.nlen,T.ndist,T.distcode,0,T.work,te),T.distbits=te.bits,ie){L.msg="invalid distances set",T.mode=30;break}if(T.mode=20,P===6)break e;case 20:T.mode=21;case 21:if(6<=W&&258<=K){L.next_out=z,L.avail_out=K,L.next_in=B,L.avail_in=W,T.hold=j,T.bits=Y,c(L,Q),z=L.next_out,V=L.output,K=L.avail_out,B=L.next_in,H=L.input,W=L.avail_in,j=T.hold,Y=T.bits,T.mode===12&&(T.back=-1);break}for(T.back=0;Le=($=T.lencode[j&(1<>>16&255,He=65535&$,!((Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>qe)])>>>16&255,He=65535&$,!(qe+(Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>>=qe,Y-=qe,T.back+=qe}if(j>>>=Ee,Y-=Ee,T.back+=Ee,T.length=He,Le===0){T.mode=26;break}if(32&Le){T.back=-1,T.mode=12;break}if(64&Le){L.msg="invalid literal/length code",T.mode=30;break}T.extra=15&Le,T.mode=22;case 22:if(T.extra){for(X=T.extra;Y>>=T.extra,Y-=T.extra,T.back+=T.extra}T.was=T.length,T.mode=23;case 23:for(;Le=($=T.distcode[j&(1<>>16&255,He=65535&$,!((Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>qe)])>>>16&255,He=65535&$,!(qe+(Ee=$>>>24)<=Y);){if(W===0)break e;W--,j+=H[B++]<>>=qe,Y-=qe,T.back+=qe}if(j>>>=Ee,Y-=Ee,T.back+=Ee,64&Le){L.msg="invalid distance code",T.mode=30;break}T.offset=He,T.extra=15&Le,T.mode=24;case 24:if(T.extra){for(X=T.extra;Y>>=T.extra,Y-=T.extra,T.back+=T.extra}if(T.offset>T.dmax){L.msg="invalid distance too far back",T.mode=30;break}T.mode=25;case 25:if(K===0)break e;if(re=Q-K,T.offset>re){if((re=T.offset-re)>T.whave&&T.sane){L.msg="invalid distance too far back",T.mode=30;break}we=re>T.wnext?(re-=T.wnext,T.wsize-re):T.wnext-re,re>T.length&&(re=T.length),Ae=T.window}else Ae=V,we=z-T.offset,re=T.length;for(KM?(C=we[Ae+y[P]],Y[ge+y[P]]):(C=96,0),S=1<>z)+(E-=S)]=O<<24|C<<16|I|0,E!==0;);for(S=1<>=1;if(S!==0?(j&=S-1,j+=S):j=0,P++,--Q[L]==0){if(L===H)break;L=h[p+y[P]]}if(V>>7)]}function ge($,ne){$.pending_buf[$.pending++]=255&ne,$.pending_buf[$.pending++]=ne>>>8&255}function Q($,ne,ae){$.bi_valid>_-ae?($.bi_buf|=ne<<$.bi_valid&65535,ge($,$.bi_buf),$.bi_buf=ne>>_-$.bi_valid,$.bi_valid+=ae-_):($.bi_buf|=ne<<$.bi_valid&65535,$.bi_valid+=ae)}function re($,ne,ae){Q($,ae[2*ne],ae[2*ne+1])}function we($,ne){for(var ae=0;ae|=1&$,$>>>=1,ae<<=1,0<--ne;);return ae>>>1}function Ae($,ne,ae){var G,D,ee=new Array(y+1),he=0;for(G=1;G<=y;G++)ee[G]=he=he+ae[G-1]<<1;for(D=0;D<=ne;D++){var ce=$[2*D+1];ce!==0&&($[2*D]=we(ee[ce]++,ce))}}function Ee($){var ne;for(ne=0;ne>1;1<=ae;ae--)qe($,ee,ae);for(D=_e;ae=$.heap[1],$.heap[1]=$.heap[$.heap_len--],qe($,ee,1),G=$.heap[1],$.heap[--$.heap_max]=ae,$.heap[--$.heap_max]=G,ee[2*D]=ee[2*ae]+ee[2*G],$.depth[D]=($.depth[ae]>=$.depth[G]?$.depth[ae]:$.depth[G])+1,ee[2*ae+1]=ee[2*G+1]=D,$.heap[1]=D++,qe($,ee,1),2<=$.heap_len;);$.heap[--$.heap_max]=$.heap[1],function(Oe,Ge){var Lt,Pe,nt,et,yt,rt,Ct=Ge.dyn_tree,Rt=Ge.max_code,Sn=Ge.stat_desc.static_tree,le=Ge.stat_desc.has_stree,je=Ge.stat_desc.extra_bits,Ce=Ge.stat_desc.extra_base,ke=Ge.stat_desc.max_length,$e=0;for(et=0;et<=y;et++)Oe.bl_count[et]=0;for(Ct[2*Oe.heap[Oe.heap_max]+1]=0,Lt=Oe.heap_max+1;Lt>=7;D>>=1)if(1&ze&&ce.dyn_ltree[2*_e]!==0)return o;if(ce.dyn_ltree[18]!==0||ce.dyn_ltree[20]!==0||ce.dyn_ltree[26]!==0)return a;for(_e=32;_e>>3,(ee=$.static_len+3+7>>>3)<=D&&(D=ee)):D=ee=ae+5,ae+4<=D&&ne!==-1?X($,ne,ae,G):$.strategy===4||ee===D?(Q($,2+(G?1:0),3),it($,U,L)):(Q($,4+(G?1:0),3),function(ce,_e,ze,Oe){var Ge;for(Q(ce,_e-257,5),Q(ce,ze-1,5),Q(ce,Oe-4,4),Ge=0;Ge>>8&255,$.pending_buf[$.d_buf+2*$.last_lit+1]=255&ne,$.pending_buf[$.l_buf+$.last_lit]=255&ae,$.last_lit++,ne===0?$.dyn_ltree[2*ae]++:($.matches++,ne--,$.dyn_ltree[2*(T[ae]+h+1)]++,$.dyn_dtree[2*Y(ne)]++),$.last_lit===$.lit_bufsize-1},i._tr_align=function($){Q($,2,3),re($,E,U),function(ne){ne.bi_valid===16?(ge(ne,ne.bi_buf),ne.bi_buf=0,ne.bi_valid=0):8<=ne.bi_valid&&(ne.pending_buf[ne.pending++]=255&ne.bi_buf,ne.bi_buf>>=8,ne.bi_valid-=8)}($)}},{"../utils/common":41}],53:[function(n,r,i){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,i){(function(s){(function(o,a){if(!o.setImmediate){var c,l,u,h,p=1,m={},g=!1,v=o.document,y=Object.getPrototypeOf&&Object.getPrototypeOf(o);y=y&&y.setTimeout?y:o,c={}.toString.call(o.process)==="[object process]"?function(b){process.nextTick(function(){S(b)})}:function(){if(o.postMessage&&!o.importScripts){var b=!0,N=o.onmessage;return o.onmessage=function(){b=!1},o.postMessage("","*"),o.onmessage=N,b}}()?(h="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",E,!1):o.attachEvent("onmessage",E),function(b){o.postMessage(h+b,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(b){S(b.data)},function(b){u.port2.postMessage(b)}):v&&"onreadystatechange"in v.createElement("script")?(l=v.documentElement,function(b){var N=v.createElement("script");N.onreadystatechange=function(){S(b),N.onreadystatechange=null,l.removeChild(N),N=null},l.appendChild(N)}):function(b){setTimeout(S,0,b)},y.setImmediate=function(b){typeof b!="function"&&(b=new Function(""+b));for(var N=new Array(arguments.length-1),R=0;R"u"?s===void 0?this:s:self)}).call(this,typeof To<"u"?To:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(upe);const zF={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(zF);var Xs=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},hf,fp,Cu;class hpe{constructor(...e){hf.set(this,new Map),fp.set(this,new Map),Cu.set(this,new Map);for(const n of e)this.define(n)}define(e,n=!1){for(let[r,i]of Object.entries(e)){r=r.toLowerCase(),i=i.map(a=>a.toLowerCase()),Xs(this,Cu,"f").has(r)||Xs(this,Cu,"f").set(r,new Set);const s=Xs(this,Cu,"f").get(r);let o=!0;for(let a of i){const c=a.startsWith("*");if(a=c?a.slice(1):a,s==null||s.add(a),o&&Xs(this,fp,"f").set(r,a),o=!1,c)continue;const l=Xs(this,hf,"f").get(a);if(l&&l!=r&&!n)throw new Error(`"${r} -> ${a}" conflicts with "${l} -> ${a}". Pass \`force=true\` to override this definition.`);Xs(this,hf,"f").set(a,r)}}return this}getType(e){if(typeof e!="string")return null;const n=e.replace(/^.*[/\\]/,"").toLowerCase(),r=n.replace(/^.*\./,"").toLowerCase(),i=n.length{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(const e of Xs(this,Cu,"f").values())Object.freeze(e);return this}_getTestState(){return{types:Xs(this,hf,"f"),extensions:Xs(this,fp,"f")}}}hf=new WeakMap,fp=new WeakMap,Cu=new WeakMap;new hpe(zF)._freeze();function ab(t){if(!t||t.type===void 0)return;const e=[{start:t.startOffset,end:t.endOffset??0}];return Object.keys(t).forEach(n=>{if(n!=="parent"){const r=t[n];cn(r)?r.forEach(i=>{e.push(ab(i))}):e.push(ab(r))}}),t.range={start:Math.min(...e.filter(n=>n).map(n=>(n==null?void 0:n.start)??0)),end:Math.max(...e.filter(n=>n).map(n=>(n==null?void 0:n.end)??0))},t.range}function fpe(t){const e=gF(`${t} -`);if(e.errors.length>0)return e;yf.input=e.tokens;const n=yf.program();if(yf.errors.length>0)return{tokens:e.tokens,errors:yf.errors.map(i=>({offset:i.token.startOffset,line:i.token.startLine,column:i.token.startColumn,length:i.token.image.length,message:i.message}))};const[r]=epe.go(n);return r?(ab(r),{tokens:e.tokens,cst:n,ast:r}):{tokens:e.tokens,cst:n,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]}}const FS=Object.getPrototypeOf(function*(){}).constructor;function dpe(t,e){const n=`compile-${t}`;console.time(n);const r=fpe(e);if(console.timeEnd(n),r.errors&&r.errors.length>0)return r;if(!r.ast)return{...r,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]};const i=spe(r.ast);if(i.code){zre&&console.info(i.code);try{return{...r,...i,source:i.code,code:new FS("api",i.code)}}catch(s){return{errors:[{message:`unexpected error ${s.message}`,offset:0,line:0,column:0,length:0}],source:"",code:new FS("api"," ")}}}return{...r,...i,source:"",code:new FS("api"," ")}}function ppe(){const t={},e={};function n(i,s){const o=t[s];if(o)return o;const a=dpe(i,s);return t[s]=a,a}const r={ids(){return Object.keys(e)},has(i){return Z(e[i])},isended(i){const s=e[i];return Z(s)?s.isended():!0},halt(i){const s=e[i];return Z(s)&&(s.halt(),delete e[i]),!!s},gc(){const i=r.ids();for(let s=0;s[_,S]);g.slice(m-5,m).forEach(([_,S])=>{Vn("os","build",`$grey${S+1} $grey${_}`)});const[v,y]=g[m]??[];if(Kt(v)&&Z(y)){const _=(p.column??1)-1,S=_+p.length,E=_{Vn("os","build",_)}),!1}}return!!(l!=null&&l.tick(o))},once(i,s,o,a){const c=r.tick(i,s,1,o,a);return r.halt(i)&&c},message(i){const{target:s,path:o}=dL(i.target),a=e[s];if(Z(a)){const c={...i,target:o};a.message(c)}}};return r}const VF=ppe();var Mr=(t=>(t.MAIN="main",t.TITLE="title",t.PLAYER="player",t.CONTENT="content",t.GADGETSTORE="gadgetstore",t.GADGETSYNC="gadgetsync",t))(Mr||{});const Wa={defaultplayer:f9(),software:{main:"",content:""},books:new Map,chips:new Map,loaders:new Map,chipindex:new Map,codepageindex:new Map,binaryfiles:new Map};function cb(){return[...Wa.books.values()]}function mpe(){const[t]=Wa.books.values();return t}function ad(t){const e=$t(t);return Wa.books.get(t)??cb().find(n=>n.name===e)}function lb(t,e){Z(ad(e))&&(Wa.software[t]=e)}function dp(t){return ad(Wa.software[t])}function HF(t){const e=xF([]);return Kt(t)&&(e.name=t),GF(e),ro("memory",`created [book] ${e.name}`),e}function gpe(t){let e=ad(t);return Z(e)||(e=xF([]),e.name=t),GF(e),ro("memory",`created [book] ${e.name}`),e}function Rc(t,e){let n=Z(e)?gpe(e):dp(t);return Z(n)||(Z(n)||(n=mpe()),Z(n)||(n=HF(e)),Z(n)&&ro("memory",`opened [book] ${n.name} for ${t}`)),lb(t,n.id),n}function Eu(t,e,n){const r=Rc(t);let i=Vm(r,e);if(Z(i))return i;const s=vF(n);return i=Pfe(s==="object"?`@${e} -`:`@${s} ${e} -`,{}),Ufe(r,i),ype(i.id,r.id),Tu("memory"),i}function Xp(t){const e=Rc("main");return zfe(e,t)}function _pe(t){const e=Rc("main");return Vfe(e,t)}function GF(t){return Wa.books.set(t.id,t),t.id}function vpe(t){const e=ad(t);e&&Wa.books.delete(e.id)}function ype(t,e){Wa.codepageindex.set(t,e)}function xpe(t,e,n,r,i=vae){if(!Z(t)||!Z(e)||!Z(n))return;const s={...se};se.book=t,se.board=e,se.element=n,se.player=n.player??Wa.defaultplayer,se.isplayer=d9(n.id??"");const o=Fc(t,n),a=n.cycle??(o==null?void 0:o.cycle)??i,c=n.id??"",l=GA(n);if(VF.tick(c,YA.CODE_PAGE,mt(a)?a:i,l,r),mt(n==null?void 0:n.tickertime)&&se.timestamp-n.tickertime>hv*5&&(n.tickertime=0,n.tickertext=""),se.isplayer){const u=Xp(se.player);u.inputcurrent=0}aL(s).forEach(u=>{se[u]=s[u]})}function Mv(t){const e=Rc("main"),n=Vm(e,t);if(!Z(e)||!Z(n)||!Z(se.element))return;const r=`${t}_run`,i=GA(se.element),s=(n==null?void 0:n.code)??"";VF.once(r,YA.CODE_PAGE,i,s)}function WF(t){return Wa.binaryfiles.get(t)}function Fi(t,e=!0){var r,i,s,o,a;const n=se.words[t];if(D4(n)){const[c,l]=R_(t);if(Z(c))return[c,l]}if(Afe(n)){const[c,l]=F4(t);if(Z(c))return[c,l]}if($F(n)){const[c,l]=Cv(t);if(Z(c))return[c,l]}if(Kt(n)&&$t(n)==="rnd"){const[c,l]=Fi(t+1),[u,h]=Fi(l);return mt(c)&&mt(u)?[sp(c,u),h]:mt(c)?[sp(0,c),l]:[sp(0,1),t+1]}if(s4(n)){const[c,l]=Fw(t);if(Z(c))return[c,l]}if(!Z(n))return[void 0,t];if(xc(n)||mt(n)||cn(n))return[n,t+1];if(Kt(n)){const c=$t(n);if(e){const l=(r=se.get)==null?void 0:r.call(se,n);if(Z(l))return[l,t+1]}switch(c){case"aligned":case"alligned":{const l=aI(se.board,se.element,se.player);return!Z(se.element)||!Z(l)?[0,t+1]:[se.element.x===l.x||se.element.y===l.y?1:0,t+1]}case"contact":{const l=aI(se.board,se.element,se.player);if(!Z(se.element)||!Z(l))return[0,t+1];const u=(l.x??0)-(((i=se.element)==null?void 0:i.x)??0),h=(l.y??0)-(((s=se.element)==null?void 0:s.y)??0);return[u===0&&Math.abs(h)<2||h===0&&Math.abs(u)<2?1:0,t+1]}case"blocked":{const[l,u]=Ve(se.words,t+1,[Ie.DIR]);return[Hfe(se.book,se.board,se.element,l)?1:0,u]}case"any":{const[l,u]=Ve(se.words,t+1,[Ie.KIND]),h=wv(l)??"",p=Fm(se.board,h);return[l4(p,l).length?1:0,u]}case"rnd":return[sp(0,1),t+1];case"abs":{const[l,u]=Ve(se.words,t+1,[Ie.NUMBER]);return[Math.abs(l),u]}case"ceil":{const[l,u]=Ve(se.words,t+1,[Ie.NUMBER]);return[Math.ceil(l),u]}case"floor":{const[l,u]=Ve(se.words,t+1,[Ie.NUMBER]);return[Math.floor(l),u]}case"round":{const[l,u]=Ve(se.words,t+1,[Ie.NUMBER]);return[Math.round(l),u]}case"min":{const l=[];for(let u=t+1;uwn.WHITE&&twn[e]).find(e=>Z(e)&&ewn[e]).find(e=>Z(e)&&e>=wn.ONBLACK)}function FI(t){if(oo(t))return t;if(jF(t))return[t];const e=$F(t);if(Z(e))return[e]}function BI(t){const e=se.words[t],n=FI(e);if(oo(n))return[n,t+1];const[r,i]=Fi(t),s=FI(r);return oo(s)?[s,i]:[void 0,t]}function Cv(t){const e=[];let n=t;const[r,i]=BI(t);if(oo(r)&&(e.push(...r),n=i),oo(e)&&!UI(e)){const[s,o]=BI(i);UI(s)&&(n=o)}return e.length?[e,n]:[void 0,t]}function Tpe(t){const e={};return t.every(n=>{const r=wn[n];Z(r)&&(rString.fromCharCode(t)),Mpe=Fs({name:"Whitespace",pattern:/ +/}),Cpe=Fs({name:"WhitespaceSkipped",pattern:/ +/,group:zr.SKIPPED}),QA=Fs({name:"Newline",line_breaks:!0,start_chars_hint:[` -`,"\r"],pattern:/\n|\r\n?/}),eM=Fs({name:"StringLiteral",pattern:/[^ $;\r\n]+/,start_chars_hint:Ape}),tM=Fs({name:"StringLiteralDouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),nM=Fs({name:"EscapedDollar",pattern:"$$"}),rM=Fs({name:"MaybeFlag",pattern:/\$[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/}),iM=Fs({name:"NumberLiteral",pattern:/\$-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?\+?/}),sM=Fs({name:"HyperLinkText",pattern:/;[^;\r\n]*/,start_chars_hint:[";"]});function Rpe(t,e=""){return Fs({name:e||t,pattern:new RegExp(t.toLowerCase(),"i")})}const Npe=Object.keys(Jy),qF=Npe.map(t=>Rpe(`\\$(${t})`,t)),kpe=[Mpe,QA,...qF,tM,eM,iM,nM,sM,rM],Ipe=new zr(kpe,{skipValidations:!Ra,ensureOptimizations:Ra}),Ope=new zr([Cpe,QA,...qF,tM,eM,iM,nM,sM,rM],{skipValidations:!Ra,ensureOptimizations:Ra});function Qy(t,e=!1){return e?Ope.tokenize(t):Ipe.tokenize(t)}function jm(t,e,n,r,i,s,o,a){return{disablewrap:!1,measureonly:!1,measuredwidth:0,writefullwidth:void 0,x:0,y:0,iseven:!0,active:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},reset:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},width:t,height:e,char:[],color:[],bg:[],changed(){}}}function ex(t){t.active={...t.reset}}function oM(t,e){const n=e.y;function r(){++e.x;const a=e.active.rightedge??e.width-1;!e.disablewrap&&e.x>a&&(e.x=e.active.leftedge??0,++e.y),e.x>e.measuredwidth&&(e.measuredwidth=e.x)}function i(){return e.x>=(e.active.leftedge??0)&&e.x<=(e.active.rightedge??e.width-1)&&e.y>=(e.active.topedge??0)&&e.y<=(e.active.bottomedge??e.height-1)}function s(a){for(let c=0;ce.measuredwidth&&(e.measuredwidth=e.x+1);const o=e.active.leftedge??0;if(Z(e.writefullwidth)&&(e.x>o||e.y===n)){const c=(e.active.rightedge??e.width-1)-e.x;if(c>0){ex(e);const l=String.fromCharCode(e.writefullwidth).repeat(c),u=e.x+e.y*e.width;nx(u,u+l.length,e.active.color,e.active.bg,e),tx(u,l,e)}}}function Hn(t,e,n){const r=Qy(t);r.tokens&&(oM(r.tokens,e),n&&ex(e))}function aM(t,e,n){const r=Qy(t);if(!r.tokens)return;const i=jm(e,n,wn.WHITE,wn.BLACK);return i.measureonly=!0,oM(r.tokens,i),i.x>0&&++i.y,i}function tx(t,e,n){let r=0;const i=t+e.length;for(let s=t;s({blink:!1}));setInterval(()=>{KF.setState(t=>({blink:!t.blink}))},333);function $a(){return KF(t=>t.blink)}function YF(){return $T(t=>{function e(){t({render:Math.random()})}return{dither:[],render:0,changed(){setTimeout(e,0)}}})}function Lpe(t){t.fill(0)}function BS(t,e,n,r,i,s){if(r<0||r>=e||i<0||i>=n)return-1;t[r+i*e]=s}const ZF=Ne.createContext(YF());function Ppe(t,e,n){const[r]=Ne.useState(()=>YF()),i=t*e,s=r.getState();return s.dither.length!==i&&(s.dither=new Array(i).fill(n),s.render=0),r}function JF(){return $T(t=>{function e(){t({render:Math.random()})}return{width:0,height:0,char:[],color:[],bg:[],render:0,changed(){setTimeout(e,0)}}})}function Dpe(t,e,n,r){t.char.fill(e),t.color.fill(n),t.bg.fill(r)}function Pr(t,e,n,r,i,s){if(r<0||r>=e||i<0||i>=n)return;const o=r+i*e;aL(s).forEach(a=>{const c=s[a];Z(c)&&(t[a][o]=c)})}const cM=Ne.createContext(JF());function lM(t,e,n,r,i){const[s]=Ne.useState(()=>JF()),o=t*e,a=s.getState();return a.char.length!==o&&(a.width=t,a.height=e,a.char=new Array(o).fill(n),a.color=new Array(o).fill(r),a.bg=new Array(o).fill(i),a.render=0),s}function Upe(){return Ne.useContext(cM).getState()}function Fpe({item:t,context:e}){return Hn(`${t} -`,e,!0),null}const rx=Ne.createContext({sendmessage(){},sendclose(){},didclose(){}}),zI={input:{color:"$white",active:"$yellow"}};function Jl(t){return t?zI.input.active:zI.input.color}function ao(t,e){return typeof t==typeof e?t:e}function QF(t,e){return`vm:${t}:${e}`}function pp(t,e,n=0,r=""){return`${t.substring(0,e)}${r}${t.substring(e+n)}`}function Bpe({chip:t,active:e,label:n,args:r,context:i}){var p;const[s,o,a]=[ao(r[0],""),ao(r[1],((p=r[1])==null?void 0:p.toString())??""),ao(r[2],"")],c=a||` ${o.toUpperCase()} `,l=Jl(e);Hn(`${i.iseven?"$black$onltgray":"$black$ondkcyan"}${c}${l}$onclear ${n} -`,i,!0);const u=Ne.useContext(rx),h=Ne.useCallback(()=>{u.sendmessage(QF(t,s)),u.sendclose()},[t,u,s]);return ve.jsxs(ve.Fragment,{children:[e&&ve.jsx(gs,{OK_BUTTON:h}),ve.jsx(xp,{hotkey:o,children:h})]})}function zpe({chip:t,active:e,label:n,args:r,context:i}){const[s,o]=[ao(r[0],""),r[1]],a=Jl(e);Hn(` $purple$16 ${a}${n} -`,i,!0);const c=Ne.useContext(rx),l=Ne.useCallback(()=>{c.sendmessage(QF(t,s),o),c.sendclose()},[c,t,s,o]);return e&&ve.jsx(gs,{OK_BUTTON:l})}function Vpe({chip:t,active:e,label:n,args:r,context:i}){const[s,o,a]=[ao(r[0],""),ao(r[1],-1),ao(r[2],-1)];let c,l;o===-1?(c=0,l=31):a===-1?(c=0,l=o):(c=o,l=a);const u=xd(t,s),h=vA(u),p=h==null?void 0:h.value,m=p??0,g=$a(),[v,y]=Ne.useState(""),[_,S]=Ne.useState(0),[E,b]=Ne.useState(!1);let N=`${m}`;const R=n.trim(),M=Jl(e);E&&(N=g?pp(v,_,1,"$219+"):v),i.writefullwidth=32,Hn(` # ${M}${R} $green${N}`,i,!1),i.writefullwidth=void 0,Hn(` -`,i,!1);const O=Ne.useCallback(U=>{const L=U.alt?10:1;Rl(u,Math.min(l,m+L))},[l,m,u]),C=Ne.useCallback(U=>{const L=U.alt?10:1;Rl(u,Math.max(c,m-L))},[c,m,u]),I=Ne.useCallback(()=>{b(U=>{const L=!U;if(L){const P=`${p}`;y(P),S(P.length)}else{const P=parseFloat(v),T=isNaN(P)?0:P;Rl(s,Math.min(l,Math.max(c,T)))}return L})},[l,c,v,s,p]);return p!==void 0&&ve.jsxs(ve.Fragment,{children:[e&&ve.jsx(gs,{MOVE_LEFT:C,MOVE_RIGHT:O,OK_BUTTON:I}),E&&ve.jsxs(Im,{blockhotkeys:!0,children:[ve.jsx(xp,{hotkey:"ctrl+c",children:()=>{console.info("copy")}}),ve.jsx(xp,{hotkey:"ctrl+v",children:()=>{console.info("paste")}}),ve.jsx(xp,{hotkey:"ctrl+a",children:()=>{console.info("select all")}}),ve.jsx(gs,{MOVE_LEFT:()=>{S(U=>Math.max(0,U-1))},MOVE_RIGHT:()=>{S(U=>Math.min(v.length,U+1))},CANCEL_BUTTON:I,OK_BUTTON:I,keydown:U=>{switch($t(U.key)){case"delete":v.length>0&&y(L=>pp(L,_,1));break;case"backspace":_>0&&(y(L=>pp(L,_-1,1)),S(L=>Math.max(0,L-1)));break}U.key.length===1&&v.lengthpp(L,_,0,U.key)),S(L=>L+1))}})]})]})}function Hpe({chip:t,active:e,label:n,args:r,context:i}){const[s,o,a]=[ao(r[0],""),ao(r[1],""),ao(r[2],"")];let c,l;o===""?(c="L ",l=" H"):a===""?(c="L ",l=` ${o}`):(c=`${o} `,l=` ${a}`);const u=0,h=8,p=xd(t,s),m=vA(p),g=(m==null?void 0:m.value)??0,v=$a(),y=n.trim(),_=Jl(e);Hn(` $red $29 ${_}${y} `,i,!1);const E=pp("----:----",g,1,`$green${e?v?"$26":"$27":"$4"}${_}`).replaceAll("-","$7").replaceAll(":","$9");Hn(`${_}${c}${E}${l} $green${g+1} -`,i,!1);const b=Ne.useCallback(R=>{const M=R.alt?10:1;Rl(p,Math.min(h,g+M))},[h,g,p]),N=Ne.useCallback(R=>{const M=R.alt?10:1;Rl(p,Math.max(u,g-M))},[u,g,p]);return ve.jsx(ve.Fragment,{children:e&&ve.jsx(gs,{MOVE_LEFT:N,MOVE_RIGHT:b})})}function Gpe({chip:t,active:e,label:n,args:r,context:i}){const[s,...o]=[ao(r[0],""),...r.slice(1)],a=0,c=o.length-1,l=xd(t,s),u=vA(l),h=(u==null?void 0:u.value)??0,p=$a(),m=`${o[h]}`,g=n.trim(),v=Jl(e);Hn(` $dkred ? ${v}${g} `,i,!1);const y=e?p?"$26":"$27":"/";Hn(`${h+1}$green${y}${v}${c+1}`,i,!1),i.writefullwidth=32,Hn(` $green${m}`,i,!1),i.writefullwidth=void 0,Hn(` -`,i,!1);const _=Ne.useCallback(E=>{const b=E.alt?10:1;Rl(l,Math.min(c,h+b))},[c,h,l]),S=Ne.useCallback(E=>{const b=E.alt?10:1;Rl(l,Math.max(a,h-b))},[a,h,l]);return ve.jsx(ve.Fragment,{children:e&&ve.jsx(gs,{MOVE_LEFT:S,MOVE_RIGHT:_})})}function Wpe({chip:t,active:e,label:n,args:r,context:i}){const s=ao(r[0],""),o=xd(t,s),a=DU(o),c=a==null?void 0:a.value,l=(c==null?void 0:c.toJSON())??"",u=$a(),[h,p]=Ne.useState(0),[m,g]=Ne.useState(!1),[v,y]=Ne.useState(void 0),_=`${l} `,S=n.trim(),E=Jl(e);Hn(`$green $20 ${E}${S} $green`,i,!1);const b=i.x,R=i.y*i.width;i.writefullwidth=32,Hn(`${_}`,i,!1),i.writefullwidth=void 0,Hn(` -`,i,!1);const M=Z(v),O=i.width-b-2,C=M?Math.min(v,h):h;let I=M?Math.max(v,h):h;M&&(I!==C&&I===h&&--I,nx(b+C+R,b+I+R,15,8,i)),m&&u&&tx(b+h+R,"Û",i);function U(){Z(c)&&(p(C),y(void 0),c.delete(C,I-C+1))}return ve.jsxs(ve.Fragment,{children:[e&&ve.jsx(gs,{OK_BUTTON:()=>{c&&(g(!0),p(c.length),y(void 0))}}),m&&ve.jsx(Im,{blockhotkeys:!0,children:ve.jsx(gs,{MOVE_LEFT:L=>{L.shift?Z(v)||y(Cn(h-1,0,l.length)):y(void 0),p(P=>Cn(P-1,0,l.length))},MOVE_RIGHT:L=>{L.shift?Z(v)||y(h):y(void 0),p(P=>Cn(P+1,0,l.length))},CANCEL_BUTTON:()=>{g(!1),p(l.length),y(void 0)},OK_BUTTON:()=>g(!1),keydown:L=>{if(!c)return;const{key:P}=L,T=$t(P),H={alt:L.altKey,ctrl:nd?L.metaKey:L.ctrlKey,shift:L.shiftKey},V=c.toJSON();switch(T){case"delete":M?U():V.length>0&&c.delete(h,1);break;case"backspace":M?U():h>0&&(c.delete(h-1,1),p(B=>Math.max(0,B-1)));break;default:if(H.ctrl)switch(T){case"a":y(0),p(V.length);break;case"c":Z(navigator.clipboard)&&navigator.clipboard.writeText(c.toJSON()).catch(B=>console.error(B));break;case"v":Z(navigator.clipboard)&&navigator.clipboard.readText().then(B=>{M&&U(),c.insert(h,B),p(h+B.length)}).catch(B=>console.error(B));break;case"x":Z(navigator.clipboard)&&navigator.clipboard.writeText(c.toJSON()).then(()=>U()).catch(B=>console.error(B));break}else H.alt||P.length===1&&V.lengthB+1));break}}})})]})}function jpe({item:t,active:e}){const n=XT(),r=ja();if(r.iseven=r.y%2===0,typeof t=="string")return ve.jsx(Fpe,{player:n,item:t,context:r});if(cn(t)){const[i,s,o,...a]=t;if(typeof i!="string"||typeof s!="string"||typeof o!="string")return null;const c={player:n,chip:i,active:e,label:s,args:a,context:r};switch($t(o)){case"hk":case"hotkey":return ve.jsx(Bpe,{...c});case"hyperlink":return ve.jsx(zpe,{...c});case"rn":case"range":return ve.jsx(Hpe,{...c});case"sl":case"select":return ve.jsx(Gpe,{...c});case"nm":case"number":return ve.jsx(Vpe,{...c});case"tx":case"text":return ve.jsx(Wpe,{...c})}ex(r)}return null}function uM({store:t,children:e}){return ve.jsx(cM.Provider,{value:t,children:e})}function hM({width:t,height:e}){const n=Ne.useContext(cM),[r,i,s]=qT(n,Yl(o=>[o.char,o.color,o.bg,o.render]));return t>0&&e>0&&ve.jsx(h3,{char:r.slice(),color:i.slice(),bg:s.slice(),width:t,height:e})}function eB({margin:t=1,selected:e=-1,width:n,height:r,color:i,bg:s,text:o}){const a=lM(n,r,0,i,s),c=a.getState(),l={...jm(n,r,i,s,0,t,n-t,r),...a.getState(),x:t};return Dpe(c,0,i,s),c.changed(),ve.jsxs(uM,{store:a,children:[ve.jsx(Iu.Provider,{value:l,children:o.map((u,h)=>ve.jsx(jpe,{item:u,active:h===e},h))}),ve.jsx(hM,{width:n,height:r})]})}var $pe=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.01,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1/(2*Math.PI);return r/Math.atan(1/n)*Math.atan(Math.sin(2*Math.PI*e*i)/n)},qpe=function(e){return 1/(1+e+.48*e*e+.235*e*e*e)};function Xpe(t,e,n){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:.25,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:.01,s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1/0,o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:qpe,a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:.001,c="velocity_"+e;if(t.__damp===void 0&&(t.__damp={}),t.__damp[c]===void 0&&(t.__damp[c]=0),Math.abs(t[e]-n)<=a)return t[e]=n,!1;r=Math.max(1e-4,r);var l=2/r,u=o(l*i),h=t[e]-n,p=n,m=s*r;h=Math.min(Math.max(h,-m),m),n=t[e]-h;var g=(t.__damp[c]+l*h)*i;t.__damp[c]=(t.__damp[c]-l*g)*u;var v=n+(h+g)*u;return p-t[e]>0==v>p&&(v=p,t.__damp[c]=(v-p)/i),t[e]=v,!0}const Kpe=2,Ype=14,tB=Ype*Kpe;function Zpe(t){return RW(t,tB*.5)}function Jpe(t,e,n,r,i=1.235){function s(a){return $pe(a,r)}Xpe(t.userData,e,n,i,r,tB*12,s),t.position[e]=Zpe(t.userData[e]);const o=n-t.position.y;return Math.abs(o)<.1}function VI({x:t,y:e,color:n,on:r=232,off:i=7,alt:s}){const o=$a(),a=Upe(),c=Ne.useRef(0),l=Z(s)?c.current%2===0?r:s:r;return Pr(a,a.width,a.height,t,e,{char:o?l:i,color:n}),a.changed(),o&&++c.current,null}function Qpe({store:t,children:e}){return ve.jsx(ZF.Provider,{value:t,children:e})}function eme({width:t,height:e}){const n=Ne.useContext(ZF),[r]=qT(n,Yl(i=>[i.dither,i.render]));return t>0&&e>0&&ve.jsx(By,{alphas:r.slice(),width:t,height:e})}function tme({name:t,width:e,height:n,color:r,bg:i,text:s,shouldclose:o}){const{viewport:a}=va(),c=e-3,l=n-3,u=lM(e,n,0,r,i),h=Ppe(c,l,0),p=Ne.useContext(rx),m=u.getState();for(let T=1;T2&&T{o&&p.didclose()},[o,p]);Ne.useEffect(()=>{if(I.current&&!o){const T=a.height;I.current.position.y=T,I.current.userData.y=T,I.current.userData.vy=0}},[o]),zv(Ne.useCallback((T,H)=>{if(Z(I.current)){const V=o?n*2*-Hi:0;Jpe(I.current,"y",V,H)&&U()}},[o,U,n]));const L=Ne.useCallback(T=>{const H=T.alt?10:1;E(V=>Math.max(0,V-H))},[E]),P=Ne.useCallback(T=>{const H=T.alt?10:1;E(V=>Math.min(s.length,V+H))},[E,s.length]);return ve.jsx(uM,{store:u,children:ve.jsx(Qpe,{store:h,children:ve.jsx("group",{ref:I,"position-y":1e6,children:ve.jsxs(Im,{children:[ve.jsx(gs,{MOVE_UP:L,MOVE_DOWN:P,CANCEL_BUTTON:p.sendclose}),ve.jsx(hM,{width:e,height:n}),ve.jsxs("group",{position:[2*as,2*Hi,0],children:[ve.jsx(eme,{width:c,height:l}),ve.jsx(eB,{name:t,width:c,height:l,margin:0,color:r,bg:wn.ONCLEAR,text:N,selected:R}),ve.jsx(VI,{x:1,y:1}),ve.jsx(VI,{x:1,y:2+R,on:26,alt:27,off:45,color:12})]})]})})})})}function HI({rect:t,shouldclose:e=!1}){switch(t.type){case 0:return ve.jsx(eB,{name:t.name,width:t.width,height:t.height,color:14,bg:1,text:t.text});case 1:return ve.jsx(tme,{name:t.name,width:t.width,height:t.height,color:14,bg:1,text:t.text,shouldclose:e});case 2:return ve.jsx(ale,{width:t.width,height:t.height})}return null}function nme(){const t=va(g=>g.viewport),{width:e,height:n}=t.getCurrentViewport(),r=Math.floor(e/as),i=Math.floor(n/Hi),s=e-r*as,o=n-i*Hi,[a,c]=Ne.useState(),[l,u]=os(bne(g=>[g.gadget.player,g.gadget.panels]));if(r<1||i<1)return null;const h={name:"main",type:2,x:0,y:0,width:r,height:i,text:[]},p=[];let m=!0;return u.forEach(g=>{let v;switch(g.edge){case Si.LEFT:v={name:g.name,type:0,x:h.x,y:h.y,width:g.size,height:h.height,text:g.text},h.x+=g.size,h.width-=g.size,p.push(v);break;default:case Si.RIGHT:v={name:g.name,type:0,x:h.x+h.width-g.size,y:h.y,width:g.size,height:h.height,text:g.text},h.width-=g.size,p.push(v);break;case Si.TOP:v={name:g.name,type:0,x:h.x,y:h.y,width:h.width,height:g.size,text:g.text},h.y+=g.size,h.height-=g.size,p.push(v);break;case Si.BOTTOM:v={name:g.name,type:0,x:h.x,y:h.y+h.height-g.size,width:h.width,height:g.size,text:g.text},h.height-=g.size,p.push(v);break;case Si.SCROLL:v={name:g.name,type:1,x:0,y:0,width:Cn(g.size||50,24,h.width-2),height:Cn(18,8,h.height-8),text:g.text},v.x=h.x+Math.floor((h.width-v.width)*.5),v.y=h.y+Math.floor((h.height-v.height)*.5),m=!1,zf(a,v)||c(Bi(v))}}),p.unshift(h),ve.jsx(rx.Provider,{value:{sendmessage(g,v){Yt.emit(g,"gadget",v,l)},sendclose(){_9("gadget",l)},didclose(){c(void 0)}},children:ve.jsxs("group",{position:[s*.5,o*.5,-512],children:[p.map(g=>ve.jsx("group",{position:[g.x*as,g.y*Hi,0],children:ve.jsx(HI,{rect:g})},g.name)),a&&ve.jsxs(Co.Fragment,{children:[ve.jsx("group",{position:[0,0,800],children:ve.jsx(Ice,{width:r,height:i,alpha:.14})}),ve.jsx("group",{position:[a.x*as,a.y*Hi,900],children:ve.jsx(HI,{rect:a,shouldclose:m})})]},a.name)]})})}const rme=250,ime=249,Kp=wn.BLUE,sme=wn.WHITE,Wl=wn.DKBLUE,ome=wn.DKGRAY,nB=wn.BLACK,Rv=1,zS=as*Rv,VS=Hi*Rv,rB=Ne.createContext({sendmessage(){}});function Lf(t,e,n,r,i){const s=qo(i);i.iseven=i.y%2===0,i.active.bg=e&&!t?nB:Wl,i.active.leftedge=s.left,i.active.rightedge=s.right,i.active.topedge=s.top,i.active.bottomedge=s.bottom,i.x=i.active.leftedge+n,i.y=i.active.topedge+r}function xf(t,e,n,r,i,s,o,a){const c=qo(i);i.iseven=i.y%2===0,i.active.bg=Wl,i.active.leftedge=c.left+s,i.active.rightedge=c.right-s,i.active.topedge=c.top+o,i.active.bottomedge=c.bottom-a,i.x=i.active.leftedge+n,i.y=i.active.topedge+r}function ame(t){let e=0;return t.split(/\r?\n/).map(r=>{const i=e,s=`${r} -`;return e+=s.length,{start:i,code:s,end:i+r.length}})}function cme(t){return t.reduce((e,n)=>{const r=n.code.length;return r>e?r:e},0)}function lme(t,e){for(let n=0;n{const e="nativeEvent"in t?t.nativeEvent:t;return{deltaX:e.deltaX||0,deltaY:e.deltaY||0,deltaZ:e.deltaZ||0,timeStamp:e.timeStamp}},dme=t=>[t.deltaX,t.deltaY,t.deltaZ],K0=t=>{const e=dme(t).map(Math.abs);return Math.max(...e)};var xl;(function(t){t.ALL_OTHER_CHECKS_FAILED="ALL_OTHER_CHECKS_FAILED",t.NO_PREVIOUS_EVENT_TO_COMPARE="NO_PREVIOUS_EVENT_TO_COMPARE",t.PAST_TIMESTAMP_EVENT="PAST_TIMESTAMP_EVENT",t.ENOUGH_TIME_PASSED="ENOUGH_TIME_PASSED",t.NON_DECREASING_DELTAS_OF_KNOWN_HUMAN="NON_DECREASING_DELTAS_OF_KNOWN_HUMAN",t.DELTA_MODULE_HAS_BEEN_INCREASING="DELTA_MODULE_HAS_BEEN_INCREASING"})(xl||(xl={}));class pme{constructor({sensitivity:e=2,delay:n=100,increasingDeltasThreshold:r=3}={}){vt(this,"sensitivity");vt(this,"delay");vt(this,"increasingDeltasThreshold");vt(this,"previousEvents");this.sensitivity=Math.max(1,e),this.delay=Math.max(1,n),this.increasingDeltasThreshold=Math.max(2,r),this.previousEvents=[]}check(e){var s;if(!(("nativeEvent"in e?e.nativeEvent:e)instanceof Event))throw new Error(`"${e}" is not a valid event`);const r=fme(e);if(K0(r)(((s=this.previousEvents.at(-1))==null?void 0:s.timeStamp)||0)&&this.previousEvents.push(r),i}isHuman(e){const n=this.previousEvents.at(-1);if(!n)return{isHuman:!0,reason:xl.NO_PREVIOUS_EVENT_TO_COMPARE};if(e.timeStampn.timeStamp+this.delay)return{isHuman:!0,reason:xl.ENOUGH_TIME_PASSED};const s=K0(e),o=K0(n);if(s>=o){if(this.previousEvents.length===1)return{isHuman:!0,reason:xl.NON_DECREASING_DELTAS_OF_KNOWN_HUMAN};if(this.increasingDeltasThreshold<=2||this.previousEvents.length>=this.increasingDeltasThreshold&&this.previousEvents.slice(-this.increasingDeltasThreshold).map(K0).every((u,h,p)=>h===0||u>p[h-1]))return{isHuman:!0,reason:xl.DELTA_MODULE_HAS_BEEN_INCREASING}}return{isHuman:!1,reason:xl.ALL_OTHER_CHECKS_FAILED}}}function GI(){}const mme=Co.forwardRef(function({args:e,children:n,...r},i){const s=Co.useRef(null);return Co.useImperativeHandle(i,()=>s.current),ve.jsxs("mesh",{ref:s,...r,children:[ve.jsx("planeGeometry",{attach:"geometry",args:e}),n]})}),gme=Co.forwardRef(function({blocking:e=!1,cursor:n="default",x:r=0,y:i=0,width:s=1,height:o=1,opacity:a=1,visible:c=!0,...l},u){const h=s*.5,p=o*.5,m=[(r+h)*as,(i+p)*Hi,0],g=Dy();return ve.jsx(mme,{ref:u,args:[s*as,o*Hi],userData:{blocking:e,cursor:n,clippingPlanes:g},onClick:e?GI:void 0,onPointerMove:e?GI:void 0,position:m,...l,children:ve.jsx("meshBasicMaterial",{color:"white",opacity:a,visible:c,transparent:a!==1,clippingPlanes:g})})}),_me=new pme({sensitivity:nd?7:2}),WI=4,vme=.75;function yme(t){const e=Cn(t,-WI,WI);return Math.round(e*vme)}function sB({debug:t=!1,disabled:e=!1,blocking:n=!0,cursor:r="pointer",x:i=0,y:s=0,width:o=30,height:a=10,children:c,onScroll:l,...u}){return ve.jsxs("group",{...u,children:[ve.jsx(gme,{blocking:n,cursor:r,visible:t,x:i,y:s,width:o,height:a,onWheel:h=>{e||!_me.check(h)||l==null||l(yme(h.deltaY))}}),c]})}function xme({tapeycursor:t,logrowtotalheight:e}){const n=$a(),r=ja(),i=br(),s=XT(),o=qo(r),a=i.buffer[i.bufferindex];let c=i.xcursor,l=i.xcursor,u=!1;Z(i.xselect)&&Z(i.yselect)&&(u=!0,c=Math.min(i.xcursor,i.xselect),l=Math.max(i.xcursor,i.xselect),i.xcursor!==i.xselect&&--l);const h=l-c+1,p=i.ycursor===0,m=u?a.substring(c,l+1):a;function g(O,C,I){i.bufferindex>0&&br.setState({bufferindex:0}),i.buffer[0]=ume(a,O,C,I),br.setState({buffer:i.buffer,xselect:void 0,xcursor:O+(I??"").length})}function v(O){const C=i.buffer.length-1,I=Cn(O,0,C);br.setState({bufferindex:I,xcursor:i.buffer[I].length,ycursor:0,xselect:void 0,yselect:void 0})}function y(O){O?Z(i.xselect)||br.setState({xselect:i.xcursor,yselect:i.ycursor}):br.setState({xselect:void 0,yselect:void 0})}function _(){Z(i.xselect)&&(br.setState({xcursor:c,xselect:void 0,yselect:void 0}),g(c,h))}function S(){br.setState({xcursor:a.length,ycursor:0,xselect:void 0,yselect:void 0})}Lf(!1,!1,0,0,r);const E="main:0.20.35 - if lost try #help";r.x=o.right-E.length,Hn(`$dkcyan${E}`,r,!0);const b="$196",R="$205".repeat(o.width-6);Lf(!1,!1,0,o.height-2,r),Hn(` ${b}${R}${b} `,r,!0);const M=a.padEnd(o.width," ");if(Lf(!1,!1,0,o.height-1,r),XF(M,r,!0),Z(i.xselect)&&Z(i.yselect)&&i.xcursor!==i.xselect){const O=Math.min(i.xcursor,i.xselect),C=Math.min(i.ycursor,i.yselect),I=Math.max(i.xcursor,i.xselect)-1,U=Math.max(i.ycursor,i.yselect);for(let L=C;L<=U;++L){const P=O+(o.bottom-L)*o.width,T=I+(o.bottom-L)*o.width;nx(P,T,15,8,r)}}if(n){const O=o.left+i.xcursor,C=o.top+t;tx(O+C*r.width,"Ý",r)}return Ne.useEffect(()=>{let O=i.scroll;t<4&&O++,t>o.bottom-4&&O--,br.setState({scroll:Math.round(Cn(O,0,e))})},[i.scroll,t,e,o.bottom]),r.changed(),ve.jsxs(ve.Fragment,{children:[ve.jsx(sB,{blocking:!0,x:o.left,y:o.top,width:o.width,height:o.height,onScroll:O=>{y(!1),br.setState({ycursor:Cn(Math.round(i.ycursor-O),0,e)})}}),ve.jsx(gs,{keydown:O=>{const{key:C}=O,I=$t(C),U=Vy(O);switch(I){case"arrowleft":y(U.shift),U.ctrl?br.setState({xcursor:0}):br.setState({xcursor:Cn(i.xcursor-(U.alt?10:1),0,o.right)});break;case"arrowright":y(U.shift),U.ctrl?br.setState({xcursor:p?a.length:o.right}):br.setState({xcursor:Cn(i.xcursor+(U.alt?10:1),0,o.right)});break;case"arrowup":U.ctrl?v(i.bufferindex+1):(y(U.shift),br.setState({ycursor:Cn(Math.round(i.ycursor+(U.alt?10:1)),0,e)}));break;case"arrowdown":U.ctrl?v(i.bufferindex-1):(y(U.shift),br.setState({ycursor:Cn(Math.round(i.ycursor-(U.alt?10:1)),0,e)}));break;case"enter":{const L=u?m:a;L.length&&(p?(br.setState({xcursor:0,bufferindex:0,xselect:void 0,yselect:void 0,buffer:["",L,...i.buffer.slice(1).filter(P=>P!==L)]}),Hv("tape",L,s)):S());break}case"esc":case"escape":Lb("tape");break;case"tab":pL("tape",!U.shift);break;case"delete":p?u?_():a.length>0&&g(i.xcursor,1):S();break;case"backspace":p?u?_():i.xcursor>0&&g(i.xcursor-1,1):S();break;default:if(U.ctrl)switch(I){case"a":br.setState({xselect:0,yselect:0,xcursor:a.length,ycursor:0});break;case"c":p&&Z(navigator.clipboard)?navigator.clipboard.writeText(m).catch(L=>console.error(L)):S();break;case"v":p&&Z(navigator.clipboard)?navigator.clipboard.readText().then(L=>{const P=L.replaceAll("\r","");u?g(c,h,P):g(i.xcursor,0,P)}).catch(L=>console.error(L)):S();break;case"x":p&&Z(navigator.clipboard)?navigator.clipboard.writeText(m).then(()=>_()).catch(L=>console.error(L)):S();break}else U.alt||C.length===1&&(p&&i.xcursor<=a.length?u?(g(c,h,C),br.setState({xselect:void 0})):g(i.xcursor,0,C):S());break}}})]})}function Sme({blink:t,active:e,prefix:n,label:r,words:i,y:s}){const o=ja(),a=Ne.useCallback(()=>{if(Z(navigator.clipboard)){const[,...l]=i,u=l.join(" ");navigator.clipboard.writeText(u).then(()=>gn("copyit","copied!")).catch(h=>console.error(h))}},[i]),c=Jl(!!e);return Lf(!!t,!!e,0,s,o),Hn(`${n} $purple$16 $yellowCOPYIT ${c}${r}`,o,!0),o.changed(),e&&ve.jsx(gs,{OK_BUTTON:a})}function Eme({blink:t,active:e,prefix:n,label:r,words:i,y:s}){const o=ja(),a=Ne.useContext(rB),c=Ne.useCallback(()=>{const[u,h]=i;a.sendmessage(u,h)},[i,a]),l=Jl(!!e);return Lf(!!t,!!e,0,s,o),Hn(`${n} $purple$16 ${l}${r}`,o,!0),o.changed(),e&&ve.jsx(gs,{OK_BUTTON:c})}function oB({blink:t,active:e,text:n,y:r}){const i=ja(),s=qo(i),o=n.startsWith("!");if(Lf(!!t,!!e,0,r,i),i.active.bottomedge=s.bottom,Hn(o?"":n,i,!0),o){const[a,...c]=n.slice(1).split("!"),l=`${c.join("!")}`;let u="PRESS ME";const h=[];Qy(l,!0).tokens.forEach(y=>{switch(y.tokenType){case sM:u=y.image.slice(1);break;default:h.push(y.image);break}});const[m,...g]=h,v={blink:t,active:e,prefix:a,label:u,words:g,y:r};switch($t(m)){case"hk":case"hotkey":return null;case"rn":case"range":return null;case"sl":case"select":return null;case"nm":case"number":return null;case"tx":case"text":return null;case"copyit":return ve.jsx(Sme,{...v,words:h});default:case"hyperlink":return ve.jsx(Eme,{...v,words:h})}}return null}function wme(t){const e=$a();return ve.jsx(oB,{active:!0,blink:e,...t})}function HS(){const t=XT(),[e,n]=ts(Yl(p=>[p.terminal.logs,p.editor.open])),r=ja(),i=br(),s=qo(r),o=e.map(p=>{const[,m,g,...v]=p;let y="$white";switch(m){case"debug":y="$yellow";break;case"error":y="$red";break}const _=v.map(b=>`${b}`).join(" "),S=_.startsWith("!"),E=`$blue[${y}${g}$blue]`;return`${S?"!":""}${E} ${_}`}),a=o.map(p=>{if(p.startsWith("!"))return 1;const m=aM(p,s.width,s.height);return(m==null?void 0:m.y)??1});let c=0,l=s.bottom-1;const u=a.map(p=>(l-=p,c+=p,l));++c;const h=s.bottom-i.ycursor+i.scroll;return ve.jsxs(ve.Fragment,{children:[ve.jsx(fM,{context:r}),ve.jsxs(rB.Provider,{value:{sendmessage(p,m){const[g,v]=hme(p);if(g==="self"){const y=`#${v} ${m??""}`;Hv("tape",y,t)}else Yt.emit(`${g}:${v}`,"gadget",m,t)}},children:[o.map((p,m)=>{const g=u[m]+i.scroll,v=a[m],y=g+v;return y<0||g>s.bottom-1?null:!n&&h>=g&&h[m.editor.type,m.editor.title])),o=$a(),a="$205".repeat(e.width-4);xf(!1,!1,0,1,t,0,0,0),Hn(`$179$${o?"7":"232"}$200${a}$181`,t,!0);const l=` ${`[${i}] `}${s} `,u=aM(l,e.width,e.height),h=(u==null?void 0:u.measuredwidth)??1,p=Math.round(e.width*.5)-Math.round(h*.5);return xf(!1,!1,p,0,t,0,0,0),Hn(l,t,!0),t.changed(),null}function Tme({xcursor:t,ycursor:e,xoffset:n,yoffset:r,rows:i,codepage:s}){var P,T;const o=$a(),a=ja(),c=Ne.useRef(),l=hr(),u=qo(a),h=ts(H=>H.editor.player),p=iB(s),m=Z(p)?p.toJSON():"",g=i.length-1,v=t+1-n,y=e+2-r;if(Z(s)){const H=((P=c.current)==null?void 0:P.x)!==v||((T=c.current)==null?void 0:T.y)!==y;if(o||H){const V=u.left+v,B=u.top+y;B>u.top+1&&Bu.left&&V0&&(p==null||p.delete(H,V)),Z(B)&&(p==null||p.insert(H,B)),hr.setState({cursor:H+(B??"").length,select:void 0})}function I(){Z(l.select)&&(hr.setState({cursor:E}),C(E,R))}function U(){hr.setState({cursor:_,select:void 0})}const L=Ne.useCallback(function(V){const B=Math.round(e+V);if(B<0)hr.setState({cursor:0});else if(B>g)hr.setState({cursor:_});else{const z=i[B];hr.setState({cursor:z.start+Math.min(t,z.code.length-1)})}},[_,i,g,t,e]);return a.changed(),ve.jsxs(ve.Fragment,{children:[ve.jsx(sB,{blocking:!0,x:u.left,y:u.top,width:u.width,height:u.height,onScroll:H=>L(H*.75)}),ve.jsx(gs,{keydown:H=>{if(!Z(p))return;const{key:V}=H,B=$t(V),z=Vy(H);switch(B){case"arrowleft":if(O(z.shift),z.ctrl)hr.setState({cursor:S.start});else{const W=l.cursor-(z.alt?10:1);hr.setState({cursor:Cn(W,0,_)})}break;case"arrowright":if(O(z.shift),z.ctrl)hr.setState({cursor:S.end});else{const W=l.cursor+(z.alt?10:1);hr.setState({cursor:Cn(W,0,_)})}break;case"arrowup":O(z.shift),z.ctrl?hr.setState({cursor:0}):L(z.alt?-10:-1);break;case"arrowdown":O(z.shift),z.ctrl?hr.setState({cursor:_}):L(z.alt?10:1);break;case"enter":Z(p)&&(p.insert(l.cursor,` -`),hr.setState({cursor:l.cursor+1}));break;case"esc":case"escape":z.shift||z.alt||z.ctrl?Lb("tape"):C9("editor");break;case"tab":pL("editor",!z.shift);break;case"delete":N?I():C(l.cursor,1);break;case"backspace":N?I():m.length>0&&C(Math.max(l.cursor-1,0),1);break;default:if(z.ctrl)switch(B){case"a":hr.setState({cursor:_,select:0});break;case"c":Z(navigator.clipboard)?navigator.clipboard.writeText(M).catch(W=>Vn("tape","clipboard",W)):U();break;case"v":Z(navigator.clipboard)?navigator.clipboard.readText().then(W=>{const K=W.replaceAll("\r","");N?C(E,R,K):C(l.cursor,0,K)}).catch(W=>Vn("tape","clipboard",W)):U();break;case"x":Z(navigator.clipboard)?navigator.clipboard.writeText(M).then(()=>I()).catch(W=>Vn("tape","clipboard",W)):U();break;case"p":Hv("editor",M,h),gn("editor",`running: ${M}`);break}else if(!z.alt){if(V.length===1)if(N)C(E,R,V);else{const W=l.cursor+V.length;p.insert(l.cursor,V),hr.setState({cursor:W})}}break}}})]})}function Ame({ycursor:t,xoffset:e,yoffset:n,rows:r,codepage:i}){const s=$a(),o=ja(),a=hr(),c=qo(o);if(!Z(i)){const m=(s?"|":"-").repeat(3);return xf(!1,!1,0,0,o,1,2,1),Hn(` ${m} LOADING ${m}`,o,!0),null}let l=a.cursor,u=a.cursor,h=!1;Z(a.select)&&(h=!0,l=Math.min(a.cursor,a.select),u=Math.max(a.cursor,a.select),a.cursor!==a.select&&--u);const p=c.left+1;xf(!1,!1,-e,-n,o,1,2,1);for(let m=0;m=l){const _=Math.max(g.start,l)-g.start-e,S=Math.min(g.end,u)-g.start-e,E=c.width-3,b=1+o.y*o.width,N=Math.max(0,_),R=Math.min(E,S);N<=E&&R>=p&&nx(b+N,b+R,sme,ome,o)}if(++o.y,o.y>=c.bottom)break}return o.disablewrap=!1,null}function GS(){const[t]=ts(Yl(v=>[v.editor])),e=ja(),n=hr(),r=DU(mL(t.book,t.page)),i=qo(e);Ne.useEffect(()=>(P9("editor",t.book,t.page,t.player),()=>{D9("editor",t.book,t.page,t.player)}),[t.book,t.page,t.player]);const s=iB(r),o=Z(s)?s.toJSON():"",a=ame(o),c=lme(n.cursor,a),l=n.cursor-a[c].start,u=cme(a),h={rows:a,xcursor:l,ycursor:c,codepage:r,xoffset:n.xscroll,yoffset:n.yscroll},p=32,m=(Math.round(u/p)+1)*p,g=a.length;return Ne.useEffect(()=>{let v=n.xscroll;const y=l-v,_=i.width-3;let S=Math.round(Cn(Math.abs(y)*.5,1,p));S<8&&(S=1),y>_-8&&(v+=S),y<8&&(v-=S);let E=n.yscroll;const b=c-E,N=i.height-4,R=Math.round(N*.5);let M=Math.round(Cn(Math.abs(b)*.25,1,R));M<8&&(M=1),b>N-4&&(E+=M),b<4&&(E-=M),setTimeout(()=>hr.setState({xscroll:Math.round(Cn(v,0,m)),yscroll:Math.round(Cn(E,0,g))}),16)},[l,m,n.xscroll,c,g,n.yscroll,i.width,i.height]),ve.jsxs(ve.Fragment,{children:[ve.jsx(fM,{context:e}),ve.jsx(bme,{}),ve.jsx(Ame,{...h}),ve.jsx(Tme,{...h})]})}function jI(t,e,n,r,i){return{...i,x:t,y:e,reset:{...i.reset,topedge:e,leftedge:t,rightedge:n,bottomedge:r},active:{...i.reset,topedge:e,leftedge:t,rightedge:n,bottomedge:r}}}function Mme({context:t}){const[e,n]=ts(Yl(l=>[l.layout,l.editor.open])),r=t.width-1,i=t.height-1,s=qo(t),o=Math.floor(s.height*.5),a=Ne.useMemo(()=>jI(0,0,r,o-1,t),[o,r,t]),c=Ne.useMemo(()=>jI(0,o,r,i,t),[o,r,i,t]);if(n){let l,u;switch(e){case Pi.SPLIT_Y:case Pi.SPLIT_Y_ALT:l=a,u=c;break}if(Z(l)&&Z(u))switch(e){case Pi.SPLIT_Y:return ve.jsxs(ve.Fragment,{children:[ve.jsx(Iu.Provider,{value:l,children:ve.jsx(HS,{})}),ve.jsx(Iu.Provider,{value:u,children:ve.jsx(GS,{})})]});case Pi.SPLIT_Y_ALT:return ve.jsxs(ve.Fragment,{children:[ve.jsx(Iu.Provider,{value:l,children:ve.jsx(GS,{})}),ve.jsx(Iu.Provider,{value:u,children:ve.jsx(HS,{})})]})}}return ve.jsx(ve.Fragment,{children:ve.jsx(Iu.Provider,{value:t,children:n?ve.jsx(GS,{}):ve.jsx(HS,{})})})}function Cme(){const t=va(_=>_.viewport),{width:e,height:n}=t.getCurrentViewport(),r=Math.floor(e/as),i=Math.floor(n/Hi),s=Math.floor(e/zS),o=Math.floor(n/VS),a=e-s*zS,c=n-o*VS;let l=0;const u=0,h=s;let p=o;const[m,g]=ts(Yl(_=>[_.layout,_.terminal.open]));switch(m){case Pi.TOP:p=Math.round(o*.5);break;case Pi.BOTTOM:p=Math.round(o*.5),l=o-p;break;default:case Pi.FULL:break}const v=lM(h,p,0,Kp,Wl),y={...jm(h,p,Kp,Wl),...v.getState()};return h<1||p<1?null:ve.jsx(uM,{store:v,children:ve.jsxs("group",{position:[0,0,900],children:[g&&ve.jsx(Oce,{width:r,height:i,top:l,left:u,right:u+h-1,bottom:l+p-1}),ve.jsx("group",{position:[a*.5+u*zS,c+l*VS,1],scale:[Rv,Rv,1],children:g?ve.jsxs(Im,{blockhotkeys:!0,children:[ve.jsx(fM,{context:y}),ve.jsx(Mme,{context:y}),ve.jsx(hM,{width:h,height:p})]}):ve.jsx(xp,{hotkey:"Shift+?",children:()=>A9("tape")})})]})})}Cb({OrthographicCamera:Uv});ece();function Rme(){const t=va(p=>p.viewport),e=Ne.useRef(null),{width:n,height:r}=t.getCurrentViewport(),i=KT(Yre);i.minFilter=vr,i.magFilter=vr;const[s]=Ne.useState(()=>new Ure);Ne.useEffect(()=>{if(!Bre)return;document.body.appendChild(s.dom),s.showPanel(0),s.dom.style.cssText="position:fixed;bottom:0;left:0;";const p=pW(()=>s.begin()),m=mW(()=>s.end());return()=>{document.body.removeChild(s.dom),p(),m()}},[s]);const[o,a]=Ne.useState();Ne.useEffect(()=>{Pre({benchmarksURL:"/benchmarks-min"}).then(a).catch(p=>Vn("gpu","detect",p))},[]);const c=!Vre&&o&&o.tier>2&&!o.isMobile,l=va(({set:p})=>p),u=va(({size:p})=>p),h=va(({camera:p})=>p);return Ne.useLayoutEffect(()=>{var p;(p=e.current)==null||p.updateProjectionMatrix()}),Ne.useLayoutEffect(()=>{const p=h;return l(()=>({camera:e.current})),()=>l(()=>({camera:p}))},[l,h,e]),ve.jsxs(ve.Fragment,{children:[ve.jsx("orthographicCamera",{ref:e,left:u.width/-2,right:u.width/2,top:u.height/2,bottom:u.height/-2,near:1,far:2e3,position:[0,0,1e3]}),ve.jsx("group",{"scale-x":-1,"rotation-z":Math.PI,children:ve.jsx("group",{position:[n*-.5,r*-.5,0],children:ve.jsxs(Im,{children:[ve.jsx(nme,{}),ve.jsx(Cme,{})]})})}),c&&ve.jsx(Cre,{children:ve.jsx(Kre,{splat:i,viewheight:r})})]})}Cb({BufferGeometry:Bo,Group:ip,Mesh:Ao,MeshBasicMaterial:Eb,OrthographicCamera:Uv,PlaneGeometry:em,Points:DG});document.addEventListener("keydown",()=>{_d()});window.addEventListener("touchstart",()=>{_d()});window.addEventListener("click",()=>{_d()});window.addEventListener("dragover",t=>{t.preventDefault()});window.addEventListener("contextmenu",t=>{_d(),t.preventDefault()});window.addEventListener("paste",t=>{var n;if(!((n=t.clipboardData)!=null&&n.files.length))return;_d(),t.preventDefault(),[...t.clipboardData.files].forEach(r=>VE("loadfile",r,rv()))});window.addEventListener("drop",t=>{var e,n;_d(),t.preventDefault(),(e=t.dataTransfer)!=null&&e.items?[...t.dataTransfer.items].forEach(i=>{if(i.kind==="file"){const s=i.getAsFile();Z(s)&&VE("loadfile",s,rv())}}):[...((n=t.dataTransfer)==null?void 0:n.files)??[]].forEach(i=>VE("loadfile",i,rv()))});function Nme(){return ve.jsx(Rme,{})}const $I=new xe,qI=new xe,XI=t=>({...wW(t),filter:e=>{const n=e.filter(o=>!(!o.object.visible||(o.object.userData.clippingPlanes??[]).some(c=>(c.projectPoint(o.point,$I),qI.subVectors(o.point,$I).normalize().round(),c.normal.equals(qI)===!1)))),r=n.findIndex(o=>o.object.userData.blocking),i=r===-1?n:n.slice(0,r+1);let s="default";return i.some(o=>o.object.userData.cursor?(s=o.object.userData.cursor,!0):!1),document.querySelectorAll("html, body").forEach(o=>{o.style.cursor=s}),i}}),KI=document.querySelector("canvas");if(Z(KI)){const t=xW(KI),e={dpr:1,flat:!0,linear:!0,shadows:!1,gl:{alpha:!1,stencil:!1,antialias:!1,preserveDrawingBuffer:!0}};t.configure({...e,events:XI,onCreated({gl:r}){r.localClippingEnabled=!0}});const n=TW((r,i)=>{t.configure({...e,events:XI,size:{width:r,height:i,top:0,left:0},onCreated({gl:s}){s.localClippingEnabled=!0}})},256);window.addEventListener("resize",()=>{n(c2(window.innerWidth),c2(window.innerHeight))}),t.render(ve.jsx(Nme,{}))}});export default kme(); diff --git a/assets/instance-BaZ499FU.js b/assets/instance-BaZ499FU.js deleted file mode 100644 index 504e541a..00000000 --- a/assets/instance-BaZ499FU.js +++ /dev/null @@ -1,208 +0,0 @@ -var eU=Object.defineProperty;var tU=(cr,Pe,Bt)=>Pe in cr?eU(cr,Pe,{enumerable:!0,configurable:!0,writable:!0,value:Bt}):cr[Pe]=Bt;var ye=(cr,Pe,Bt)=>tU(cr,typeof Pe!="symbol"?Pe+"":Pe,Bt);(function(){"use strict";const cr=new Set,Pe={emit(e,t,n,r){Pe.invoke(yb(e,t,n,r))},invoke(e){cr.forEach(t=>t.handle(e))},connect(e){cr.add(e)},disconnect(e){cr.delete(e)}};var Bt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Pi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function tb(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}),n}var sh={};(function(e){var t=Bt&&Bt.__spreadArray||function(l,u,f){if(f||arguments.length===2)for(var d=0,h=u.length,p;df.length?u:f})}function i(l){return l.reduce(function(u,f){return u.lengthcrypto.getRandomValues(new Uint8Array(e)),sb=(e,t,n)=>{let r=(2<{let o="";for(;;){let a=n(i),c=i;for(;c--;)if(o+=e[a[c]&r]||"",o.length===s)return o}}},oh=(e,t=21)=>sb(e,t,ib),ob=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e));for(;e--;)t+=rb[n[e]&63];return t};var ah="abcdefghijklmnopqrstuvwxyz",ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ",lh="0123456789",ab="346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz",cb="6789BCDFGHJKLMNPQRTWbcdfghjkmnpqrtwz";const lb=lh,ub=ah,fb=ch;var hb=lb+ub+fb,zc={lowercase:ah,uppercase:ch,numbers:lh,nolookalikes:ab,nolookalikesSafe:cb,alphanumeric:hb};function ht(){return`sid_${ob(12).replaceAll("-",".")}`}const db=oh(zc.numbers,4),pb=oh(`${zc.numbers}${zc.lowercase}`,16);function mb(){return`pid_${db()}_${pb()}`}function uh(e){return(e==null?void 0:e.startsWith("pid_"))??!1}function gb(){return nb({capitalize:!1,adjectiveCount:1})}var be=(e=>(e[e.BLACK=0]="BLACK",e[e.DKBLUE=1]="DKBLUE",e[e.DKGREEN=2]="DKGREEN",e[e.DKCYAN=3]="DKCYAN",e[e.DKRED=4]="DKRED",e[e.DKPURPLE=5]="DKPURPLE",e[e.DKYELLOW=6]="DKYELLOW",e[e.LTGRAY=7]="LTGRAY",e[e.DKGRAY=8]="DKGRAY",e[e.BLUE=9]="BLUE",e[e.GREEN=10]="GREEN",e[e.CYAN=11]="CYAN",e[e.RED=12]="RED",e[e.PURPLE=13]="PURPLE",e[e.YELLOW=14]="YELLOW",e[e.WHITE=15]="WHITE",e[e.ONBLACK=16]="ONBLACK",e[e.ONDKBLUE=17]="ONDKBLUE",e[e.ONDKGREEN=18]="ONDKGREEN",e[e.ONDKCYAN=19]="ONDKCYAN",e[e.ONDKRED=20]="ONDKRED",e[e.ONDKPURPLE=21]="ONDKPURPLE",e[e.ONDKYELLOW=22]="ONDKYELLOW",e[e.ONLTGRAY=23]="ONLTGRAY",e[e.ONDKGRAY=24]="ONDKGRAY",e[e.ONBLUE=25]="ONBLUE",e[e.ONGREEN=26]="ONGREEN",e[e.ONCYAN=27]="ONCYAN",e[e.ONRED=28]="ONRED",e[e.ONPURPLE=29]="ONPURPLE",e[e.ONYELLOW=30]="ONYELLOW",e[e.ONWHITE=31]="ONWHITE",e[e.ONCLEAR=32]="ONCLEAR",e[e.ONSHADOW=33]="ONSHADOW",e[e.ONBORROW=34]="ONBORROW",e))(be||{}),Ye=(e=>(e[e.ISWALK=0]="ISWALK",e[e.ISSOLID=1]="ISSOLID",e[e.ISSWIM=2]="ISSWIM",e[e.ISBULLET=3]="ISBULLET",e))(Ye||{}),Uo=(e=>(e[e.ISTERRAIN=0]="ISTERRAIN",e[e.ISOBJECT=1]="ISOBJECT",e))(Uo||{}),ae=(e=>(e[e.IDLE=0]="IDLE",e[e.NORTH=1]="NORTH",e[e.SOUTH=2]="SOUTH",e[e.WEST=3]="WEST",e[e.EAST=4]="EAST",e[e.BY=5]="BY",e[e.AT=6]="AT",e[e.FLOW=7]="FLOW",e[e.SEEK=8]="SEEK",e[e.RNDNS=9]="RNDNS",e[e.RNDNE=10]="RNDNE",e[e.RND=11]="RND",e[e.CW=12]="CW",e[e.CCW=13]="CCW",e[e.OPP=14]="OPP",e[e.RNDP=15]="RNDP",e))(ae||{}),fe=(e=>(e[e.LOADER=0]="LOADER",e[e.BOARD=1]="BOARD",e[e.OBJECT=2]="OBJECT",e[e.TERRAIN=3]="TERRAIN",e[e.CHARSET=4]="CHARSET",e[e.PALETTE=5]="PALETTE",e[e.CONST=6]="CONST",e[e.RANGE=7]="RANGE",e[e.SELECT=8]="SELECT",e[e.NUMBER=9]="NUMBER",e[e.TEXT=10]="TEXT",e[e.LINK=11]="LINK",e[e.HOTKEY=12]="HOTKEY",e[e.SCROLL=13]="SCROLL",e[e.COPYIT=14]="COPYIT",e))(fe||{});function De(e){return e.toLowerCase().trim()}function yb(e,t,n,r){return{id:ht(),target:e,sender:t,data:n,player:r}}function fh(e){const[t,...n]=e.split(":");return{target:t,path:n.join(":")}}function Po(e,t,n){const r=ht(),i=De(e),s=t.map(De),o={id(){return r},name(){return e},topics(){return t},emit(a,c,l){Pe.emit(a,r,c,l)},reply(a,c,l,u){o.emit(`${a.sender}:${c}`,l,u)},handle(a){const{target:c,path:l}=fh(a.target),u=De(c);s.findIndex(f=>f==="all"||f===u)!==-1&&n(a),(r===c||u==="all"||i===u)&&n({...a,target:l})}};return Pe.connect(o),o}function _b(e){const t=new Set;function n(r){t.has(r.id)||(t.add(r.id),Pe.invoke(r))}return Po("forward",["all"],r=>{t.has(r.id)||(t.add(r.id),e(r))}),n}function Do(e,t){return new Array(e).fill(t)}function hh(e,t,n,r,i=0){const s=n*r;return{id:`tiles:${e}:${t}`,type:1,width:n,height:r,char:Do(s,0),color:Do(s,0),bg:Do(s,i)}}function bb(e,t,n,r=1,i=15){return{id:`sprites:${e}:${t}:${n}`,x:0,y:0,char:r,color:i,bg:be.ONCLEAR}}function wb(e,t){return{id:`sprites:${e}:${t}`,type:2,sprites:[]}}function vb(e,t,n,r,i=0){const s=n*r;return{id:`dither:${e}:${t}`,type:3,width:n,height:r,alphas:Do(s,i)}}function Eb(e,t){return{id:`control:${e}:${t}`,type:5,focusx:0,focusy:0,focusid:e,viewscale:2}}var fn=(e=>(e[e.START=0]="START",e[e.LEFT=1]="LEFT",e[e.RIGHT=2]="RIGHT",e[e.TOP=3]="TOP",e[e.BOTTOM=4]="BOTTOM",e[e.SCROLL=5]="SCROLL",e))(fn||{});const kb={start:0,left:1,right:2,top:3,bottom:4,scroll:5},Sb={0:1,1:20,2:20,3:1,4:1,5:40};function dh(e,t){return`${e}:${t}`}const Ab=1,Tb=16,xb=256;var Ft=(e=>(e[e.NONE=0]="NONE",e[e.ALT=1]="ALT",e[e.CTRL=2]="CTRL",e[e.SHIFT=3]="SHIFT",e[e.MOVE_UP=4]="MOVE_UP",e[e.MOVE_DOWN=5]="MOVE_DOWN",e[e.MOVE_LEFT=6]="MOVE_LEFT",e[e.MOVE_RIGHT=7]="MOVE_RIGHT",e[e.OK_BUTTON=8]="OK_BUTTON",e[e.CANCEL_BUTTON=9]="CANCEL_BUTTON",e[e.MENU_BUTTON=10]="MENU_BUTTON",e[e.SHOOT_UP=11]="SHOOT_UP",e[e.SHOOT_DOWN=12]="SHOOT_DOWN",e[e.SHOOT_LEFT=13]="SHOOT_LEFT",e[e.SHOOT_RIGHT=14]="SHOOT_RIGHT",e))(Ft||{});function et(e,t,n,r){const i=r??"";return Pe.emit(`error:${t}`,e,n,i),Fb(e,n,i)}function Rb(e,t,n){Pe.emit("gadgetclient:reset",e,t,n)}function Ib(e,t,n){Pe.emit("gadgetclient:patch",e,t,n)}function Ob(e,t){Pe.emit("gadgetserver:clearplayer",e,void 0,t)}function Nb(e,t,n){Pe.emit("register:flush",e,[t,n])}function Cb(e,t){Pe.emit("register:dev",e,void 0,t)}function Lb(e,t){Pe.emit("register:share",e,void 0,t)}function Mb(e){Pe.emit("register:refresh",e)}function Ub(e){Pe.emit("register:nuke",e)}function Pb(e,t,n){Pe.emit("synth:tts",e,[t,n])}function Db(e,t,n){Pe.emit("synth:play",e,[t,n])}function Wc(e,t,n,r){Pe.emit("synth:voice",e,[t,n,r])}function Bb(e,t,n,r,i){Pe.emit("synth:voicefx",e,[t,n,r,i])}function Nt(e,...t){return Pe.emit("tape:info",e,t),!0}function ph(e,...t){return Pe.emit("tape:debug",e,t),!0}function Fb(e,...t){return Pe.emit("tape:error",e,t),!1}function $b(e,t,n,r,i,s){Pe.emit("tape:editor:open",e,[t,n,r,i],s)}function jb(e,t){Pe.emit("vm:endgame",e,void 0,t)}function mh(e,t){return`${e}${t}`}function Dr(e,t=""){Pe.emit("vm:flush",e,t)}function Gc(e,t){function n(r){console.error(r),et(e,"crash",r.message)}t().catch(n)}/*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2017-2022 Joachim Wester - * MIT licensed - */var zb=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),Wb=Object.prototype.hasOwnProperty;function Hc(e,t){return Wb.call(e,t)}function Vc(e){if(Array.isArray(e)){for(var t=new Array(e.length),n=0;n=48&&r<=57){t++;continue}return!1}return!0}function ri(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function gh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function qc(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(l[h]===void 0?d=c.slice(0,u).join("/"):u==f-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),u++,Array.isArray(l)){if(h==="-")h=l.length;else{if(n&&!Kc(h))throw new it("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,t,e);Kc(h)&&(h=~~h)}if(u>=f){if(n&&t.op==="add"&&h>l.length)throw new it("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);var o=Hb[t.op].call(t,l,h,e);if(o.test===!1)throw new it("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return o}}else if(u>=f){var o=Di[t.op].call(t,l,h,e);if(o.test===!1)throw new it("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return o}if(l=l[h],n&&u0)throw new it('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new it("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new it("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&qc(e.value))throw new it("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n){if(e.op=="add"){var i=e.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new it("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==r)throw new it("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if(e.op==="move"||e.op==="copy"){var o={op:"_get",path:e.from,value:void 0},a=bh([o],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new it("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new it("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function bh(e,t,n){try{if(!Array.isArray(e))throw new it("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Jc(qt(t),qt(e),n||!0);else{n=n||Fo;for(var r=0;r0&&(e.patches=[],e.callback&&e.callback(r)),r}function Yc(e,t,n,r,i){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=Vc(t),o=Vc(e),a=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(Hc(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var f=t[l];typeof u=="object"&&u!=null&&typeof f=="object"&&f!=null&&Array.isArray(u)===Array.isArray(f)?Yc(u,f,n,r+"/"+ri(l),i):u!==f&&(i&&n.push({op:"test",path:r+"/"+ri(l),value:qt(u)}),n.push({op:"replace",path:r+"/"+ri(l),value:qt(f)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:"test",path:r+"/"+ri(l),value:qt(u)}),n.push({op:"remove",path:r+"/"+ri(l)}),a=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:t}))}if(!(!a&&s.length==o.length))for(var c=0;c-1&&(u=u.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var f=u.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),d=f.match(/ (\(.+\)$)/);f=d?f.replace(d[0],""):f;var h=this.extractLocation(d?d[1]:f),p=d&&f||void 0,m=["eval",""].indexOf(h[0])>-1?void 0:h[0];return new r({functionName:p,fileName:m,lineNumber:h[1],columnNumber:h[2],source:u})},this)},parseFFOrSafari:function(c){var l=c.stack.split(` -`).filter(function(u){return!u.match(o)},this);return l.map(function(u){if(u.indexOf(" > eval")>-1&&(u=u.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),u.indexOf("@")===-1&&u.indexOf(":")===-1)return new r({functionName:u});var f=/((.*".+"[^@]*)?[^@]*)(?:@)/,d=u.match(f),h=d&&d[1]?d[1]:void 0,p=this.extractLocation(u.replace(f,""));return new r({functionName:h,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:u})},this)},parseOpera:function(c){return!c.stacktrace||c.message.indexOf(` -`)>-1&&c.message.split(` -`).length>c.stacktrace.split(` -`).length?this.parseOpera9(c):c.stack?this.parseOpera11(c):this.parseOpera10(c)},parseOpera9:function(c){for(var l=/Line (\d+).*script (?:in )?(\S+)/i,u=c.message.split(` -`),f=[],d=2,h=u.length;d/,"$2").replace(/\([^)]*\)/g,"")||void 0,m;h.match(/\(([^)]*)\)/)&&(m=h.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var b=m===void 0||m==="[arguments not available]"?void 0:m.split(",");return new r({functionName:p,args:b,fileName:d[0],lineNumber:d[1],columnNumber:d[2],source:u})},this)}}})})(vh);var fw=vh.exports,hw=Pi(fw);function lr(e){const t={},n={get(){return[!1,void 0]},set(){return[!1,void 0]},tick(){},everytick(){},...e,getcommand(r){return t[r]},command(r,i){return t[r]=i,n}};return n}var kh={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(Bt,function(){return n.importState=function(i){var s=new n;return s.importState(i),s},n;function n(){return function(i){var s=0,o=0,a=0,c=1;i.length==0&&(i=[+new Date]);var l=r();s=l(" "),o=l(" "),a=l(" ");for(var u=0;u>>0,c-=i,c*=i,i=c>>>0,c-=i,i+=c*4294967296}return(i>>>0)*23283064365386963e-26};return s.version="Mash 0.9",s}})})(kh);var dw=kh.exports,pw=Pi(dw);function si(e,t,n){return Math.max(t,Math.min(n,e))}const mw=pw("089fad0j9awfem09wavefc09uwaef");function gw(){return mw()}function bs(e,t){const n=Math.min(e,t),i=Math.max(e,t)-n+1;return n+Math.floor(gw()*i)}function el(e,t,n){typeof e!="number"&&(e=0,t=0,n=1),typeof t!="number"&&(t=e,e=0,n=1),typeof n!="number"&&(n=1);const r=[],i=Math.min(e,t),s=Math.max(e,t);for(let o=i;o<=s;o+=n)r.push(o);return r}function yw(e){return e[bs(0,e.length-1)]}function ur(...e){return yw(e.flat())}function _w(e){return[...new Set(e)].filter(E)}function bw(...e){const t=e.flat().filter(E);return t.reduce((n,r)=>n+r,0)/t.length}function fr(e){return E(e)&&E(e.x)&&E(e.y)}function St(e,t){switch(t){case ae.NORTH:--e.y;break;case ae.SOUTH:++e.y;break;case ae.WEST:--e.x;break;case ae.EAST:++e.x;break}return e}function Bi(e,t){const n=t.x-e.x,r=t.y-e.y;if(n<0)return ae.WEST;if(n>0)return ae.EAST;if(r<0)return ae.NORTH;if(r>0)return ae.SOUTH}const Sh={idle:"IDLE",up:"NORTH",down:"SOUTH",left:"WEST",right:"EAST",by:"BY",at:"AT",flow:"FLOW",seek:"SEEK",rndns:"RNDNS",rndne:"RNDNE",rnd:"RND",cw:"CW",ccw:"CCW",opp:"OPP",rndp:"RNDP",i:"IDLE",u:"NORTH",north:"NORTH",n:"NORTH",d:"SOUTH",south:"SOUTH",s:"SOUTH",l:"WEST",west:"WEST",w:"WEST",r:"EAST",east:"EAST",e:"EAST",edit:"EDIT"};function hr(e){return He(e)&&Ah(e[0])}function Ah(e){return E(ae[e])&&Ie(e)}function ww(e){const t=ae[e];return E(t)?t:ae.IDLE}function Th(e){if(Ie(e))return Sh[De(e)]}function xh(e){if(hr(e))return e;if(Ah(e))return[e];const t=Th(e);if(E(t))return[t]}function Rh(e){const t=L.words[e],n=xh(t);if(hr(n))return[n,e+1];const[r,i]=Gt(e),s=xh(r);return hr(s)?[s,i]:[void 0,e]}function tl(e){const t=[];let[n,r]=Rh(e);for(;hr(n);){if(t.push(...n),(n[0]==="AT"||n[0]==="BY")&&n.length<2){const[o,a,c]=ne(L.words,r,[q.NUMBER,q.NUMBER]);t.push(o,a),r=c}const[i,s]=Rh(r);n=i,r=s}return t.length?[t,r]:[void 0,e]}function Fi(e){return He(e)&&typeof e[0]=="string"}function Ih(e){const t=L.words[e];if(Fi(t))return[t,e+1];const[n,r]=Ha(e),[i,s]=Gt(r,!1);return Ie(i)?[[i,n],s]:[void 0,e]}function jo(e){if(!Fi(e))return;const[t]=e;return t}function Oh(e){if(!Fi(e))return;const[,t]=e,n=E(t)?oI(t):void 0;return E(n)?n:void 0}function Nh(e){if(!Fi(e))return;const[,t]=e,n=E(t)?aI(t):void 0;return E(n)?n:void 0}const ze=60,rn=25;var Ae=(e=>(e[e.ERROR=0]="ERROR",e[e.LOADER=1]="LOADER",e[e.BOARD=2]="BOARD",e[e.OBJECT=3]="OBJECT",e[e.TERRAIN=4]="TERRAIN",e[e.CHARSET=5]="CHARSET",e[e.PALETTE=6]="PALETTE",e))(Ae||{});function Ch(e,t){const n=e??Ye.ISWALK,r=t??Ye.ISWALK;switch(n){case Ye.ISWALK:return r!==Ye.ISWALK;case Ye.ISSWIM:return r!==Ye.ISSWIM;case Ye.ISSOLID:return!0;case Ye.ISBULLET:return r!==Ye.ISWALK&&r!==Ye.ISSWIM}}function Lh(e,t,n){const r=e==null?void 0:e.objects[n];if(E(r))return r;if(E(t)){const i=ws(e,"player"),s={x:t.x??0,y:t.y??0};Uh(s,i)}}function ws(e,t){var r,i;return[...((i=(r=e==null?void 0:e.named)==null?void 0:r[t])==null?void 0:i.values())??[]].map(s=>typeof s=="string"?e==null?void 0:e.objects[s]:e==null?void 0:e.terrain[s]).filter(E)}function Mh(e,t){const n=jo(t),r=Oh(t),i=Nh(t);return e.filter(s=>!(E(n)&&Bu(s)!==n||E(r)&&dI(s)!==r||E(i)&&pI(s)!==i)).filter(E)}function nl(e,t){return E(e)?t.map(n=>{var r;if(typeof n=="string"){const i=e.objects[n];if(E(i))return i;const s=ws(e,De(n));if(s.length)return s}else if(fr(n)&&n.x>=0&&n.x=0&&n.y0){if(++t>=lv)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function dv(e){return function(){return e}}var Ho=function(){try{var e=ai(Object,"defineProperty");return e({},"",{}),e}catch{}}(),pv=Ho?function(e,t){return Ho(e,"toString",{configurable:!0,enumerable:!1,value:dv(t),writable:!0})}:$i,mv=hv(pv);function Kh(e,t){for(var n=-1,r=e==null?0:e.length;++n-1}var _v=9007199254740991,bv=/^(?:0|[1-9]\d*)$/;function Vo(e,t){var n=typeof e;return t=t??_v,!!t&&(n=="number"||n!="symbol"&&bv.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=kv}function jn(e){return e!=null&&ll(e.length)&&!dr(e)}function Zh(e,t,n){if(!dn(n))return!1;var r=typeof t;return(r=="number"?jn(n)&&Vo(t,n.length):r=="string"&&t in n)?Es(n[t],e):!1}function Sv(e){return cl(function(t,n){var r=-1,i=n.length,s=i>1?n[i-1]:void 0,o=i>2?n[2]:void 0;for(s=e.length>3&&typeof s=="function"?(i--,s):void 0,o&&Zh(n[0],n[1],o)&&(s=i<3?void 0:s,i=1),t=Object(t);++r-1}function UE(e,t){var n=this.__data__,r=Xo(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function pr(e){var t=-1,n=e==null?0:e.length;for(this.clear();++ti?0:i+t),n=n>i?i:n,n<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var s=Array(i);++r=r?e:yl(e,t,n)}var YE="\\ud800-\\udfff",QE="\\u0300-\\u036f",ek="\\ufe20-\\ufe2f",tk="\\u20d0-\\u20ff",nk=QE+ek+tk,rk="\\ufe0e\\ufe0f",ik="\\u200d",sk=RegExp("["+ik+YE+nk+rk+"]");function hd(e){return sk.test(e)}function ok(e){return e.split("")}var dd="\\ud800-\\udfff",ak="\\u0300-\\u036f",ck="\\ufe20-\\ufe2f",lk="\\u20d0-\\u20ff",uk=ak+ck+lk,fk="\\ufe0e\\ufe0f",hk="["+dd+"]",_l="["+uk+"]",bl="\\ud83c[\\udffb-\\udfff]",dk="(?:"+_l+"|"+bl+")",pd="[^"+dd+"]",md="(?:\\ud83c[\\udde6-\\uddff]){2}",gd="[\\ud800-\\udbff][\\udc00-\\udfff]",pk="\\u200d",yd=dk+"?",_d="["+fk+"]?",mk="(?:"+pk+"(?:"+[pd,md,gd].join("|")+")"+_d+yd+")*",gk=_d+yd+mk,yk="(?:"+[pd+_l+"?",_l,md,gd,hk].join("|")+")",_k=RegExp(bl+"(?="+bl+")|"+yk+gk,"g");function bk(e){return e.match(_k)||[]}function wk(e){return hd(e)?bk(e):ok(e)}function vk(e){return function(t){t=ld(t);var n=hd(t)?wk(t):void 0,r=n?n[0]:t.charAt(0),i=n?ZE(n,1).join(""):t.slice(1);return r[e]()+i}}var bd=vk("toUpperCase");function Ek(e,t,n,r){var i=-1,s=e==null?0:e.length;for(r&&s&&(n=e[++i]);++ia))return!1;var l=s.get(e),u=s.get(t);if(l&&u)return l==t&&u==e;var f=-1,d=!0,h=n&eS?new zi:void 0;for(s.set(e,t),s.set(t,e);++f2?t[2]:void 0;for(i&&Zh(t[0],t[1],i)&&(r=1);++n=GS&&(s=Al,o=!1,t=new zi(t));e:for(;++i-1?i[s?t[o]:o]:void 0}}var XS=Math.max;function ZS(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var i=n==null?0:Go(n);return i<0&&(i=XS(r+i,0)),qh(e,Wn(t),i)}var Gi=JS(ZS);function In(e){return e&&e.length?e[0]:void 0}function YS(e,t){var n=-1,r=jn(e)?Array(e.length):[];return li(e,function(i,s,o){r[++n]=t(i,s,o)}),r}function ce(e,t){var n=Le(e)?Wo:YS;return n(e,Wn(t))}function yn(e,t){return gl(ce(e,t))}var QS=Object.prototype,eA=QS.hasOwnProperty,Zd=zS(function(e,t,n){eA.call(e,n)?e[n].push(t):ol(e,n,[t])}),tA=Object.prototype,nA=tA.hasOwnProperty;function rA(e,t){return e!=null&&nA.call(e,t)}function pe(e,t){return e!=null&&Kd(e,t,rA)}var iA="[object String]";function Xt(e){return typeof e=="string"||!Le(e)&&xn(e)&&Br(e)==iA}function sA(e,t){return Wo(t,function(n){return e[n]})}function dt(e){return e==null?[]:sA(e,pn(e))}var oA=Math.max;function $t(e,t,n,r){e=jn(e)?e:dt(e),n=n&&!r?Go(n):0;var i=e.length;return n<0&&(n=oA(i+n,0)),Xt(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&sl(e,t,n)>-1}function Yd(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var i=0;return sl(e,t,i)}var aA="[object Map]",cA="[object Set]",lA=Object.prototype,uA=lA.hasOwnProperty;function Ke(e){if(e==null)return!0;if(jn(e)&&(Le(e)||typeof e=="string"||typeof e.splice=="function"||Ss(e)||fl(e)||qo(e)))return!e.length;var t=mn(e);if(t==aA||t==cA)return!e.size;if(ks(e))return!ad(e).length;for(var n in e)if(uA.call(e,n))return!1;return!0}var fA="[object RegExp]";function hA(e){return xn(e)&&Br(e)==fA}var Qd=Fr&&Fr.isRegExp,gr=Qd?Jo(Qd):hA;function yr(e){return e===void 0}var dA="Expected a function";function pA(e){if(typeof e!="function")throw new TypeError(dA);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}function mA(e,t,n,r){if(!dn(e))return e;t=Yo(t,e);for(var i=-1,s=t.length,o=s-1,a=e;a!=null&&++i=vA){var l=wA(e);if(l)return Tl(l);o=!1,i=Al,c=new zi}else c=a;e:for(;++r{n.accept(t)})}}class Yt extends Gn{constructor(t){super([]),this.idx=1,Jt(this,On(t,n=>n!==void 0))}set definition(t){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(t){t.visit(this)}}class Hi extends Gn{constructor(t){super(t.definition),this.orgText="",Jt(this,On(t,n=>n!==void 0))}}class Qt extends Gn{constructor(t){super(t.definition),this.ignoreAmbiguities=!1,Jt(this,On(t,n=>n!==void 0))}}class en extends Gn{constructor(t){super(t.definition),this.idx=1,Jt(this,On(t,n=>n!==void 0))}}class Hn extends Gn{constructor(t){super(t.definition),this.idx=1,Jt(this,On(t,n=>n!==void 0))}}class Vn extends Gn{constructor(t){super(t.definition),this.idx=1,Jt(this,On(t,n=>n!==void 0))}}class _t extends Gn{constructor(t){super(t.definition),this.idx=1,Jt(this,On(t,n=>n!==void 0))}}class Nn extends Gn{constructor(t){super(t.definition),this.idx=1,Jt(this,On(t,n=>n!==void 0))}}class Cn extends Gn{get definition(){return this._definition}set definition(t){this._definition=t}constructor(t){super(t.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,Jt(this,On(t,n=>n!==void 0))}}class tt{constructor(t){this.idx=1,Jt(this,On(t,n=>n!==void 0))}accept(t){t.visit(this)}}function AA(e){return ce(e,sa)}function sa(e){function t(n){return ce(n,sa)}if(e instanceof Yt){const n={type:"NonTerminal",name:e.nonTerminalName,idx:e.idx};return Xt(e.label)&&(n.label=e.label),n}else{if(e instanceof Qt)return{type:"Alternative",definition:t(e.definition)};if(e instanceof en)return{type:"Option",idx:e.idx,definition:t(e.definition)};if(e instanceof Hn)return{type:"RepetitionMandatory",idx:e.idx,definition:t(e.definition)};if(e instanceof Vn)return{type:"RepetitionMandatoryWithSeparator",idx:e.idx,separator:sa(new tt({terminalType:e.separator})),definition:t(e.definition)};if(e instanceof Nn)return{type:"RepetitionWithSeparator",idx:e.idx,separator:sa(new tt({terminalType:e.separator})),definition:t(e.definition)};if(e instanceof _t)return{type:"Repetition",idx:e.idx,definition:t(e.definition)};if(e instanceof Cn)return{type:"Alternation",idx:e.idx,definition:t(e.definition)};if(e instanceof tt){const n={type:"Terminal",name:e.terminalType.name,label:kA(e.terminalType),idx:e.idx};Xt(e.label)&&(n.terminalLabel=e.label);const r=e.terminalType.PATTERN;return e.terminalType.PATTERN&&(n.pattern=gr(r)?r.source:r),n}else{if(e instanceof Hi)return{type:"Rule",name:e.name,orgText:e.orgText,definition:t(e.definition)};throw Error("non exhaustive match")}}}class ui{visit(t){const n=t;switch(n.constructor){case Yt:return this.visitNonTerminal(n);case Qt:return this.visitAlternative(n);case en:return this.visitOption(n);case Hn:return this.visitRepetitionMandatory(n);case Vn:return this.visitRepetitionMandatoryWithSeparator(n);case Nn:return this.visitRepetitionWithSeparator(n);case _t:return this.visitRepetition(n);case Cn:return this.visitAlternation(n);case tt:return this.visitTerminal(n);case Hi:return this.visitRule(n);default:throw Error("non exhaustive match")}}visitNonTerminal(t){}visitAlternative(t){}visitOption(t){}visitRepetition(t){}visitRepetitionMandatory(t){}visitRepetitionMandatoryWithSeparator(t){}visitRepetitionWithSeparator(t){}visitAlternation(t){}visitTerminal(t){}visitRule(t){}}function TA(e){return e instanceof Qt||e instanceof en||e instanceof _t||e instanceof Hn||e instanceof Vn||e instanceof Nn||e instanceof tt||e instanceof Hi}function oa(e,t=[]){return e instanceof en||e instanceof _t||e instanceof Nn?!0:e instanceof Cn?Ol(e.definition,r=>oa(r,t)):e instanceof Yt&&$t(t,e)?!1:e instanceof Gn?(e instanceof Yt&&t.push(e),Rn(e.definition,r=>oa(r,t))):!1}function xA(e){return e instanceof Cn}function Kn(e){if(e instanceof Yt)return"SUBRULE";if(e instanceof en)return"OPTION";if(e instanceof Cn)return"OR";if(e instanceof Hn)return"AT_LEAST_ONE";if(e instanceof Vn)return"AT_LEAST_ONE_SEP";if(e instanceof Nn)return"MANY_SEP";if(e instanceof _t)return"MANY";if(e instanceof tt)return"CONSUME";throw Error("non exhaustive match")}class aa{walk(t,n=[]){me(t.definition,(r,i)=>{const s=Lt(t.definition,i+1);if(r instanceof Yt)this.walkProdRef(r,s,n);else if(r instanceof tt)this.walkTerminal(r,s,n);else if(r instanceof Qt)this.walkFlat(r,s,n);else if(r instanceof en)this.walkOption(r,s,n);else if(r instanceof Hn)this.walkAtLeastOne(r,s,n);else if(r instanceof Vn)this.walkAtLeastOneSep(r,s,n);else if(r instanceof Nn)this.walkManySep(r,s,n);else if(r instanceof _t)this.walkMany(r,s,n);else if(r instanceof Cn)this.walkOr(r,s,n);else throw Error("non exhaustive match")})}walkTerminal(t,n,r){}walkProdRef(t,n,r){}walkFlat(t,n,r){const i=n.concat(r);this.walk(t,i)}walkOption(t,n,r){const i=n.concat(r);this.walk(t,i)}walkAtLeastOne(t,n,r){const i=[new en({definition:t.definition})].concat(n,r);this.walk(t,i)}walkAtLeastOneSep(t,n,r){const i=rp(t,n,r);this.walk(t,i)}walkMany(t,n,r){const i=[new en({definition:t.definition})].concat(n,r);this.walk(t,i)}walkManySep(t,n,r){const i=rp(t,n,r);this.walk(t,i)}walkOr(t,n,r){const i=n.concat(r);me(t.definition,s=>{const o=new Qt({definition:[s]});this.walk(o,i)})}}function rp(e,t,n){return[new en({definition:[new tt({terminalType:e.separator})].concat(e.definition)})].concat(t,n)}function Ns(e){if(e instanceof Yt)return Ns(e.referencedRule);if(e instanceof tt)return OA(e);if(TA(e))return RA(e);if(xA(e))return IA(e);throw Error("non exhaustive match")}function RA(e){let t=[];const n=e.definition;let r=0,i=n.length>r,s,o=!0;for(;i&&o;)s=n[r],o=oa(s),t=t.concat(Ns(s)),r=r+1,i=n.length>r;return ia(t)}function IA(e){const t=ce(e.definition,n=>Ns(n));return ia(sn(t))}function OA(e){return[e.terminalType]}const ip="_~IN~_";class NA extends aa{constructor(t){super(),this.topProd=t,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(t,n,r){}walkProdRef(t,n,r){const i=LA(t.referencedRule,t.idx)+this.topProd.name,s=n.concat(r),o=new Qt({definition:s}),a=Ns(o);this.follows[i]=a}}function CA(e){const t={};return me(e,n=>{const r=new NA(n).startWalking();Jt(t,r)}),t}function LA(e,t){return e.name+t+ip}function ge(e){return e.charCodeAt(0)}function Cl(e,t){Array.isArray(e)?e.forEach(function(n){t.push(n)}):t.push(e)}function Cs(e,t){if(e[t]===!0)throw"duplicate flag "+t;e[t],e[t]=!0}function Vi(e){if(e===void 0)throw Error("Internal Error - Should never get here!");return!0}function MA(){throw Error("Internal Error - Should never get here!")}function sp(e){return e.type==="Character"}const ca=[];for(let e=ge("0");e<=ge("9");e++)ca.push(e);const la=[ge("_")].concat(ca);for(let e=ge("a");e<=ge("z");e++)la.push(e);for(let e=ge("A");e<=ge("Z");e++)la.push(e);const op=[ge(" "),ge("\f"),ge(` -`),ge("\r"),ge(" "),ge("\v"),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge("\u2028"),ge("\u2029"),ge(" "),ge(" "),ge(" "),ge("\uFEFF")],UA=/[0-9a-fA-F]/,ua=/[0-9]/,PA=/[1-9]/;class DA{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(t){this.idx=t.idx,this.input=t.input,this.groupIdx=t.groupIdx}pattern(t){this.idx=0,this.input=t,this.groupIdx=0,this.consumeChar("/");const n=this.disjunction();this.consumeChar("/");const r={type:"Flags",loc:{begin:this.idx,end:t.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":Cs(r,"global");break;case"i":Cs(r,"ignoreCase");break;case"m":Cs(r,"multiLine");break;case"u":Cs(r,"unicode");break;case"y":Cs(r,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:r,value:n,loc:this.loc(0)}}disjunction(){const t=[],n=this.idx;for(t.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),t.push(this.alternative());return{type:"Disjunction",value:t,loc:this.loc(n)}}alternative(){const t=[],n=this.idx;for(;this.isTerm();)t.push(this.term());return{type:"Alternative",value:t,loc:this.loc(n)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){const t=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(t)};case"$":return{type:"EndAnchor",loc:this.loc(t)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(t)};case"B":return{type:"NonWordBoundary",loc:this.loc(t)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let n;switch(this.popChar()){case"=":n="Lookahead";break;case"!":n="NegativeLookahead";break}Vi(n);const r=this.disjunction();return this.consumeChar(")"),{type:n,value:r,loc:this.loc(t)}}return MA()}quantifier(t=!1){let n;const r=this.idx;switch(this.popChar()){case"*":n={atLeast:0,atMost:1/0};break;case"+":n={atLeast:1,atMost:1/0};break;case"?":n={atLeast:0,atMost:1};break;case"{":const i=this.integerIncludingZero();switch(this.popChar()){case"}":n={atLeast:i,atMost:i};break;case",":let s;this.isDigit()?(s=this.integerIncludingZero(),n={atLeast:i,atMost:s}):n={atLeast:i,atMost:1/0},this.consumeChar("}");break}if(t===!0&&n===void 0)return;Vi(n);break}if(!(t===!0&&n===void 0)&&Vi(n))return this.peekChar(0)==="?"?(this.consumeChar("?"),n.greedy=!1):n.greedy=!0,n.type="Quantifier",n.loc=this.loc(r),n}atom(){let t;const n=this.idx;switch(this.peekChar()){case".":t=this.dotAll();break;case"\\":t=this.atomEscape();break;case"[":t=this.characterClass();break;case"(":t=this.group();break}if(t===void 0&&this.isPatternCharacter()&&(t=this.patternCharacter()),Vi(t))return t.loc=this.loc(n),this.isQuantifier()&&(t.quantifier=this.quantifier()),t}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[ge(` -`),ge("\r"),ge("\u2028"),ge("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let t,n=!1;switch(this.popChar()){case"d":t=ca;break;case"D":t=ca,n=!0;break;case"s":t=op;break;case"S":t=op,n=!0;break;case"w":t=la;break;case"W":t=la,n=!0;break}if(Vi(t))return{type:"Set",value:t,complement:n}}controlEscapeAtom(){let t;switch(this.popChar()){case"f":t=ge("\f");break;case"n":t=ge(` -`);break;case"r":t=ge("\r");break;case"t":t=ge(" ");break;case"v":t=ge("\v");break}if(Vi(t))return{type:"Character",value:t}}controlLetterEscapeAtom(){this.consumeChar("c");const t=this.popChar();if(/[a-zA-Z]/.test(t)===!1)throw Error("Invalid ");return{type:"Character",value:t.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:ge("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){const t=this.popChar();return{type:"Character",value:ge(t)}}classPatternCharacterAtom(){switch(this.peekChar()){case` -`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:const t=this.popChar();return{type:"Character",value:ge(t)}}}characterClass(){const t=[];let n=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),n=!0);this.isClassAtom();){const r=this.classAtom();if(r.type,sp(r)&&this.isRangeDash()){this.consumeChar("-");const i=this.classAtom();if(i.type,sp(i)){if(i.value=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(t){return{begin:t,end:this.idx}}}class Ll{visitChildren(t){for(const n in t){const r=t[n];t.hasOwnProperty(n)&&(r.type!==void 0?this.visit(r):Array.isArray(r)&&r.forEach(i=>{this.visit(i)},this))}}visit(t){switch(t.type){case"Pattern":this.visitPattern(t);break;case"Flags":this.visitFlags(t);break;case"Disjunction":this.visitDisjunction(t);break;case"Alternative":this.visitAlternative(t);break;case"StartAnchor":this.visitStartAnchor(t);break;case"EndAnchor":this.visitEndAnchor(t);break;case"WordBoundary":this.visitWordBoundary(t);break;case"NonWordBoundary":this.visitNonWordBoundary(t);break;case"Lookahead":this.visitLookahead(t);break;case"NegativeLookahead":this.visitNegativeLookahead(t);break;case"Character":this.visitCharacter(t);break;case"Set":this.visitSet(t);break;case"Group":this.visitGroup(t);break;case"GroupBackReference":this.visitGroupBackReference(t);break;case"Quantifier":this.visitQuantifier(t);break}this.visitChildren(t)}visitPattern(t){}visitFlags(t){}visitDisjunction(t){}visitAlternative(t){}visitStartAnchor(t){}visitEndAnchor(t){}visitWordBoundary(t){}visitNonWordBoundary(t){}visitLookahead(t){}visitNegativeLookahead(t){}visitCharacter(t){}visitSet(t){}visitGroup(t){}visitGroupBackReference(t){}visitQuantifier(t){}}let fa={};const BA=new DA;function ha(e){const t=e.toString();if(fa.hasOwnProperty(t))return fa[t];{const n=BA.pattern(t);return fa[t]=n,n}}function FA(){fa={}}const ap="Complement Sets are not supported for first char optimization",da=`Unable to use "first char" lexer optimizations: -`;function $A(e,t=!1){try{const n=ha(e);return Ml(n.value,{},n.flags.ignoreCase)}catch(n){if(n.message===ap)t&&ep(`${da} Unable to optimize: < ${e.toString()} > - Complement Sets cannot be automatically optimized. - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let r="";t&&(r=` - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),Nl(`${da} - Failed parsing: < ${e.toString()} > - Using the @chevrotain/regexp-to-ast library - Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+r)}}return[]}function Ml(e,t,n){switch(e.type){case"Disjunction":for(let i=0;i{if(typeof c=="number")pa(c,t,n);else{const l=c;if(n===!0)for(let u=l.from;u<=l.to;u++)pa(u,t,n);else{for(let u=l.from;u<=l.to&&u=Ms){const u=l.from>=Ms?l.from:Ms,f=l.to,d=$r(u),h=$r(f);for(let p=d;p<=h;p++)t[p]=p}}}});break;case"Group":Ml(o.value,t,n);break;default:throw Error("Non Exhaustive Match")}const a=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&Ul(o)===!1||o.type!=="Group"&&a===!1)break}break;default:throw Error("non exhaustive match!")}return dt(t)}function pa(e,t,n){const r=$r(e);t[r]=r,n===!0&&jA(e,t)}function jA(e,t){const n=String.fromCharCode(e),r=n.toUpperCase();if(r!==n){const i=$r(r.charCodeAt(0));t[i]=i}else{const i=n.toLowerCase();if(i!==n){const s=$r(i.charCodeAt(0));t[s]=s}}}function cp(e,t){return Gi(e.value,n=>{if(typeof n=="number")return $t(t,n);{const r=n;return Gi(t,i=>r.from<=i&&i<=r.to)!==void 0}})}function Ul(e){const t=e.quantifier;return t&&t.atLeast===0?!0:e.value?Le(e.value)?Rn(e.value,Ul):Ul(e.value):!1}class zA extends Ll{constructor(t){super(),this.targetCharCodes=t,this.found=!1}visitChildren(t){if(this.found!==!0){switch(t.type){case"Lookahead":this.visitLookahead(t);return;case"NegativeLookahead":this.visitNegativeLookahead(t);return}super.visitChildren(t)}}visitCharacter(t){$t(this.targetCharCodes,t.value)&&(this.found=!0)}visitSet(t){t.complement?cp(t,this.targetCharCodes)===void 0&&(this.found=!0):cp(t,this.targetCharCodes)!==void 0&&(this.found=!0)}}function Pl(e,t){if(t instanceof RegExp){const n=ha(t),r=new zA(e);return r.visit(n),r.found}else return Gi(t,n=>$t(e,n.charCodeAt(0)))!==void 0}const fi="PATTERN",Ls="defaultMode",ma="modes";let lp=typeof new RegExp("(?:)").sticky=="boolean";function WA(e,t){t=Il(t,{useSticky:lp,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` -`],tracer:(w,v)=>v()});const n=t.tracer;n("initCharCodeToOptimizedIndexMap",()=>{hT()});let r;n("Reject Lexer.NA",()=>{r=ra(e,w=>w[fi]===bt.NA)});let i=!1,s;n("Transform Patterns",()=>{i=!1,s=ce(r,w=>{const v=w[fi];if(gr(v)){const S=v.source;return S.length===1&&S!=="^"&&S!=="$"&&S!=="."&&!v.ignoreCase?S:S.length===2&&S[0]==="\\"&&!$t(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],S[1])?S[1]:t.useSticky?fp(v):up(v)}else{if(dr(v))return i=!0,{exec:v};if(typeof v=="object")return i=!0,v;if(typeof v=="string"){if(v.length===1)return v;{const S=v.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),C=new RegExp(S);return t.useSticky?fp(C):up(C)}}else throw Error("non exhaustive match")}})});let o,a,c,l,u;n("misc mapping",()=>{o=ce(r,w=>w.tokenTypeIdx),a=ce(r,w=>{const v=w.GROUP;if(v!==bt.SKIPPED){if(Xt(v))return v;if(yr(v))return!1;throw Error("non exhaustive match")}}),c=ce(r,w=>{const v=w.LONGER_ALT;if(v)return Le(v)?ce(v,C=>Yd(r,C)):[Yd(r,v)]}),l=ce(r,w=>w.PUSH_MODE),u=ce(r,w=>pe(w,"POP_MODE"))});let f;n("Line Terminator Handling",()=>{const w=pp(t.lineTerminatorCharacters);f=ce(r,v=>!1),t.positionTracking!=="onlyOffset"&&(f=ce(r,v=>pe(v,"LINE_BREAKS")?!!v.LINE_BREAKS:dp(v,w)===!1&&Pl(w,v.PATTERN)))});let d,h,p,m;n("Misc Mapping #2",()=>{d=ce(r,hp),h=ce(s,lT),p=Zt(r,(w,v)=>{const S=v.GROUP;return Xt(S)&&S!==bt.SKIPPED&&(w[S]=[]),w},{}),m=ce(s,(w,v)=>({pattern:s[v],longerAlt:c[v],canLineTerminator:f[v],isCustom:d[v],short:h[v],group:a[v],push:l[v],pop:u[v],tokenTypeIdx:o[v],tokenType:r[v]}))});let b=!0,_=[];return t.safeMode||n("First Char Optimization",()=>{_=Zt(r,(w,v,S)=>{if(typeof v.PATTERN=="string"){const C=v.PATTERN.charCodeAt(0),I=$r(C);Dl(w,I,m[S])}else if(Le(v.START_CHARS_HINT)){let C;me(v.START_CHARS_HINT,I=>{const T=typeof I=="string"?I.charCodeAt(0):I,M=$r(T);C!==M&&(C=M,Dl(w,M,m[S]))})}else if(gr(v.PATTERN))if(v.PATTERN.unicode)b=!1,t.ensureOptimizations&&Nl(`${da} Unable to analyze < ${v.PATTERN.toString()} > pattern. - The regexp unicode flag is not currently supported by the regexp-to-ast library. - This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{const C=$A(v.PATTERN,t.ensureOptimizations);Ke(C)&&(b=!1),me(C,I=>{Dl(w,I,m[S])})}else t.ensureOptimizations&&Nl(`${da} TokenType: <${v.name}> is using a custom token pattern without providing parameter. - This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),b=!1;return w},[])}),{emptyGroups:p,patternIdxToConfig:m,charCodeToPatternIdxToConfig:_,hasCustom:i,canBeOptimized:b}}function GA(e,t){let n=[];const r=VA(e);n=n.concat(r.errors);const i=KA(r.valid),s=i.valid;return n=n.concat(i.errors),n=n.concat(HA(s)),n=n.concat(tT(s)),n=n.concat(nT(s,t)),n=n.concat(rT(s)),n}function HA(e){let t=[];const n=gn(e,r=>gr(r[fi]));return t=t.concat(JA(n)),t=t.concat(YA(n)),t=t.concat(QA(n)),t=t.concat(eT(n)),t=t.concat(XA(n)),t}function VA(e){const t=gn(e,i=>!pe(i,fi)),n=ce(t,i=>({message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:st.MISSING_PATTERN,tokenTypes:[i]})),r=na(e,t);return{errors:n,valid:r}}function KA(e){const t=gn(e,i=>{const s=i[fi];return!gr(s)&&!dr(s)&&!pe(s,"exec")&&!Xt(s)}),n=ce(t,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:st.INVALID_PATTERN,tokenTypes:[i]})),r=na(e,t);return{errors:n,valid:r}}const qA=/[^\\][$]/;function JA(e){class t extends Ll{constructor(){super(...arguments),this.found=!1}visitEndAnchor(s){this.found=!0}}const n=gn(e,i=>{const s=i.PATTERN;try{const o=ha(s),a=new t;return a.visit(o),a.found}catch{return qA.test(s.source)}});return ce(n,i=>({message:`Unexpected RegExp Anchor Error: - Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain end of input anchor '$' - See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:st.EOI_ANCHOR_FOUND,tokenTypes:[i]}))}function XA(e){const t=gn(e,r=>r.PATTERN.test(""));return ce(t,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' must not match an empty string",type:st.EMPTY_MATCH_PATTERN,tokenTypes:[r]}))}const ZA=/[^\\[][\^]|^\^/;function YA(e){class t extends Ll{constructor(){super(...arguments),this.found=!1}visitStartAnchor(s){this.found=!0}}const n=gn(e,i=>{const s=i.PATTERN;try{const o=ha(s),a=new t;return a.visit(o),a.found}catch{return ZA.test(s.source)}});return ce(n,i=>({message:`Unexpected RegExp Anchor Error: - Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain start of input anchor '^' - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:st.SOI_ANCHOR_FOUND,tokenTypes:[i]}))}function QA(e){const t=gn(e,r=>{const i=r[fi];return i instanceof RegExp&&(i.multiline||i.global)});return ce(t,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:st.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[r]}))}function eT(e){const t=[];let n=ce(e,s=>Zt(e,(o,a)=>(s.PATTERN.source===a.PATTERN.source&&!$t(t,a)&&a.PATTERN!==bt.NA&&(t.push(a),o.push(a)),o),[]));n=Is(n);const r=gn(n,s=>s.length>1);return ce(r,s=>{const o=ce(s,c=>c.name);return{message:`The same RegExp pattern ->${In(s).PATTERN}<-has been used in all of the following Token Types: ${o.join(", ")} <-`,type:st.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}})}function tT(e){const t=gn(e,r=>{if(!pe(r,"GROUP"))return!1;const i=r.GROUP;return i!==bt.SKIPPED&&i!==bt.NA&&!Xt(i)});return ce(t,r=>({message:"Token Type: ->"+r.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:st.INVALID_GROUP_TYPE_FOUND,tokenTypes:[r]}))}function nT(e,t){const n=gn(e,i=>i.PUSH_MODE!==void 0&&!$t(t,i.PUSH_MODE));return ce(n,i=>({message:`Token Type: ->${i.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${i.PUSH_MODE}<-which does not exist`,type:st.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}))}function rT(e){const t=[],n=Zt(e,(r,i,s)=>{const o=i.PATTERN;return o===bt.NA||(Xt(o)?r.push({str:o,idx:s,tokenType:i}):gr(o)&&sT(o)&&r.push({str:o.source,idx:s,tokenType:i})),r},[]);return me(e,(r,i)=>{me(n,({str:s,idx:o,tokenType:a})=>{if(i${a.name}<- can never be matched. -Because it appears AFTER the Token Type ->${r.name}<-in the lexer's definition. -See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;t.push({message:c,type:st.UNREACHABLE_PATTERN,tokenTypes:[r,a]})}})}),t}function iT(e,t){if(gr(t)){const n=t.exec(e);return n!==null&&n.index===0}else{if(dr(t))return t(e,0,[],{});if(pe(t,"exec"))return t.exec(e,0,[],{});if(typeof t=="string")return t===e;throw Error("non exhaustive match")}}function sT(e){return Gi([".","\\","[","]","|","^","$","(",")","?","*","+","{"],n=>e.source.indexOf(n)!==-1)===void 0}function up(e){const t=e.ignoreCase?"i":"";return new RegExp(`^(?:${e.source})`,t)}function fp(e){const t=e.ignoreCase?"iy":"y";return new RegExp(`${e.source}`,t)}function oT(e,t,n){const r=[];return pe(e,Ls)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+Ls+`> property in its definition -`,type:st.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),pe(e,ma)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+ma+`> property in its definition -`,type:st.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),pe(e,ma)&&pe(e,Ls)&&!pe(e.modes,e.defaultMode)&&r.push({message:`A MultiMode Lexer cannot be initialized with a ${Ls}: <${e.defaultMode}>which does not exist -`,type:st.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),pe(e,ma)&&me(e.modes,(i,s)=>{me(i,(o,a)=>{if(yr(o))r.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${s}> at index: <${a}> -`,type:st.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED});else if(pe(o,"LONGER_ALT")){const c=Le(o.LONGER_ALT)?o.LONGER_ALT:[o.LONGER_ALT];me(c,l=>{!yr(l)&&!$t(i,l)&&r.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${l.name}> on token <${o.name}> outside of mode <${s}> -`,type:st.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),r}function aT(e,t,n){const r=[];let i=!1;const s=Is(sn(dt(e.modes))),o=ra(s,c=>c[fi]===bt.NA),a=pp(n);return t&&me(o,c=>{const l=dp(c,a);if(l!==!1){const f={message:fT(c,l),type:l.issue,tokenType:c};r.push(f)}else pe(c,"LINE_BREAKS")?c.LINE_BREAKS===!0&&(i=!0):Pl(a,c.PATTERN)&&(i=!0)}),t&&!i&&r.push({message:`Warning: No LINE_BREAKS Found. - This Lexer has been defined to track line and column information, - But none of the Token Types can be identified as matching a line terminator. - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS - for details.`,type:st.NO_LINE_BREAKS_FLAGS}),r}function cT(e){const t={},n=pn(e);return me(n,r=>{const i=e[r];if(Le(i))t[r]=[];else throw Error("non exhaustive match")}),t}function hp(e){const t=e.PATTERN;if(gr(t))return!1;if(dr(t))return!0;if(pe(t,"exec"))return!0;if(Xt(t))return!1;throw Error("non exhaustive match")}function lT(e){return Xt(e)&&e.length===1?e.charCodeAt(0):!1}const uT={test:function(e){const t=e.length;for(let n=this.lastIndex;n Token Type - Root cause: ${t.errMsg}. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(t.issue===st.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. - The problem is in the <${e.name}> Token Type - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function pp(e){return ce(e,n=>Xt(n)?n.charCodeAt(0):n)}function Dl(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}const Ms=256;let ga=[];function $r(e){return e255?255+~~(e/255):e}}function Us(e,t){const n=e.tokenTypeIdx;return n===t.tokenTypeIdx?!0:t.isParent===!0&&t.categoryMatchesMap[n]===!0}function ya(e,t){return e.tokenTypeIdx===t.tokenTypeIdx}let mp=1;const gp={};function Ps(e){const t=dT(e);pT(t),gT(t),mT(t),me(t,n=>{n.isParent=n.categoryMatches.length>0})}function dT(e){let t=Ct(e),n=e,r=!0;for(;r;){n=Is(sn(ce(n,s=>s.CATEGORIES)));const i=na(n,t);t=t.concat(i),Ke(i)?r=!1:n=i}return t}function pT(e){me(e,t=>{_p(t)||(gp[mp]=t,t.tokenTypeIdx=mp++),bp(t)&&!Le(t.CATEGORIES)&&(t.CATEGORIES=[t.CATEGORIES]),bp(t)||(t.CATEGORIES=[]),yT(t)||(t.categoryMatches=[]),_T(t)||(t.categoryMatchesMap={})})}function mT(e){me(e,t=>{t.categoryMatches=[],me(t.categoryMatchesMap,(n,r)=>{t.categoryMatches.push(gp[r].tokenTypeIdx)})})}function gT(e){me(e,t=>{yp([],t)})}function yp(e,t){me(e,n=>{t.categoryMatchesMap[n.tokenTypeIdx]=!0}),me(t.CATEGORIES,n=>{const r=e.concat(t);$t(r,n)||yp(r,n)})}function _p(e){return pe(e,"tokenTypeIdx")}function bp(e){return pe(e,"CATEGORIES")}function yT(e){return pe(e,"categoryMatches")}function _T(e){return pe(e,"categoryMatchesMap")}function bT(e){return pe(e,"tokenTypeIdx")}const wT={buildUnableToPopLexerModeMessage(e){return`Unable to pop Lexer Mode after encountering Token ->${e.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(e,t,n,r,i){return`unexpected character: ->${e.charAt(t)}<- at offset: ${t}, skipped ${n} characters.`}};var st;(function(e){e[e.MISSING_PATTERN=0]="MISSING_PATTERN",e[e.INVALID_PATTERN=1]="INVALID_PATTERN",e[e.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",e[e.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",e[e.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",e[e.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",e[e.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",e[e.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",e[e.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",e[e.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",e[e.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",e[e.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",e[e.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",e[e.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",e[e.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",e[e.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",e[e.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",e[e.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(st||(st={}));const Ds={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` -`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:wT,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(Ds);class bt{constructor(t,n=Ds){if(this.lexerDefinition=t,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(i,s)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;const o=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${i}>`);const{time:a,value:c}=tp(s),l=a>10?console.warn:console.log;return this.traceInitIndent time: ${a}ms`),this.traceInitIndent--,c}else return s()},typeof n=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. -a boolean 2nd argument is no longer supported`);this.config=Jt({},Ds,n);const r=this.config.traceInitPerf;r===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof r=="number"&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let i,s=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===Ds.lineTerminatorsPattern)this.config.lineTerminatorsPattern=uT;else if(this.config.lineTerminatorCharacters===Ds.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(n.safeMode&&n.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),Le(t)?i={modes:{defaultMode:Ct(t)},defaultMode:Ls}:(s=!1,i=Ct(t))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(oT(i,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(aT(i,this.trackStartLines,this.config.lineTerminatorCharacters))})),i.modes=i.modes?i.modes:{},me(i.modes,(a,c)=>{i.modes[c]=ra(a,l=>yr(l))});const o=pn(i.modes);if(me(i.modes,(a,c)=>{this.TRACE_INIT(`Mode: <${c}> processing`,()=>{if(this.modes.push(c),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(GA(a,o))}),Ke(this.lexerDefinitionErrors)){Ps(a);let l;this.TRACE_INIT("analyzeTokenTypes",()=>{l=WA(a,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:n.positionTracking,ensureOptimizations:n.ensureOptimizations,safeMode:n.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[c]=l.patternIdxToConfig,this.charCodeToPatternIdxToConfig[c]=l.charCodeToPatternIdxToConfig,this.emptyGroups=Jt({},this.emptyGroups,l.emptyGroups),this.hasCustom=l.hasCustom||this.hasCustom,this.canModeBeOptimized[c]=l.canBeOptimized}})}),this.defaultMode=i.defaultMode,!Ke(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){const c=ce(this.lexerDefinitionErrors,l=>l.message).join(`----------------------- -`);throw new Error(`Errors detected in definition of Lexer: -`+c)}me(this.lexerDefinitionWarning,a=>{ep(a.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(lp?(this.chopInput=$i,this.match=this.matchWithTest):(this.updateLastIndex=yt,this.match=this.matchWithExec),s&&(this.handleModes=yt),this.trackStartLines===!1&&(this.computeNewColumn=$i),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=yt),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{const a=Zt(this.canModeBeOptimized,(c,l,u)=>(l===!1&&c.push(u),c),[]);if(n.ensureOptimizations&&!Ke(a))throw Error(`Lexer Modes: < ${a.join(", ")} > cannot be optimized. - Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. - Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{FA()}),this.TRACE_INIT("toFastProperties",()=>{np(this)})})}tokenize(t,n=this.defaultMode){if(!Ke(this.lexerDefinitionErrors)){const i=ce(this.lexerDefinitionErrors,s=>s.message).join(`----------------------- -`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: -`+i)}return this.tokenizeInternal(t,n)}tokenizeInternal(t,n){let r,i,s,o,a,c,l,u,f,d,h,p,m,b,_;const w=t,v=w.length;let S=0,C=0;const I=this.hasCustom?0:Math.floor(t.length/10),T=new Array(I),M=[];let x=this.trackStartLines?1:void 0,V=this.trackStartLines?1:void 0;const oe=cT(this.emptyGroups),O=this.trackStartLines,k=this.config.lineTerminatorsPattern;let g=0,N=[],W=[];const B=[],Z=[];Object.freeze(Z);let H;function Y(){return N}function $(Se){const je=$r(Se),we=W[je];return we===void 0?Z:we}const F=Se=>{if(B.length===1&&Se.tokenType.PUSH_MODE===void 0){const je=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(Se);M.push({offset:Se.startOffset,line:Se.startLine,column:Se.startColumn,length:Se.image.length,message:je})}else{B.pop();const je=Wi(B);N=this.patternIdxToConfig[je],W=this.charCodeToPatternIdxToConfig[je],g=N.length;const we=this.canModeBeOptimized[je]&&this.config.safeMode===!1;W&&we?H=$:H=Y}};function ue(Se){B.push(Se),W=this.charCodeToPatternIdxToConfig[Se],N=this.patternIdxToConfig[Se],g=N.length,g=N.length;const je=this.canModeBeOptimized[Se]&&this.config.safeMode===!1;W&&je?H=$:H=Y}ue.call(this,n);let Q;const ee=this.config.recoveryEnabled;for(;Sc.length){c=o,l=u,Q=gt;break}}}break}}if(c!==null){if(f=c.length,d=Q.group,d!==void 0&&(h=Q.tokenTypeIdx,p=this.createTokenInstance(c,S,h,Q.tokenType,x,V,f),this.handlePayload(p,l),d===!1?C=this.addToken(T,C,p):oe[d].push(p)),t=this.chopInput(t,f),S=S+f,V=this.computeNewColumn(V,f),O===!0&&Q.canLineTerminator===!0){let _e=0,Ge,$e;k.lastIndex=0;do Ge=k.test(c),Ge===!0&&($e=k.lastIndex-1,_e++);while(Ge===!0);_e!==0&&(x=x+_e,V=f-$e,this.updateTokenEndLineColumnLocation(p,d,$e,_e,x,V,f))}this.handleModes(Q,F,ue,p)}else{const _e=S,Ge=x,$e=V;let gt=ee===!1;for(;gt===!1&&S ${Bs(e)} <--`:`token of type --> ${e.name} <--`} but found --> '${t.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:e,ruleName:t}){return"Redundant input, expecting EOF but found: "+e.image},buildNoViableAltMessage({expectedPathsPerAlt:e,actual:t,previous:n,customUserDescription:r,ruleName:i}){const s="Expecting: ",a=` -but found: '`+In(t).image+"'";if(r)return s+r+a;{const c=Zt(e,(d,h)=>d.concat(h),[]),l=ce(c,d=>`[${ce(d,h=>Bs(h)).join(", ")}]`),f=`one of these possible Token sequences: -${ce(l,(d,h)=>` ${h+1}. ${d}`).join(` -`)}`;return s+f+a}},buildEarlyExitMessage({expectedIterationPaths:e,actual:t,customUserDescription:n,ruleName:r}){const i="Expecting: ",o=` -but found: '`+In(t).image+"'";if(n)return i+n+o;{const c=`expecting at least one iteration which starts with one of these possible Token sequences:: - <${ce(e,l=>`[${ce(l,u=>Bs(u)).join(",")}]`).join(" ,")}>`;return i+c+o}}};Object.freeze(Ip);const ST={buildRuleNotFoundError(e,t){return"Invalid grammar, reference to a rule which is not defined: ->"+t.nonTerminalName+`<- -inside top level rule: ->`+e.name+"<-"}},di={buildDuplicateFoundError(e,t){function n(u){return u instanceof tt?u.terminalType.name:u instanceof Yt?u.nonTerminalName:""}const r=e.name,i=In(t),s=i.idx,o=Kn(i),a=n(i),c=s>0;let l=`->${o}${c?s:""}<- ${a?`with argument: ->${a}<-`:""} - appears more than once (${t.length} times) in the top level rule: ->${r}<-. - For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES - `;return l=l.replace(/[ \t]+/g," "),l=l.replace(/\s\s+/g,` -`),l},buildNamespaceConflictError(e){return`Namespace conflict found in grammar. -The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${e.name}>. -To resolve this make sure each Terminal and Non-Terminal names are unique -This is easy to accomplish by using the convention that Terminal names start with an uppercase letter -and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(e){const t=ce(e.prefixPath,i=>Bs(i)).join(", "),n=e.alternation.idx===0?"":e.alternation.idx;return`Ambiguous alternatives: <${e.ambiguityIndices.join(" ,")}> due to common lookahead prefix -in inside <${e.topLevelRule.name}> Rule, -<${t}> may appears as a prefix path in all these alternatives. -See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX -For Further details.`},buildAlternationAmbiguityError(e){const t=ce(e.prefixPath,i=>Bs(i)).join(", "),n=e.alternation.idx===0?"":e.alternation.idx;let r=`Ambiguous Alternatives Detected: <${e.ambiguityIndices.join(" ,")}> in inside <${e.topLevelRule.name}> Rule, -<${t}> may appears as a prefix path in all these alternatives. -`;return r=r+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES -For Further details.`,r},buildEmptyRepetitionError(e){let t=Kn(e.repetition);return e.repetition.idx!==0&&(t+=e.repetition.idx),`The repetition <${t}> within Rule <${e.topLevelRule.name}> can never consume any tokens. -This could lead to an infinite loop.`},buildTokenNameError(e){return"deprecated"},buildEmptyAlternationError(e){return`Ambiguous empty alternative: <${e.emptyChoiceIdx+1}> in inside <${e.topLevelRule.name}> Rule. -Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(e){return`An Alternation cannot have more than 256 alternatives: - inside <${e.topLevelRule.name}> Rule. - has ${e.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(e){const t=e.topLevelRule.name,n=ce(e.leftRecursionPath,s=>s.name),r=`${t} --> ${n.concat([t]).join(" --> ")}`;return`Left Recursion found in grammar. -rule: <${t}> can be invoked from itself (directly or indirectly) -without consuming any Tokens. The grammar path that causes this is: - ${r} - To fix this refactor your grammar to remove the left recursion. -see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(e){return"deprecated"},buildDuplicateRuleNameError(e){let t;return e.topLevelRule instanceof Hi?t=e.topLevelRule.name:t=e.topLevelRule,`Duplicate definition, rule: ->${t}<- is already defined in the grammar: ->${e.grammarName}<-`}};function AT(e,t){const n=new TT(e,t);return n.resolveRefs(),n.errors}class TT extends ui{constructor(t,n){super(),this.nameToTopRule=t,this.errMsgProvider=n,this.errors=[]}resolveRefs(){me(dt(this.nameToTopRule),t=>{this.currTopLevel=t,t.accept(this)})}visitNonTerminal(t){const n=this.nameToTopRule[t.nonTerminalName];if(n)t.referencedRule=n;else{const r=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,t);this.errors.push({message:r,type:jt.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:t.nonTerminalName})}}}class xT extends aa{constructor(t,n){super(),this.topProd=t,this.path=n,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=Ct(this.path.ruleStack).reverse(),this.occurrenceStack=Ct(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(t,n=[]){this.found||super.walk(t,n)}walkProdRef(t,n,r){if(t.referencedRule.name===this.nextProductionName&&t.idx===this.nextProductionOccurrence){const i=n.concat(r);this.updateExpectedNext(),this.walk(t.referencedRule,i)}}updateExpectedNext(){Ke(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}}class RT extends xT{constructor(t,n){super(t,n),this.path=n,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(t,n,r){if(this.isAtEndOfPath&&t.terminalType.name===this.nextTerminalName&&t.idx===this.nextTerminalOccurrence&&!this.found){const i=n.concat(r),s=new Qt({definition:i});this.possibleTokTypes=Ns(s),this.found=!0}}}class ba extends aa{constructor(t,n){super(),this.topRule=t,this.occurrence=n,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}}class IT extends ba{walkMany(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkMany(t,n,r)}}class Op extends ba{walkManySep(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkManySep(t,n,r)}}class OT extends ba{walkAtLeastOne(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOne(t,n,r)}}class Np extends ba{walkAtLeastOneSep(t,n,r){if(t.idx===this.occurrence){const i=In(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof tt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOneSep(t,n,r)}}function Bl(e,t,n=[]){n=Ct(n);let r=[],i=0;function s(a){return a.concat(Lt(e,i+1))}function o(a){const c=Bl(s(a),t,n);return r.concat(c)}for(;n.length{Ke(c.definition)===!1&&(r=o(c.definition))}),r;if(a instanceof tt)n.push(a.terminalType);else throw Error("non exhaustive match")}i++}return r.push({partialPath:n,suffixDef:Lt(e,i)}),r}function Cp(e,t,n,r){const i="EXIT_NONE_TERMINAL",s=[i],o="EXIT_ALTERNATIVE";let a=!1;const c=t.length,l=c-r-1,u=[],f=[];for(f.push({idx:-1,def:e,ruleStack:[],occurrenceStack:[]});!Ke(f);){const d=f.pop();if(d===o){a&&Wi(f).idx<=l&&f.pop();continue}const h=d.def,p=d.idx,m=d.ruleStack,b=d.occurrenceStack;if(Ke(h))continue;const _=h[0];if(_===i){const w={idx:p,def:Lt(h),ruleStack:Os(m),occurrenceStack:Os(b)};f.push(w)}else if(_ instanceof tt)if(p=0;w--){const v=_.definition[w],S={idx:p,def:v.definition.concat(Lt(h)),ruleStack:m,occurrenceStack:b};f.push(S),f.push(o)}else if(_ instanceof Qt)f.push({idx:p,def:_.definition.concat(Lt(h)),ruleStack:m,occurrenceStack:b});else if(_ instanceof Hi)f.push(NT(_,p,m,b));else throw Error("non exhaustive match")}return u}function NT(e,t,n,r){const i=Ct(n);i.push(e.name);const s=Ct(r);return s.push(1),{idx:t,def:e.definition,ruleStack:i,occurrenceStack:s}}var ot;(function(e){e[e.OPTION=0]="OPTION",e[e.REPETITION=1]="REPETITION",e[e.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",e[e.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",e[e.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",e[e.ALTERNATION=5]="ALTERNATION"})(ot||(ot={}));function Lp(e){if(e instanceof en||e==="Option")return ot.OPTION;if(e instanceof _t||e==="Repetition")return ot.REPETITION;if(e instanceof Hn||e==="RepetitionMandatory")return ot.REPETITION_MANDATORY;if(e instanceof Vn||e==="RepetitionMandatoryWithSeparator")return ot.REPETITION_MANDATORY_WITH_SEPARATOR;if(e instanceof Nn||e==="RepetitionWithSeparator")return ot.REPETITION_WITH_SEPARATOR;if(e instanceof Cn||e==="Alternation")return ot.ALTERNATION;throw Error("non exhaustive match")}function CT(e,t,n,r,i,s){const o=$l(e,t,n),a=Dp(o)?ya:Us;return s(o,r,a,i)}function LT(e,t,n,r,i,s){const o=jl(e,t,i,n),a=Dp(o)?ya:Us;return s(o[0],a,r)}function MT(e,t,n,r){const i=e.length,s=Rn(e,o=>Rn(o,a=>a.length===1));if(t)return function(o){const a=ce(o,c=>c.GATE);for(let c=0;csn(c)),a=Zt(o,(c,l,u)=>(me(l,f=>{pe(c,f.tokenTypeIdx)||(c[f.tokenTypeIdx]=u),me(f.categoryMatches,d=>{pe(c,d)||(c[d]=u)})}),c),{});return function(){const c=this.LA(1);return a[c.tokenTypeIdx]}}else return function(){for(let o=0;os.length===1),i=e.length;if(r&&!n){const s=sn(e);if(s.length===1&&Ke(s[0].categoryMatches)){const a=s[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===a}}else{const o=Zt(s,(a,c,l)=>(a[c.tokenTypeIdx]=!0,me(c.categoryMatches,u=>{a[u]=!0}),a),[]);return function(){const a=this.LA(1);return o[a.tokenTypeIdx]===!0}}}else return function(){e:for(let s=0;sBl([o],1)),r=Up(n.length),i=ce(n,o=>{const a={};return me(o,c=>{const l=Fl(c.partialPath);me(l,u=>{a[u]=!0})}),a});let s=n;for(let o=1;o<=t;o++){const a=s;s=Up(a.length);for(let c=0;c{const _=Fl(b.partialPath);me(_,w=>{i[c][w]=!0})})}}}}return r}function $l(e,t,n,r){const i=new Mp(e,ot.ALTERNATION,r);return t.accept(i),Pp(i.result,n)}function jl(e,t,n,r){const i=new Mp(e,n);t.accept(i);const s=i.result,a=new PT(t,e,n).startWalking(),c=new Qt({definition:s}),l=new Qt({definition:a});return Pp([c,l],r)}function zl(e,t){e:for(let n=0;n{const i=t[r];return n===i||i.categoryMatchesMap[n.tokenTypeIdx]})}function Dp(e){return Rn(e,t=>Rn(t,n=>Rn(n,r=>Ke(r.categoryMatches))))}function FT(e){const t=e.lookaheadStrategy.validate({rules:e.rules,tokenTypes:e.tokenTypes,grammarName:e.grammarName});return ce(t,n=>Object.assign({type:jt.CUSTOM_LOOKAHEAD_VALIDATION},n))}function $T(e,t,n,r){const i=yn(e,c=>jT(c,n)),s=QT(e,t,n),o=yn(e,c=>JT(c,n)),a=yn(e,c=>GT(c,e,r,n));return i.concat(s,o,a)}function jT(e,t){const n=new WT;e.accept(n);const r=n.allProductions,i=Zd(r,zT),s=On(i,a=>a.length>1);return ce(dt(s),a=>{const c=In(a),l=t.buildDuplicateFoundError(e,a),u=Kn(c),f={message:l,type:jt.DUPLICATE_PRODUCTIONS,ruleName:e.name,dslName:u,occurrence:c.idx},d=Bp(c);return d&&(f.parameter=d),f})}function zT(e){return`${Kn(e)}_#_${e.idx}_#_${Bp(e)}`}function Bp(e){return e instanceof tt?e.terminalType.name:e instanceof Yt?e.nonTerminalName:""}class WT extends ui{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(t){this.allProductions.push(t)}visitOption(t){this.allProductions.push(t)}visitRepetitionWithSeparator(t){this.allProductions.push(t)}visitRepetitionMandatory(t){this.allProductions.push(t)}visitRepetitionMandatoryWithSeparator(t){this.allProductions.push(t)}visitRepetition(t){this.allProductions.push(t)}visitAlternation(t){this.allProductions.push(t)}visitTerminal(t){this.allProductions.push(t)}}function GT(e,t,n,r){const i=[];if(Zt(t,(o,a)=>a.name===e.name?o+1:o,0)>1){const o=r.buildDuplicateRuleNameError({topLevelRule:e,grammarName:n});i.push({message:o,type:jt.DUPLICATE_RULE_NAME,ruleName:e.name})}return i}function HT(e,t,n){const r=[];let i;return $t(t,e)||(i=`Invalid rule override, rule: ->${e}<- cannot be overridden in the grammar: ->${n}<-as it is not defined in any of the super grammars `,r.push({message:i,type:jt.INVALID_RULE_OVERRIDE,ruleName:e})),r}function Fp(e,t,n,r=[]){const i=[],s=wa(t.definition);if(Ke(s))return[];{const o=e.name;$t(s,e)&&i.push({message:n.buildLeftRecursionError({topLevelRule:e,leftRecursionPath:r}),type:jt.LEFT_RECURSION,ruleName:o});const c=na(s,r.concat([e])),l=yn(c,u=>{const f=Ct(r);return f.push(u),Fp(e,u,n,f)});return i.concat(l)}}function wa(e){let t=[];if(Ke(e))return t;const n=In(e);if(n instanceof Yt)t.push(n.referencedRule);else if(n instanceof Qt||n instanceof en||n instanceof Hn||n instanceof Vn||n instanceof Nn||n instanceof _t)t=t.concat(wa(n.definition));else if(n instanceof Cn)t=sn(ce(n.definition,s=>wa(s.definition)));else if(!(n instanceof tt))throw Error("non exhaustive match");const r=oa(n),i=e.length>1;if(r&&i){const s=Lt(e);return t.concat(wa(s))}else return t}class Wl extends ui{constructor(){super(...arguments),this.alternations=[]}visitAlternation(t){this.alternations.push(t)}}function VT(e,t){const n=new Wl;e.accept(n);const r=n.alternations;return yn(r,s=>{const o=Os(s.definition);return yn(o,(a,c)=>{const l=Cp([a],[],Us,1);return Ke(l)?[{message:t.buildEmptyAlternationError({topLevelRule:e,alternation:s,emptyChoiceIdx:c}),type:jt.NONE_LAST_EMPTY_ALT,ruleName:e.name,occurrence:s.idx,alternative:c+1}]:[]})})}function KT(e,t,n){const r=new Wl;e.accept(r);let i=r.alternations;return i=ra(i,o=>o.ignoreAmbiguities===!0),yn(i,o=>{const a=o.idx,c=o.maxLookahead||t,l=$l(a,e,c,o),u=ZT(l,o,e,n),f=YT(l,o,e,n);return u.concat(f)})}class qT extends ui{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(t){this.allProductions.push(t)}visitRepetitionMandatory(t){this.allProductions.push(t)}visitRepetitionMandatoryWithSeparator(t){this.allProductions.push(t)}visitRepetition(t){this.allProductions.push(t)}}function JT(e,t){const n=new Wl;e.accept(n);const r=n.alternations;return yn(r,s=>s.definition.length>255?[{message:t.buildTooManyAlternativesError({topLevelRule:e,alternation:s}),type:jt.TOO_MANY_ALTS,ruleName:e.name,occurrence:s.idx}]:[])}function XT(e,t,n){const r=[];return me(e,i=>{const s=new qT;i.accept(s);const o=s.allProductions;me(o,a=>{const c=Lp(a),l=a.maxLookahead||t,u=a.idx,d=jl(u,i,c,l)[0];if(Ke(sn(d))){const h=n.buildEmptyRepetitionError({topLevelRule:i,repetition:a});r.push({message:h,type:jt.NO_NON_EMPTY_LOOKAHEAD,ruleName:i.name})}})}),r}function ZT(e,t,n,r){const i=[],s=Zt(e,(a,c,l)=>(t.definition[l].ignoreAmbiguities===!0||me(c,u=>{const f=[l];me(e,(d,h)=>{l!==h&&zl(d,u)&&t.definition[h].ignoreAmbiguities!==!0&&f.push(h)}),f.length>1&&!zl(i,u)&&(i.push(u),a.push({alts:f,path:u}))}),a),[]);return ce(s,a=>{const c=ce(a.alts,u=>u+1);return{message:r.buildAlternationAmbiguityError({topLevelRule:n,alternation:t,ambiguityIndices:c,prefixPath:a.path}),type:jt.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:t.idx,alternatives:a.alts}})}function YT(e,t,n,r){const i=Zt(e,(o,a,c)=>{const l=ce(a,u=>({idx:c,path:u}));return o.concat(l)},[]);return Is(yn(i,o=>{if(t.definition[o.idx].ignoreAmbiguities===!0)return[];const c=o.idx,l=o.path,u=gn(i,d=>t.definition[d.idx].ignoreAmbiguities!==!0&&d.idx{const h=[d.idx+1,c+1],p=t.idx===0?"":t.idx;return{message:r.buildAlternationPrefixAmbiguityError({topLevelRule:n,alternation:t,ambiguityIndices:h,prefixPath:d.path}),type:jt.AMBIGUOUS_PREFIX_ALTS,ruleName:n.name,occurrence:p,alternatives:h}})}))}function QT(e,t,n){const r=[],i=ce(t,s=>s.name);return me(e,s=>{const o=s.name;if($t(i,o)){const a=n.buildNamespaceConflictError(s);r.push({message:a,type:jt.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:o})}}),r}function ex(e){const t=Il(e,{errMsgProvider:ST}),n={};return me(e.rules,r=>{n[r.name]=r}),AT(n,t.errMsgProvider)}function tx(e){return e=Il(e,{errMsgProvider:di}),$T(e.rules,e.tokenTypes,e.errMsgProvider,e.grammarName)}const $p="MismatchedTokenException",jp="NoViableAltException",zp="EarlyExitException",Wp="NotAllInputParsedException",Gp=[$p,jp,zp,Wp];Object.freeze(Gp);function va(e){return $t(Gp,e.name)}class Ea extends Error{constructor(t,n){super(t),this.token=n,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class Hp extends Ea{constructor(t,n,r){super(t,n),this.previousToken=r,this.name=$p}}class nx extends Ea{constructor(t,n,r){super(t,n),this.previousToken=r,this.name=jp}}class rx extends Ea{constructor(t,n){super(t,n),this.name=Wp}}class ix extends Ea{constructor(t,n,r){super(t,n),this.previousToken=r,this.name=zp}}const Gl={},Vp="InRuleRecoveryException";class sx extends Error{constructor(t){super(t),this.name=Vp}}class ox{initRecoverable(t){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=pe(t,"recoveryEnabled")?t.recoveryEnabled:_r.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=ax)}getTokenToInsert(t){const n=_a(t,"",NaN,NaN,NaN,NaN,NaN,NaN);return n.isInsertedInRecovery=!0,n}canTokenTypeBeInsertedInRecovery(t){return!0}canTokenTypeBeDeletedInRecovery(t){return!0}tryInRepetitionRecovery(t,n,r,i){const s=this.findReSyncTokenType(),o=this.exportLexerState(),a=[];let c=!1;const l=this.LA(1);let u=this.LA(1);const f=()=>{const d=this.LA(0),h=this.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:l,previous:d,ruleName:this.getCurrRuleFullName()}),p=new Hp(h,l,this.LA(0));p.resyncedTokens=Os(a),this.SAVE_ERROR(p)};for(;!c;)if(this.tokenMatcher(u,i)){f();return}else if(r.call(this)){f(),t.apply(this,n);return}else this.tokenMatcher(u,s)?c=!0:(u=this.SKIP_TOKEN(),this.addToResyncTokens(u,a));this.importLexerState(o)}shouldInRepetitionRecoveryBeTried(t,n,r){return!(r===!1||this.tokenMatcher(this.LA(1),t)||this.isBackTracking()||this.canPerformInRuleRecovery(t,this.getFollowsForInRuleRecovery(t,n)))}getFollowsForInRuleRecovery(t,n){const r=this.getCurrentGrammarPath(t,n);return this.getNextPossibleTokenTypes(r)}tryInRuleRecovery(t,n){if(this.canRecoverWithSingleTokenInsertion(t,n))return this.getTokenToInsert(t);if(this.canRecoverWithSingleTokenDeletion(t)){const r=this.SKIP_TOKEN();return this.consumeToken(),r}throw new sx("sad sad panda")}canPerformInRuleRecovery(t,n){return this.canRecoverWithSingleTokenInsertion(t,n)||this.canRecoverWithSingleTokenDeletion(t)}canRecoverWithSingleTokenInsertion(t,n){if(!this.canTokenTypeBeInsertedInRecovery(t)||Ke(n))return!1;const r=this.LA(1);return Gi(n,s=>this.tokenMatcher(r,s))!==void 0}canRecoverWithSingleTokenDeletion(t){return this.canTokenTypeBeDeletedInRecovery(t)?this.tokenMatcher(this.LA(2),t):!1}isInCurrentRuleReSyncSet(t){const n=this.getCurrFollowKey(),r=this.getFollowSetFromFollowKey(n);return $t(r,t)}findReSyncTokenType(){const t=this.flattenFollowSet();let n=this.LA(1),r=2;for(;;){const i=Gi(t,s=>kT(n,s));if(i!==void 0)return i;n=this.LA(r),r++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return Gl;const t=this.getLastExplicitRuleShortName(),n=this.getLastExplicitRuleOccurrenceIndex(),r=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(t),idxInCallingRule:n,inRule:this.shortRuleNameToFullName(r)}}buildFullFollowKeyStack(){const t=this.RULE_STACK,n=this.RULE_OCCURRENCE_STACK;return ce(t,(r,i)=>i===0?Gl:{ruleName:this.shortRuleNameToFullName(r),idxInCallingRule:n[i],inRule:this.shortRuleNameToFullName(t[i-1])})}flattenFollowSet(){const t=ce(this.buildFullFollowKeyStack(),n=>this.getFollowSetFromFollowKey(n));return sn(t)}getFollowSetFromFollowKey(t){if(t===Gl)return[hi];const n=t.ruleName+t.idxInCallingRule+ip+t.inRule;return this.resyncFollows[n]}addToResyncTokens(t,n){return this.tokenMatcher(t,hi)||n.push(t),n}reSyncTo(t){const n=[];let r=this.LA(1);for(;this.tokenMatcher(r,t)===!1;)r=this.SKIP_TOKEN(),this.addToResyncTokens(r,n);return Os(n)}attemptInRepetitionRecovery(t,n,r,i,s,o,a){}getCurrentGrammarPath(t,n){const r=this.getHumanReadableRuleStack(),i=Ct(this.RULE_OCCURRENCE_STACK);return{ruleStack:r,occurrenceStack:i,lastTok:t,lastTokOccurrence:n}}getHumanReadableRuleStack(){return ce(this.RULE_STACK,t=>this.shortRuleNameToFullName(t))}}function ax(e,t,n,r,i,s,o){const a=this.getKeyForAutomaticLookahead(r,i);let c=this.firstAfterRepMap[a];if(c===void 0){const d=this.getCurrRuleFullName(),h=this.getGAstProductions()[d];c=new s(h,i).startWalking(),this.firstAfterRepMap[a]=c}let l=c.token,u=c.occurrence;const f=c.isEndOfRule;this.RULE_STACK.length===1&&f&&l===void 0&&(l=hi,u=1),!(l===void 0||u===void 0)&&this.shouldInRepetitionRecoveryBeTried(l,u,o)&&this.tryInRepetitionRecovery(e,t,n,l)}const cx=4,jr=8,Kp=1<Fp(n,n,di))}validateEmptyOrAlternatives(t){return yn(t,n=>VT(n,di))}validateAmbiguousAlternationAlternatives(t,n){return yn(t,r=>KT(r,n,di))}validateSomeNonEmptyLookaheadPath(t,n){return XT(t,n,di)}buildLookaheadForAlternation(t){return CT(t.prodOccurrence,t.rule,t.maxLookahead,t.hasPredicates,t.dynamicTokensEnabled,MT)}buildLookaheadForOptional(t){return LT(t.prodOccurrence,t.rule,t.maxLookahead,t.dynamicTokensEnabled,Lp(t.prodType),UT)}}class ux{initLooksAhead(t){this.dynamicTokensEnabled=pe(t,"dynamicTokensEnabled")?t.dynamicTokensEnabled:_r.dynamicTokensEnabled,this.maxLookahead=pe(t,"maxLookahead")?t.maxLookahead:_r.maxLookahead,this.lookaheadStrategy=pe(t,"lookaheadStrategy")?t.lookaheadStrategy:new lx({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(t){me(t,n=>{this.TRACE_INIT(`${n.name} Rule Lookahead`,()=>{const{alternation:r,repetition:i,option:s,repetitionMandatory:o,repetitionMandatoryWithSeparator:a,repetitionWithSeparator:c}=hx(n);me(r,l=>{const u=l.idx===0?"":l.idx;this.TRACE_INIT(`${Kn(l)}${u}`,()=>{const f=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:l.idx,rule:n,maxLookahead:l.maxLookahead||this.maxLookahead,hasPredicates:l.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),d=ql(this.fullRuleNameToShort[n.name],Kp,l.idx);this.setLaFuncCache(d,f)})}),me(i,l=>{this.computeLookaheadFunc(n,l.idx,Hl,"Repetition",l.maxLookahead,Kn(l))}),me(s,l=>{this.computeLookaheadFunc(n,l.idx,qp,"Option",l.maxLookahead,Kn(l))}),me(o,l=>{this.computeLookaheadFunc(n,l.idx,Vl,"RepetitionMandatory",l.maxLookahead,Kn(l))}),me(a,l=>{this.computeLookaheadFunc(n,l.idx,ka,"RepetitionMandatoryWithSeparator",l.maxLookahead,Kn(l))}),me(c,l=>{this.computeLookaheadFunc(n,l.idx,Kl,"RepetitionWithSeparator",l.maxLookahead,Kn(l))})})})}computeLookaheadFunc(t,n,r,i,s,o){this.TRACE_INIT(`${o}${n===0?"":n}`,()=>{const a=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:n,rule:t,maxLookahead:s||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:i}),c=ql(this.fullRuleNameToShort[t.name],r,n);this.setLaFuncCache(c,a)})}getKeyForAutomaticLookahead(t,n){const r=this.getLastExplicitRuleShortName();return ql(r,t,n)}getLaFuncFromCache(t){return this.lookAheadFuncsCache.get(t)}setLaFuncCache(t,n){this.lookAheadFuncsCache.set(t,n)}}class fx extends ui{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(t){this.dslMethods.option.push(t)}visitRepetitionWithSeparator(t){this.dslMethods.repetitionWithSeparator.push(t)}visitRepetitionMandatory(t){this.dslMethods.repetitionMandatory.push(t)}visitRepetitionMandatoryWithSeparator(t){this.dslMethods.repetitionMandatoryWithSeparator.push(t)}visitRepetition(t){this.dslMethods.repetition.push(t)}visitAlternation(t){this.dslMethods.alternation.push(t)}}const Sa=new fx;function hx(e){Sa.reset(),e.accept(Sa);const t=Sa.dslMethods;return Sa.reset(),t}function Jp(e,t){isNaN(e.startOffset)===!0?(e.startOffset=t.startOffset,e.endOffset=t.endOffset):e.endOffseto.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: - ${s.join(` - -`).replace(/\n/g,` - `)}`)}}};return n.prototype=r,n.prototype.constructor=n,n._RULE_NAMES=t,n}function _x(e,t,n){const r=function(){};Zp(r,e+"BaseSemanticsWithDefaults");const i=Object.create(n.prototype);return me(t,s=>{i[s]=gx}),r.prototype=i,r.prototype.constructor=r,r}var Jl;(function(e){e[e.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",e[e.MISSING_METHOD=1]="MISSING_METHOD"})(Jl||(Jl={}));function bx(e,t){return wx(e,t)}function wx(e,t){const n=gn(t,i=>dr(e[i])===!1),r=ce(n,i=>({msg:`Missing visitor method: <${i}> on ${e.constructor.name} CST Visitor.`,type:Jl.MISSING_METHOD,methodName:i}));return Is(r)}class vx{initTreeBuilder(t){if(this.CST_STACK=[],this.outputCst=t.outputCst,this.nodeLocationTracking=pe(t,"nodeLocationTracking")?t.nodeLocationTracking:_r.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=yt,this.cstFinallyStateUpdate=yt,this.cstPostTerminal=yt,this.cstPostNonTerminal=yt,this.cstPostRule=yt;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Xp,this.setNodeLocationFromNode=Xp,this.cstPostRule=yt,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=yt,this.setNodeLocationFromNode=yt,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Jp,this.setNodeLocationFromNode=Jp,this.cstPostRule=yt,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=yt,this.setNodeLocationFromNode=yt,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=yt,this.setNodeLocationFromNode=yt,this.cstPostRule=yt,this.setInitialNodeLocation=yt;else throw Error(`Invalid config option: "${t.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(t){t.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(t){t.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(t){t.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(t){const n=this.LA(1);t.location={startOffset:n.startOffset,startLine:n.startLine,startColumn:n.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(t){const n={name:t,children:Object.create(null)};this.setInitialNodeLocation(n),this.CST_STACK.push(n)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(t){const n=this.LA(0),r=t.location;r.startOffset<=n.startOffset?(r.endOffset=n.endOffset,r.endLine=n.endLine,r.endColumn=n.endColumn):(r.startOffset=NaN,r.startLine=NaN,r.startColumn=NaN)}cstPostRuleOnlyOffset(t){const n=this.LA(0),r=t.location;r.startOffset<=n.startOffset?r.endOffset=n.endOffset:r.startOffset=NaN}cstPostTerminal(t,n){const r=this.CST_STACK[this.CST_STACK.length-1];dx(r,n,t),this.setNodeLocationFromToken(r.location,n)}cstPostNonTerminal(t,n){const r=this.CST_STACK[this.CST_STACK.length-1];px(r,n,t),this.setNodeLocationFromNode(r.location,t.location)}getBaseCstVisitorConstructor(){if(yr(this.baseCstVisitorConstructor)){const t=yx(this.className,pn(this.gastProductionsCache));return this.baseCstVisitorConstructor=t,t}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(yr(this.baseCstVisitorWithDefaultsConstructor)){const t=_x(this.className,pn(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=t,t}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){const t=this.RULE_STACK;return t[t.length-1]}getPreviousExplicitRuleShortName(){const t=this.RULE_STACK;return t[t.length-2]}getLastExplicitRuleOccurrenceIndex(){const t=this.RULE_OCCURRENCE_STACK;return t[t.length-1]}}class Ex{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(t){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=t,this.tokVectorLength=t.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):xa}LA(t){const n=this.currIdx+t;return n<0||this.tokVectorLength<=n?xa:this.tokVector[n]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(t){this.currIdx=t}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}}class kx{ACTION(t){return t.call(this)}consume(t,n,r){return this.consumeInternal(n,t,r)}subrule(t,n,r){return this.subruleInternal(n,t,r)}option(t,n){return this.optionInternal(n,t)}or(t,n){return this.orInternal(n,t)}many(t,n){return this.manyInternal(t,n)}atLeastOne(t,n){return this.atLeastOneInternal(t,n)}CONSUME(t,n){return this.consumeInternal(t,0,n)}CONSUME1(t,n){return this.consumeInternal(t,1,n)}CONSUME2(t,n){return this.consumeInternal(t,2,n)}CONSUME3(t,n){return this.consumeInternal(t,3,n)}CONSUME4(t,n){return this.consumeInternal(t,4,n)}CONSUME5(t,n){return this.consumeInternal(t,5,n)}CONSUME6(t,n){return this.consumeInternal(t,6,n)}CONSUME7(t,n){return this.consumeInternal(t,7,n)}CONSUME8(t,n){return this.consumeInternal(t,8,n)}CONSUME9(t,n){return this.consumeInternal(t,9,n)}SUBRULE(t,n){return this.subruleInternal(t,0,n)}SUBRULE1(t,n){return this.subruleInternal(t,1,n)}SUBRULE2(t,n){return this.subruleInternal(t,2,n)}SUBRULE3(t,n){return this.subruleInternal(t,3,n)}SUBRULE4(t,n){return this.subruleInternal(t,4,n)}SUBRULE5(t,n){return this.subruleInternal(t,5,n)}SUBRULE6(t,n){return this.subruleInternal(t,6,n)}SUBRULE7(t,n){return this.subruleInternal(t,7,n)}SUBRULE8(t,n){return this.subruleInternal(t,8,n)}SUBRULE9(t,n){return this.subruleInternal(t,9,n)}OPTION(t){return this.optionInternal(t,0)}OPTION1(t){return this.optionInternal(t,1)}OPTION2(t){return this.optionInternal(t,2)}OPTION3(t){return this.optionInternal(t,3)}OPTION4(t){return this.optionInternal(t,4)}OPTION5(t){return this.optionInternal(t,5)}OPTION6(t){return this.optionInternal(t,6)}OPTION7(t){return this.optionInternal(t,7)}OPTION8(t){return this.optionInternal(t,8)}OPTION9(t){return this.optionInternal(t,9)}OR(t){return this.orInternal(t,0)}OR1(t){return this.orInternal(t,1)}OR2(t){return this.orInternal(t,2)}OR3(t){return this.orInternal(t,3)}OR4(t){return this.orInternal(t,4)}OR5(t){return this.orInternal(t,5)}OR6(t){return this.orInternal(t,6)}OR7(t){return this.orInternal(t,7)}OR8(t){return this.orInternal(t,8)}OR9(t){return this.orInternal(t,9)}MANY(t){this.manyInternal(0,t)}MANY1(t){this.manyInternal(1,t)}MANY2(t){this.manyInternal(2,t)}MANY3(t){this.manyInternal(3,t)}MANY4(t){this.manyInternal(4,t)}MANY5(t){this.manyInternal(5,t)}MANY6(t){this.manyInternal(6,t)}MANY7(t){this.manyInternal(7,t)}MANY8(t){this.manyInternal(8,t)}MANY9(t){this.manyInternal(9,t)}MANY_SEP(t){this.manySepFirstInternal(0,t)}MANY_SEP1(t){this.manySepFirstInternal(1,t)}MANY_SEP2(t){this.manySepFirstInternal(2,t)}MANY_SEP3(t){this.manySepFirstInternal(3,t)}MANY_SEP4(t){this.manySepFirstInternal(4,t)}MANY_SEP5(t){this.manySepFirstInternal(5,t)}MANY_SEP6(t){this.manySepFirstInternal(6,t)}MANY_SEP7(t){this.manySepFirstInternal(7,t)}MANY_SEP8(t){this.manySepFirstInternal(8,t)}MANY_SEP9(t){this.manySepFirstInternal(9,t)}AT_LEAST_ONE(t){this.atLeastOneInternal(0,t)}AT_LEAST_ONE1(t){return this.atLeastOneInternal(1,t)}AT_LEAST_ONE2(t){this.atLeastOneInternal(2,t)}AT_LEAST_ONE3(t){this.atLeastOneInternal(3,t)}AT_LEAST_ONE4(t){this.atLeastOneInternal(4,t)}AT_LEAST_ONE5(t){this.atLeastOneInternal(5,t)}AT_LEAST_ONE6(t){this.atLeastOneInternal(6,t)}AT_LEAST_ONE7(t){this.atLeastOneInternal(7,t)}AT_LEAST_ONE8(t){this.atLeastOneInternal(8,t)}AT_LEAST_ONE9(t){this.atLeastOneInternal(9,t)}AT_LEAST_ONE_SEP(t){this.atLeastOneSepFirstInternal(0,t)}AT_LEAST_ONE_SEP1(t){this.atLeastOneSepFirstInternal(1,t)}AT_LEAST_ONE_SEP2(t){this.atLeastOneSepFirstInternal(2,t)}AT_LEAST_ONE_SEP3(t){this.atLeastOneSepFirstInternal(3,t)}AT_LEAST_ONE_SEP4(t){this.atLeastOneSepFirstInternal(4,t)}AT_LEAST_ONE_SEP5(t){this.atLeastOneSepFirstInternal(5,t)}AT_LEAST_ONE_SEP6(t){this.atLeastOneSepFirstInternal(6,t)}AT_LEAST_ONE_SEP7(t){this.atLeastOneSepFirstInternal(7,t)}AT_LEAST_ONE_SEP8(t){this.atLeastOneSepFirstInternal(8,t)}AT_LEAST_ONE_SEP9(t){this.atLeastOneSepFirstInternal(9,t)}RULE(t,n,r=Ra){if($t(this.definedRulesNames,t)){const o={message:di.buildDuplicateRuleNameError({topLevelRule:t,grammarName:this.className}),type:jt.DUPLICATE_RULE_NAME,ruleName:t};this.definitionErrors.push(o)}this.definedRulesNames.push(t);const i=this.defineRule(t,n,r);return this[t]=i,i}OVERRIDE_RULE(t,n,r=Ra){const i=HT(t,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(i);const s=this.defineRule(t,n,r);return this[t]=s,s}BACKTRACK(t,n){return function(){this.isBackTrackingStack.push(1);const r=this.saveRecogState();try{return t.apply(this,n),!0}catch(i){if(va(i))return!1;throw i}finally{this.reloadRecogState(r),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return AA(dt(this.gastProductionsCache))}}class Sx{initRecognizerEngine(t,n){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=ya,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},pe(n,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 - For Further details.`);if(Le(t)){if(Ke(t))throw Error(`A Token Vocabulary cannot be empty. - Note that the first argument for the parser constructor - is no longer a Token vector (since v4.0).`);if(typeof t[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 - For Further details.`)}if(Le(t))this.tokensMap=Zt(t,(s,o)=>(s[o.name]=o,s),{});else if(pe(t,"modes")&&Rn(sn(dt(t.modes)),bT)){const s=sn(dt(t.modes)),o=ia(s);this.tokensMap=Zt(o,(a,c)=>(a[c.name]=c,a),{})}else if(dn(t))this.tokensMap=Ct(t);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=hi;const r=pe(t,"modes")?sn(dt(t.modes)):dt(t),i=Rn(r,s=>Ke(s.categoryMatches));this.tokenMatcher=i?ya:Us,Ps(dt(this.tokensMap))}defineRule(t,n,r){if(this.selfAnalysisDone)throw Error(`Grammar rule <${t}> may not be defined after the 'performSelfAnalysis' method has been called' -Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);const i=pe(r,"resyncEnabled")?r.resyncEnabled:Ra.resyncEnabled,s=pe(r,"recoveryValueFunc")?r.recoveryValueFunc:Ra.recoveryValueFunc,o=this.ruleShortNameIdx<o.call(this)&&a.call(this)}}else s=t;if(i.call(this)===!0)return s.call(this)}atLeastOneInternal(t,n){const r=this.getKeyForAutomaticLookahead(Vl,t);return this.atLeastOneInternalLogic(t,n,r)}atLeastOneInternalLogic(t,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const o=n.GATE;if(o!==void 0){const a=i;i=()=>o.call(this)&&a.call(this)}}else s=n;if(i.call(this)===!0){let o=this.doSingleRepetition(s);for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s)}else throw this.raiseEarlyExitException(t,ot.REPETITION_MANDATORY,n.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[t,n],i,Vl,t,OT)}atLeastOneSepFirstInternal(t,n){const r=this.getKeyForAutomaticLookahead(ka,t);this.atLeastOneSepFirstInternalLogic(t,n,r)}atLeastOneSepFirstInternalLogic(t,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,s,a,i,Np],a,ka,t,Np)}else throw this.raiseEarlyExitException(t,ot.REPETITION_MANDATORY_WITH_SEPARATOR,n.ERR_MSG)}manyInternal(t,n){const r=this.getKeyForAutomaticLookahead(Hl,t);return this.manyInternalLogic(t,n,r)}manyInternalLogic(t,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const a=n.GATE;if(a!==void 0){const c=i;i=()=>a.call(this)&&c.call(this)}}else s=n;let o=!0;for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s);this.attemptInRepetitionRecovery(this.manyInternal,[t,n],i,Hl,t,IT,o)}manySepFirstInternal(t,n){const r=this.getKeyForAutomaticLookahead(Kl,t);this.manySepFirstInternalLogic(t,n,r)}manySepFirstInternalLogic(t,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,s,a,i,Op],a,Kl,t,Op)}}repetitionSepSecondInternal(t,n,r,i,s){for(;r();)this.CONSUME(n),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,n,r,i,s],r,ka,t,s)}doSingleRepetition(t){const n=this.getLexerPosition();return t.call(this),this.getLexerPosition()>n}orInternal(t,n){const r=this.getKeyForAutomaticLookahead(Kp,n),i=Le(t)?t:t.DEF,o=this.getLaFuncFromCache(r).call(this,i);if(o!==void 0)return i[o].ALT.call(this);this.raiseNoAltException(n,t.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){const t=this.LA(1),n=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:t,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new rx(n,t))}}subruleInternal(t,n,r){let i;try{const s=r!==void 0?r.ARGS:void 0;return this.subruleIdx=n,i=t.apply(this,s),this.cstPostNonTerminal(i,r!==void 0&&r.LABEL!==void 0?r.LABEL:t.ruleName),i}catch(s){throw this.subruleInternalError(s,r,t.ruleName)}}subruleInternalError(t,n,r){throw va(t)&&t.partialCstResult!==void 0&&(this.cstPostNonTerminal(t.partialCstResult,n!==void 0&&n.LABEL!==void 0?n.LABEL:r),delete t.partialCstResult),t}consumeInternal(t,n,r){let i;try{const s=this.LA(1);this.tokenMatcher(s,t)===!0?(this.consumeToken(),i=s):this.consumeInternalError(t,s,r)}catch(s){i=this.consumeInternalRecovery(t,n,s)}return this.cstPostTerminal(r!==void 0&&r.LABEL!==void 0?r.LABEL:t.name,i),i}consumeInternalError(t,n,r){let i;const s=this.LA(0);throw r!==void 0&&r.ERR_MSG?i=r.ERR_MSG:i=this.errorMessageProvider.buildMismatchTokenMessage({expected:t,actual:n,previous:s,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new Hp(i,n,s))}consumeInternalRecovery(t,n,r){if(this.recoveryEnabled&&r.name==="MismatchedTokenException"&&!this.isBackTracking()){const i=this.getFollowsForInRuleRecovery(t,n);try{return this.tryInRuleRecovery(t,i)}catch(s){throw s.name===Vp?r:s}}else throw r}saveRecogState(){const t=this.errors,n=Ct(this.RULE_STACK);return{errors:t,lexerState:this.exportLexerState(),RULE_STACK:n,CST_STACK:this.CST_STACK}}reloadRecogState(t){this.errors=t.errors,this.importLexerState(t.lexerState),this.RULE_STACK=t.RULE_STACK}ruleInvocationStateUpdate(t,n,r){this.RULE_OCCURRENCE_STACK.push(r),this.RULE_STACK.push(t),this.cstInvocationStateUpdate(n)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){const t=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[t]}shortRuleNameToFullName(t){return this.shortRuleNameToFull[t]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),hi)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}}class Ax{initErrorHandler(t){this._errors=[],this.errorMessageProvider=pe(t,"errorMessageProvider")?t.errorMessageProvider:_r.errorMessageProvider}SAVE_ERROR(t){if(va(t))return t.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:Ct(this.RULE_OCCURRENCE_STACK)},this._errors.push(t),t;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return Ct(this._errors)}set errors(t){this._errors=t}raiseEarlyExitException(t,n,r){const i=this.getCurrRuleFullName(),s=this.getGAstProductions()[i],a=jl(t,s,n,this.maxLookahead)[0],c=[];for(let u=1;u<=this.maxLookahead;u++)c.push(this.LA(u));const l=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:c,previous:this.LA(0),customUserDescription:r,ruleName:i});throw this.SAVE_ERROR(new ix(l,this.LA(1),this.LA(0)))}raiseNoAltException(t,n){const r=this.getCurrRuleFullName(),i=this.getGAstProductions()[r],s=$l(t,i,this.maxLookahead),o=[];for(let l=1;l<=this.maxLookahead;l++)o.push(this.LA(l));const a=this.LA(0),c=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:s,actual:o,previous:a,customUserDescription:n,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new nx(c,this.LA(1),a))}}class Tx{initContentAssist(){}computeContentAssist(t,n){const r=this.gastProductionsCache[t];if(yr(r))throw Error(`Rule ->${t}<- does not exist in this grammar.`);return Cp([r],n,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(t){const n=In(t.ruleStack),i=this.getGAstProductions()[n];return new RT(i,t).startWalking()}}const Aa={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(Aa);const Yp=!0,Qp=Math.pow(2,jr)-1,em=on({name:"RECORDING_PHASE_TOKEN",pattern:bt.NA});Ps([em]);const tm=_a(em,`This IToken indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(tm);const xx={name:`This CSTNode indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}};class Rx{initGastRecorder(t){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let t=0;t<10;t++){const n=t>0?t:"";this[`CONSUME${n}`]=function(r,i){return this.consumeInternalRecord(r,t,i)},this[`SUBRULE${n}`]=function(r,i){return this.subruleInternalRecord(r,t,i)},this[`OPTION${n}`]=function(r){return this.optionInternalRecord(r,t)},this[`OR${n}`]=function(r){return this.orInternalRecord(r,t)},this[`MANY${n}`]=function(r){this.manyInternalRecord(t,r)},this[`MANY_SEP${n}`]=function(r){this.manySepFirstInternalRecord(t,r)},this[`AT_LEAST_ONE${n}`]=function(r){this.atLeastOneInternalRecord(t,r)},this[`AT_LEAST_ONE_SEP${n}`]=function(r){this.atLeastOneSepFirstInternalRecord(t,r)}}this.consume=function(t,n,r){return this.consumeInternalRecord(n,t,r)},this.subrule=function(t,n,r){return this.subruleInternalRecord(n,t,r)},this.option=function(t,n){return this.optionInternalRecord(n,t)},this.or=function(t,n){return this.orInternalRecord(n,t)},this.many=function(t,n){this.manyInternalRecord(t,n)},this.atLeastOne=function(t,n){this.atLeastOneInternalRecord(t,n)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{const t=this;for(let n=0;n<10;n++){const r=n>0?n:"";delete t[`CONSUME${r}`],delete t[`SUBRULE${r}`],delete t[`OPTION${r}`],delete t[`OR${r}`],delete t[`MANY${r}`],delete t[`MANY_SEP${r}`],delete t[`AT_LEAST_ONE${r}`],delete t[`AT_LEAST_ONE_SEP${r}`]}delete t.consume,delete t.subrule,delete t.option,delete t.or,delete t.many,delete t.atLeastOne,delete t.ACTION,delete t.BACKTRACK,delete t.LA})}ACTION_RECORD(t){}BACKTRACK_RECORD(t,n){return()=>!0}LA_RECORD(t){return xa}topLevelRuleRecord(t,n){try{const r=new Hi({definition:[],name:t});return r.name=t,this.recordingProdStack.push(r),n.call(this),this.recordingProdStack.pop(),r}catch(r){if(r.KNOWN_RECORDER_ERROR!==!0)try{r.message=r.message+` - This error was thrown during the "grammar recording phase" For more info see: - https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw r}throw r}}optionInternalRecord(t,n){return Fs.call(this,en,t,n)}atLeastOneInternalRecord(t,n){Fs.call(this,Hn,n,t)}atLeastOneSepFirstInternalRecord(t,n){Fs.call(this,Vn,n,t,Yp)}manyInternalRecord(t,n){Fs.call(this,_t,n,t)}manySepFirstInternalRecord(t,n){Fs.call(this,Nn,n,t,Yp)}orInternalRecord(t,n){return Ix.call(this,t,n)}subruleInternalRecord(t,n,r){if(Ta(n),!t||pe(t,"ruleName")===!1){const a=new Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(t)}> - inside top level rule: <${this.recordingProdStack[0].name}>`);throw a.KNOWN_RECORDER_ERROR=!0,a}const i=Wi(this.recordingProdStack),s=t.ruleName,o=new Yt({idx:n,nonTerminalName:s,label:r==null?void 0:r.LABEL,referencedRule:void 0});return i.definition.push(o),this.outputCst?xx:Aa}consumeInternalRecord(t,n,r){if(Ta(n),!_p(t)){const o=new Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(t)}> - inside top level rule: <${this.recordingProdStack[0].name}>`);throw o.KNOWN_RECORDER_ERROR=!0,o}const i=Wi(this.recordingProdStack),s=new tt({idx:n,terminalType:t,label:r==null?void 0:r.LABEL});return i.definition.push(s),tm}}function Fs(e,t,n,r=!1){Ta(n);const i=Wi(this.recordingProdStack),s=dr(t)?t:t.DEF,o=new e({definition:[],idx:n});return r&&(o.separator=t.SEP),pe(t,"MAX_LOOKAHEAD")&&(o.maxLookahead=t.MAX_LOOKAHEAD),this.recordingProdStack.push(o),s.call(this),i.definition.push(o),this.recordingProdStack.pop(),Aa}function Ix(e,t){Ta(t);const n=Wi(this.recordingProdStack),r=Le(e)===!1,i=r===!1?e:e.DEF,s=new Cn({definition:[],idx:t,ignoreAmbiguities:r&&e.IGNORE_AMBIGUITIES===!0});pe(e,"MAX_LOOKAHEAD")&&(s.maxLookahead=e.MAX_LOOKAHEAD);const o=Ol(i,a=>dr(a.GATE));return s.hasPredicates=o,n.definition.push(s),me(i,a=>{const c=new Qt({definition:[]});s.definition.push(c),pe(a,"IGNORE_AMBIGUITIES")?c.ignoreAmbiguities=a.IGNORE_AMBIGUITIES:pe(a,"GATE")&&(c.ignoreAmbiguities=!0),this.recordingProdStack.push(c),a.ALT.call(this),this.recordingProdStack.pop()}),Aa}function nm(e){return e===0?"":`${e}`}function Ta(e){if(e<0||e>Qp){const t=new Error(`Invalid DSL Method idx value: <${e}> - Idx value must be a none negative value smaller than ${Qp+1}`);throw t.KNOWN_RECORDER_ERROR=!0,t}}class Ox{initPerformanceTracer(t){if(pe(t,"traceInitPerf")){const n=t.traceInitPerf,r=typeof n=="number";this.traceInitMaxIdent=r?n:1/0,this.traceInitPerf=r?n>0:n}else this.traceInitMaxIdent=0,this.traceInitPerf=_r.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(t,n){if(this.traceInitPerf===!0){this.traceInitIndent++;const r=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${t}>`);const{time:i,value:s}=tp(n),o=i>10?console.warn:console.log;return this.traceInitIndent time: ${i}ms`),this.traceInitIndent--,s}else return n()}}function Nx(e,t){t.forEach(n=>{const r=n.prototype;Object.getOwnPropertyNames(r).forEach(i=>{if(i==="constructor")return;const s=Object.getOwnPropertyDescriptor(r,i);s&&(s.get||s.set)?Object.defineProperty(e.prototype,i,s):e.prototype[i]=n.prototype[i]})})}const xa=_a(hi,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(xa);const _r=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:Ip,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),Ra=Object.freeze({recoveryValueFunc:()=>{},resyncEnabled:!0});var jt;(function(e){e[e.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",e[e.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",e[e.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",e[e.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",e[e.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",e[e.LEFT_RECURSION=5]="LEFT_RECURSION",e[e.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",e[e.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",e[e.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",e[e.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",e[e.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",e[e.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",e[e.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",e[e.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(jt||(jt={}));class $s{static performSelfAnalysis(t){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let t;this.selfAnalysisDone=!0;const n=this.className;this.TRACE_INIT("toFastProps",()=>{np(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),me(this.definedRulesNames,i=>{const o=this[i].originalGrammarAction;let a;this.TRACE_INIT(`${i} Rule`,()=>{a=this.topLevelRuleRecord(i,o)}),this.gastProductionsCache[i]=a})}finally{this.disableRecording()}});let r=[];if(this.TRACE_INIT("Grammar Resolving",()=>{r=ex({rules:dt(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(r)}),this.TRACE_INIT("Grammar Validations",()=>{if(Ke(r)&&this.skipValidations===!1){const i=tx({rules:dt(this.gastProductionsCache),tokenTypes:dt(this.tokensMap),errMsgProvider:di,grammarName:n}),s=FT({lookaheadStrategy:this.lookaheadStrategy,rules:dt(this.gastProductionsCache),tokenTypes:dt(this.tokensMap),grammarName:n});this.definitionErrors=this.definitionErrors.concat(i,s)}}),Ke(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{const i=CA(dt(this.gastProductionsCache));this.resyncFollows=i}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var i,s;(s=(i=this.lookaheadStrategy).initialize)===null||s===void 0||s.call(i,{rules:dt(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(dt(this.gastProductionsCache))})),!$s.DEFER_DEFINITION_ERRORS_HANDLING&&!Ke(this.definitionErrors))throw t=ce(this.definitionErrors,i=>i.message),new Error(`Parser Definition Errors detected: - ${t.join(` -------------------------------- -`)}`)})}constructor(t,n){this.definitionErrors=[],this.selfAnalysisDone=!1;const r=this;if(r.initErrorHandler(n),r.initLexerAdapter(),r.initLooksAhead(n),r.initRecognizerEngine(t,n),r.initRecoverable(n),r.initTreeBuilder(n),r.initContentAssist(),r.initGastRecorder(n),r.initPerformanceTracer(n),pe(n,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. - Please use the flag on the relevant DSL method instead. - See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES - For further details.`);this.skipValidations=pe(n,"skipValidations")?n.skipValidations:_r.skipValidations}}$s.DEFER_DEFINITION_ERRORS_HANDLING=!1,Nx($s,[ox,ux,vx,Ex,Sx,kx,Ax,Tx,Rx,Ox]);class Cx extends $s{constructor(t,n=_r){const r=Ct(n);r.outputCst=!0,super(t,r)}}function Lx(e){const t=new Mx,n=dt(e);return ce(n,r=>t.visitRule(r))}class Mx extends ui{visitRule(t){const n=this.visitEach(t.definition),r=Zd(n,s=>s.propertyName),i=ce(r,(s,o)=>{const a=!Ol(s,l=>!l.canBeNull);let c=s[0].type;return s.length>1&&(c=ce(s,l=>l.type)),{name:o,type:c,optional:a}});return{name:t.name,properties:i}}visitAlternative(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitOption(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitRepetition(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitRepetitionMandatory(t){return this.visitEach(t.definition)}visitRepetitionMandatoryWithSeparator(t){return this.visitEach(t.definition).concat({propertyName:t.separator.name,canBeNull:!0,type:Ia(t.separator)})}visitRepetitionWithSeparator(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0}).concat({propertyName:t.separator.name,canBeNull:!0,type:Ia(t.separator)})}visitAlternation(t){return this.visitEachAndOverrideWith(t.definition,{canBeNull:!0})}visitTerminal(t){return[{propertyName:t.label||t.terminalType.name,canBeNull:!1,type:Ia(t)}]}visitNonTerminal(t){return[{propertyName:t.label||t.nonTerminalName,canBeNull:!1,type:Ia(t)}]}visitEachAndOverrideWith(t,n){return ce(this.visitEach(t),r=>Jt({},r,n))}visitEach(t){return sn(ce(t,n=>this.visit(n)))}}function Ia(e){return e instanceof Yt?{kind:"rule",name:e.referencedRule.name}:{kind:"token"}}function Ux(e,t){let n=[];return n=n.concat('import type { CstNode, ICstVisitor, IToken } from "chevrotain";'),n=n.concat(sn(ce(e,r=>Px(r)))),t.includeVisitorInterface&&(n=n.concat($x(t.visitorInterfaceName,e))),n.join(` - -`)+` -`}function Px(e){const t=Dx(e),n=Bx(e);return[t,n]}function Dx(e){const t=im(e.name),n=Xl(e.name);return`export interface ${t} extends CstNode { - name: "${e.name}"; - children: ${n}; -}`}function Bx(e){return`export type ${Xl(e.name)} = { - ${ce(e.properties,n=>Fx(n)).join(` - `)} -};`}function Fx(e){const t=zx(e.type);return`${e.name}${e.optional?"?":""}: ${t}[];`}function $x(e,t){return`export interface ${e} extends ICstVisitor { - ${ce(t,n=>jx(n)).join(` - `)} -}`}function jx(e){const t=Xl(e.name);return`${e.name}(children: ${t}, param?: IN): OUT;`}function zx(e){if(Le(e)){const t=ia(ce(e,r=>rm(r)));return"("+Zt(t,(r,i)=>r+" | "+i)+")"}else return rm(e)}function rm(e){return e.kind==="token"?"IToken":im(e.name)}function im(e){return bd(e)+"CstNode"}function Xl(e){return bd(e)+"CstChildren"}const Wx={includeVisitorInterface:!0,visitorInterfaceName:"ICstNodeVisitor"};function Gx(e,t){const n=Object.assign(Object.assign({},Wx),t),r=Lx(e);return Ux(r,n)}const qn=!!JSON.parse("false"),Hx=!!JSON.parse("false");JSON.parse("false");const Vx=!!JSON.parse("false");JSON.parse("false"),JSON.parse("false");const Zl=el(32,126).map(e=>String.fromCharCode(e));function Te(e){return on({...e,name:`token_${e.name}`})}function _n(e,t=!1){return Te(t?{name:e,pattern:new RegExp(e.toLowerCase(),"i"),longer_alt:zt,group:bt.SKIPPED}:{name:e,pattern:new RegExp(e.toLowerCase(),"i"),longer_alt:zt})}const js=Te({name:"newline",line_breaks:!0,start_chars_hint:[` -`,"\r"],pattern:/\n|\r\n?/}),Kx=Te({name:"whitespace",pattern:/ +/,group:bt.SKIPPED}),qx=Te({name:"whitespace",pattern:/\s+/,line_breaks:!0,group:bt.SKIPPED}),Yl=Te({name:"stat",pattern:/@.*/,start_chars_hint:["@"]}),Ki=Te({name:"command",pattern:/#/,start_chars_hint:["#"]});let sm=!1;function Jx(e,t,n){if(!sm)return null;const[r]=n.slice(-1);if(r&&r.tokenType!==js)return null;let i=t;for(;e[i]===" ";)i++;if("@#/?':!".includes(e[i]))return null;let s=t+1;for(;s"@#/?':!".includes(e)===!1)}),am=Te({name:"comment",pattern:/'.*/,start_chars_hint:["'"]}),cm=Te({name:"label",pattern:/:[^;:\n]*/,start_chars_hint:[":"]}),lm=Te({name:"hyperlink",pattern:/!/,start_chars_hint:["!"]}),um=Te({name:"hyperlinktext",pattern:/;[^;\n]*/,start_chars_hint:[";"]}),zt=Te({name:"stringliteral",pattern:/[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/,start_chars_hint:Zl}),fm=Te({name:"stringliteraldouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),hm=Te({name:"numberliteral",pattern:/-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?/}),dm=Te({name:"iseq",pattern:/=|is|eq|equal/,longer_alt:zt}),pm=Te({name:"isnoteq",pattern:/!=|not ?eq|not ?equal/,longer_alt:zt}),mm=Te({name:"islessthan",pattern:/<|below/,longer_alt:zt}),gm=Te({name:"isgreaterthan",pattern:/>|above/,longer_alt:zt}),ym=Te({name:"islessthanorequal",pattern:/<=|below ?or ?eq|below ?or ?equal/,longer_alt:zt}),_m=Te({name:"isgreaterthanorequal",pattern:/>=|above ?or ?eq|above ?or ?equal/,longer_alt:zt}),Ql=Te({name:"or",pattern:/or/i,longer_alt:zt}),eu=Te({name:"not",pattern:/not/i,longer_alt:zt}),tu=Te({name:"and",pattern:/and/i,longer_alt:zt}),nu=Te({name:"plus",pattern:/\+/}),ru=Te({name:"minus",pattern:/-/}),bm=Te({name:"power",pattern:/\*\*/}),wm=Te({name:"multiply",pattern:/\*/}),iu=Te({name:"divide",pattern:/\//}),vm=Te({name:"moddivide",pattern:/%/}),Em=Te({name:"floordivide",pattern:/%%/}),km=Te({name:"query",pattern:/\?/}),Sm=Te({name:"lparen",pattern:/\(/,push_mode:"ignore_newlines"}),Am=Te({name:"rparen",pattern:/\)/,pop_mode:!0}),Tm=Te({name:"command_play",pattern:/(play|bgplay) .*/,start_chars_hint:Zl,longer_alt:zt}),xm=_n("debugger"),su=_n("if"),Oa=_n("do"),Xx=_n("to",!0),ou=_n("done"),Zx=_n("then",!0),au=_n("else"),Rm=_n("while"),Im=_n("repeat"),Om=_n("waitfor"),Nm=Te({name:"foreach",pattern:/foreach|for/,longer_alt:zt}),Cm=_n("break"),Lm=_n("continue");function Mm(e){return[...e,hm,dm,pm,ym,mm,_m,gm,Ql,eu,tu,nu,ru,bm,wm,iu,Em,vm,km,Sm,Am,fm,zt]}const Um=Mm([om,Yl,Tm,Ki,am,cm,lm,um,js,Kx,Cm,Lm,xm,ou,Oa,au,Nm,su,Im,Zx,Xx,Om,Rm]),Yx=new bt({defaultMode:"use_newlines",modes:{use_newlines:Um,ignore_newlines:Mm([qx])}},{skipValidations:!qn,ensureOptimizations:qn});function Pm(e){sm=!0;const t=Yx.tokenize(e||` -`),[n]=(He(t.tokens)?t.tokens:[]).slice(-1);return n&&n.tokenType.name!=="Newline"&&t.tokens.push(_a(js,` -`,n.startOffset,n.endOffset??NaN,n.startLine??NaN,n.endLine??NaN,n.startColumn??NaN,n.endColumn??NaN)),t}function Dm(e,t=!0){const[n,...r]=e;switch(De(n)){default:return t?{type:fe.OBJECT,values:e}:{type:fe.CONST,values:e};case"loader":return{type:fe.LOADER,values:r};case"board":return{type:fe.BOARD,values:r};case"object":return{type:fe.OBJECT,values:r};case"terrain":return{type:fe.TERRAIN,values:r};case"charset":return{type:fe.CHARSET,values:r};case"palette":return{type:fe.PALETTE,values:r};case"rn":case"range":return{type:fe.RANGE,values:r};case"sl":case"select":return{type:fe.SELECT,values:r};case"nm":case"number":return{type:fe.NUMBER,values:r};case"tx":case"text":return{type:fe.TEXT,values:r};case"ln":case"link":return{type:fe.LINK,values:r};case"hk":case"hotkey":return{type:fe.HOTKEY,values:r};case"scroll":return{type:fe.SCROLL,values:r};case"copyit":return{type:fe.COPYIT,values:r}}}function bn(e){switch(e){case fe.LOADER:return"loader";case fe.BOARD:return"board";case fe.OBJECT:return"object";case fe.TERRAIN:return"terrain";case fe.CHARSET:return"charset";case fe.PALETTE:return"palette";case fe.CONST:return"const";case fe.RANGE:return"range";case fe.SELECT:return"select";case fe.NUMBER:return"number";case fe.TEXT:return"text";case fe.LINK:return"link";case fe.HOTKEY:return"hotkey";case fe.SCROLL:return"scroll";case fe.COPYIT:return"copyit"}}var Bm={},br={},wr={};Object.defineProperty(wr,"__esModule",{value:!0}),wr.throwUnsupportedData=wr.throwUnknownDataType=wr.getType=void 0;function Fm(e){return Object.prototype.toString.call(e)}wr.getType=Fm;function Qx(e){throw new TypeError("unsupported data type: "+Fm(e))}wr.throwUnknownDataType=Qx;function eR(e){throw new TypeError("unsupported data type: "+e)}wr.throwUnsupportedData=eR;var Mt={},Ut={};Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.s_to_num=Ut.int_str_to_s=Ut.num_to_s=Ut.big_int_to_s=Ut.int_to_s=Ut.s_to_big_int=Ut.s_to_int=void 0;let vr="";for(let e=0;e<10;e++){const t=String.fromCharCode(48+e);vr+=t}for(let e=0;e<26;e++){const t=String.fromCharCode(65+e);vr+=t}for(let e=0;e<26;e++){const t=String.fromCharCode(97+e);vr+=t}const qi=vr.length,cu={};for(let e=0;e=0;r--){const i=e[r];let s=cu[i];s*=n,t+=s,n*=qi}return t}Ut.s_to_int=lu;function $m(e){let t=BigInt(0),n=BigInt(1);const r=BigInt(qi);for(let i=e.length-1;i>=0;i--){const s=e[i];let o=BigInt(cu[s]);o*=n,t+=o,n*=r}return t}Ut.s_to_big_int=$m;function uu(e){if(e===0)return vr[0];const t=[];for(;e!==0;){const n=e%qi,r=vr[n];t.push(r),e-=n,e/=qi}return t.reverse().join("")}Ut.int_to_s=uu;function jm(e){const t=BigInt(0),n=BigInt(qi);if(e===t)return vr[0];const r=[];for(;e!==t;){const i=e%n,s=vr[Number(i)];r.push(s),e/=n}return r.reverse().join("")}Ut.big_int_to_s=jm;function zm(e){return e.split("").reverse().join("")}function Wm(e){if(e<0)return"-"+Wm(-e);let[t,n]=e.toString().split(".");if(!n)return uu(e);let r;n&&([n,r]=n.split("e")),t=Na(t),n=zm(n),n=Na(n);let i=t+"."+n;if(r){switch(i+=".",r[0]){case"+":r=r.slice(1);break;case"-":i+="-",r=r.slice(1);break}r=Na(r),i+=r}return i}Ut.num_to_s=Wm;function Na(e){const t=+e;return t.toString()===e&&t+1!==t&&t-1!==t?uu(t):":"+jm(BigInt(e))}Ut.int_str_to_s=Na;function fu(e){return e[0]===":"?$m(e.substring(1)).toString():lu(e).toString()}function Gm(e){if(e[0]==="-")return-Gm(e.substr(1));let[t,n,r]=e.split(".");if(!n)return lu(t);t=fu(t),n=fu(n),n=zm(n);let i=t+"."+n;if(r){i+="e";let s=!1;r[0]==="-"&&(s=!0,r=r.slice(1)),r=fu(r),i+=s?-r:+r}return+i}Ut.s_to_num=Gm,Object.defineProperty(Mt,"__esModule",{value:!0}),Mt.decodeStr=Mt.encodeStr=Mt.decodeBool=Mt.encodeBool=Mt.decodeKey=Mt.decodeNum=Mt.encodeNum=void 0;const hu=Ut;function tR(e){return"n|"+(0,hu.num_to_s)(e)}Mt.encodeNum=tR;function nR(e){return e=e.replace("n|",""),(0,hu.s_to_num)(e)}Mt.decodeNum=nR;function rR(e){return typeof e=="number"?e:(0,hu.s_to_int)(e)}Mt.decodeKey=rR;function iR(e){return e?"b|T":"b|F"}Mt.encodeBool=iR;function sR(e){switch(e){case"b|T":return!0;case"b|F":return!1}return!!e}Mt.decodeBool=sR;function oR(e){switch(e[0]+e[1]){case"b|":case"o|":case"n|":case"a|":case"s|":e="s|"+e}return e}Mt.encodeStr=oR;function aR(e){return e[0]+e[1]==="s|"?e.substr(2):e}Mt.decodeStr=aR;var an={},zs={};Object.defineProperty(zs,"__esModule",{value:!0}),zs.config=void 0,zs.config={sort_key:!1,error_on_nan:!1,error_on_infinite:!1},Object.defineProperty(an,"__esModule",{value:!0}),an.addValue=an.makeInMemoryMemory=an.makeInMemoryCache=an.makeInMemoryStore=an.memToValues=void 0;const du=zs,pu=wr,mu=Mt,cR=Ut;function lR(e){return e.store.toArray()}an.memToValues=lR;function Hm(){const e=[];return{forEach(t){for(let n=0;n(Eu(),this?this.unpack(t,n):Hs.prototype.unpack.call(qm,t,n)));!t.buffer&&t.constructor===ArrayBuffer&&(t=typeof Buffer<"u"?Buffer.from(t):new Uint8Array(t)),typeof n=="object"?(wn=n.end||t.length,U=n.start||0):(U=0,wn=n>-1?n:t.length),Jn=0,zr=null,At=null,ie=t;try{xe=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(r){throw ie=null,t instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(t&&typeof t=="object"?t.constructor.name:typeof t))}if(this instanceof Hs){if(qe=this,this.structures)return Oe=this.structures,La(n);(!Oe||Oe.length>0)&&(Oe=[])}else qe=qm,(!Oe||Oe.length>0)&&(Oe=[]);return La(n)}unpackMultiple(t,n){let r,i=0;try{Wr=!0;let s=t.length,o=this?this.unpack(t,s):Ma.unpack(t,s);if(n){if(n(o,i,U)===!1)return;for(;Ur.slice(0)));for(let r=0,i=t.length;r=32&&(s.highByte=r-32>>5))}t.sharedLength=t.length;for(let r in n||[])if(r>=0){let i=t[r],s=n[r];s&&(i&&((t.restoreStructures||(t.restoreStructures=[]))[r]=i),t[r]=s)}return this.structures=t}decode(t,n){return this.unpack(t,n)}}function La(e){try{if(!qe.trusted&&!Wr){let n=Oe.sharedLength||0;n=32&&Ym?(t=Ym(ie,U,wn,qe),ie=null,!(e&&e.lazy)&&t&&(t=t.toJSON()),U=wn):t=lt(),At&&(U=At.postBundlePosition,At=null),Wr&&(Oe.restoreStructures=null),U==wn)Oe&&Oe.restoreStructures&&Qm(),Oe=null,ie=null,Er&&(Er=null);else{if(U>wn)throw new Error("Unexpected end of MessagePack data");if(!Wr){let n;try{n=JSON.stringify(t,(r,i)=>typeof i=="bigint"?`${i}n`:i).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return t}catch(t){throw Oe&&Oe.restoreStructures&&Qm(),Eu(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer")||U>wn)&&(t.incomplete=!0),t}}function Qm(){for(let e in Oe.restoreStructures)Oe[e]=Oe.restoreStructures[e];Oe.restoreStructures=null}function lt(){let e=ie[U++];if(e<160)if(e<128){if(e<64)return e;{let t=Oe[e&63]||qe.getStructures&&tg()[e&63];return t?(t.read||(t.read=_u(t,e&63)),t.read()):e}}else if(e<144)if(e-=128,qe.mapsAsObjects){let t={};for(let n=0;n=U)return zr.slice(U-vn,(U+=t)-vn);if(Jn==0&&wn<140){let n=t<16?wu(t):ig(t);if(n!=null)return n}return bu(t)}else{let t;switch(e){case 192:return null;case 193:return At?(t=lt(),t>0?At[1].slice(At.position1,At.position1+=t):At[0].slice(At.position0,At.position0-=t)):Xm;case 194:return!1;case 195:return!0;case 196:if(t=ie[U++],t===void 0)throw new Error("Unexpected end of buffer");return vu(t);case 197:return t=xe.getUint16(U),U+=2,vu(t);case 198:return t=xe.getUint32(U),U+=4,vu(t);case 199:return mi(ie[U++]);case 200:return t=xe.getUint16(U),U+=2,mi(t);case 201:return t=xe.getUint32(U),U+=4,mi(t);case 202:if(t=xe.getFloat32(U),qe.useFloat32>2){let n=ku[(ie[U]&127)<<1|ie[U+1]>>7];return U+=4,(n*t+(t>0?.5:-.5)>>0)/n}return U+=4,t;case 203:return t=xe.getFloat64(U),U+=8,t;case 204:return ie[U++];case 205:return t=xe.getUint16(U),U+=2,t;case 206:return t=xe.getUint32(U),U+=4,t;case 207:return qe.int64AsType==="number"?(t=xe.getUint32(U)*4294967296,t+=xe.getUint32(U+4)):qe.int64AsType==="string"?t=xe.getBigUint64(U).toString():qe.int64AsType==="auto"?(t=xe.getBigUint64(U),t<=BigInt(2)<=BigInt(-2)<=U?zr.slice(U-vn,(U+=t)-vn):wR(t);case 218:return t=xe.getUint16(U),U+=2,Jn>=U?zr.slice(U-vn,(U+=t)-vn):vR(t);case 219:return t=xe.getUint32(U),U+=4,Jn>=U?zr.slice(U-vn,(U+=t)-vn):ER(t);case 220:return t=xe.getUint16(U),U+=2,ng(t);case 221:return t=xe.getUint32(U),U+=4,ng(t);case 222:return t=xe.getUint16(U),U+=2,rg(t);case 223:return t=xe.getUint32(U),U+=4,rg(t);default:if(e>=224)return e-256;if(e===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+e)}}}const bR=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function _u(e,t){function n(){if(n.count++>Zm){let i=e.read=new Function("r","return function(){return "+(qe.freezeData?"Object.freeze":"")+"({"+e.map(s=>s==="__proto__"?"__proto_:r()":bR.test(s)?s+":r()":"["+JSON.stringify(s)+"]:r()").join(",")+"})}")(lt);return e.highByte===0&&(e.read=eg(t,e.read)),i()}let r={};for(let i=0,s=e.length;ifunction(){let n=ie[U++];if(n===0)return t();let r=e<32?-(e+(n<<5)):e+(n<<5),i=Oe[r]||tg()[r];if(!i)throw new Error("Record id is not defined for "+r);return i.read||(i.read=_u(i,e)),i.read()};function tg(){let e=fg(()=>(ie=null,qe.getStructures()));return Oe=qe._mergeStructures(e,Oe)}var bu=Vs,wR=Vs,vR=Vs,ER=Vs;function Vs(e){let t;if(e<16&&(t=wu(e)))return t;if(e>64&&yu)return yu.decode(ie.subarray(U,U+=e));const n=U+e,r=[];for(t="";U65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c)}else r.push(i);r.length>=4096&&(t+=Tt.apply(String,r),r.length=0)}return r.length>0&&(t+=Tt.apply(String,r)),t}function ng(e){let t=new Array(e);for(let n=0;n0){U=t;return}n[r]=i}return Tt.apply(String,n)}function wu(e){if(e<4)if(e<2){if(e===0)return"";{let t=ie[U++];if((t&128)>1){U-=1;return}return Tt(t)}}else{let t=ie[U++],n=ie[U++];if((t&128)>0||(n&128)>0){U-=2;return}if(e<3)return Tt(t,n);let r=ie[U++];if((r&128)>0){U-=3;return}return Tt(t,n,r)}else{let t=ie[U++],n=ie[U++],r=ie[U++],i=ie[U++];if((t&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){U-=4;return}if(e<6){if(e===4)return Tt(t,n,r,i);{let s=ie[U++];if((s&128)>0){U-=5;return}return Tt(t,n,r,i,s)}}else if(e<8){let s=ie[U++],o=ie[U++];if((s&128)>0||(o&128)>0){U-=6;return}if(e<7)return Tt(t,n,r,i,s,o);let a=ie[U++];if((a&128)>0){U-=7;return}return Tt(t,n,r,i,s,o,a)}else{let s=ie[U++],o=ie[U++],a=ie[U++],c=ie[U++];if((s&128)>0||(o&128)>0||(a&128)>0||(c&128)>0){U-=8;return}if(e<10){if(e===8)return Tt(t,n,r,i,s,o,a,c);{let l=ie[U++];if((l&128)>0){U-=9;return}return Tt(t,n,r,i,s,o,a,c,l)}}else if(e<12){let l=ie[U++],u=ie[U++];if((l&128)>0||(u&128)>0){U-=10;return}if(e<11)return Tt(t,n,r,i,s,o,a,c,l,u);let f=ie[U++];if((f&128)>0){U-=11;return}return Tt(t,n,r,i,s,o,a,c,l,u,f)}else{let l=ie[U++],u=ie[U++],f=ie[U++],d=ie[U++];if((l&128)>0||(u&128)>0||(f&128)>0||(d&128)>0){U-=12;return}if(e<14){if(e===12)return Tt(t,n,r,i,s,o,a,c,l,u,f,d);{let h=ie[U++];if((h&128)>0){U-=13;return}return Tt(t,n,r,i,s,o,a,c,l,u,f,d,h)}}else{let h=ie[U++],p=ie[U++];if((h&128)>0||(p&128)>0){U-=14;return}if(e<15)return Tt(t,n,r,i,s,o,a,c,l,u,f,d,h,p);let m=ie[U++];if((m&128)>0){U-=15;return}return Tt(t,n,r,i,s,o,a,c,l,u,f,d,h,p,m)}}}}}function sg(){let e=ie[U++],t;if(e<192)t=e-160;else switch(e){case 217:t=ie[U++];break;case 218:t=xe.getUint16(U),U+=2;break;case 219:t=xe.getUint32(U),U+=4;break;default:throw new Error("Expected string")}return Vs(t)}function vu(e){return qe.copyBuffers?Uint8Array.prototype.slice.call(ie,U,U+=e):ie.subarray(U,U+=e)}function mi(e){let t=ie[U++];if(tn[t]){let n;return tn[t](ie.subarray(U,n=U+=e),r=>{U=r;try{return lt()}finally{U=n}})}else throw new Error("Unknown extension type "+t)}var og=new Array(4096);function ag(){let e=ie[U++];if(e>=160&&e<192){if(e=e-160,Jn>=U)return zr.slice(U-vn,(U+=e)-vn);if(!(Jn==0&&wn<180))return bu(e)}else return U--,cg(lt());let t=(e<<5^(e>1?xe.getUint16(U):e>0?ie[U]:0))&4095,n=og[t],r=U,i=U+e-3,s,o=0;if(n&&n.bytes==e){for(;r{let n=lt().map(cg),r=e;t!==void 0&&(e=e<32?-((t<<5)+e):(t<<5)+e,n.highByte=t);let i=Oe[e];return i&&(i.isShared||Wr)&&((Oe.restoreStructures||(Oe.restoreStructures=[]))[e]=i),Oe[e]=n,n.read=_u(n,r),n.read()};tn[0]=()=>{},tn[0].noBuffer=!0,tn[66]=e=>{let t=e.length,n=BigInt(e[0]&128?e[0]-256:e[0]);for(let r=1;r{let e=lt();return(kR[e[0]]||Error)(e[1],{cause:e[2]})},tn[105]=e=>{if(qe.structuredClone===!1)throw new Error("Structured clone extension is disabled");let t=xe.getUint32(U-4);Er||(Er=new Map);let n=ie[U],r;n>=144&&n<160||n==220||n==221?r=[]:r={};let i={target:r};Er.set(t,i);let s=lt();return i.used?Object.assign(r,s):(i.target=s,s)},tn[112]=e=>{if(qe.structuredClone===!1)throw new Error("Structured clone extension is disabled");let t=xe.getUint32(U-4),n=Er.get(t);return n.used=!0,n.target},tn[115]=()=>new Set(lt());const ug=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(e=>e+"Array");let SR=typeof globalThis=="object"?globalThis:window;tn[116]=e=>{let t=e[0],n=ug[t];if(!n){if(t===16){let r=new ArrayBuffer(e.length-1);return new Uint8Array(r).set(e.subarray(1)),r}throw new Error("Could not find typed array for code "+t)}return new SR[n](Uint8Array.prototype.slice.call(e,1).buffer)},tn[120]=()=>{let e=lt();return new RegExp(e[0],e[1])};const AR=[];tn[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],n=U;return U+=t-e.length,At=AR,At=[sg(),sg()],At.position0=0,At.position1=0,At.postBundlePosition=U,U=n,lt()},tn[255]=e=>e.length==4?new Date((e[0]*16777216+(e[1]<<16)+(e[2]<<8)+e[3])*1e3):e.length==8?new Date(((e[0]<<22)+(e[1]<<14)+(e[2]<<6)+(e[3]>>2))/1e6+((e[3]&3)*4294967296+e[4]*16777216+(e[5]<<16)+(e[6]<<8)+e[7])*1e3):e.length==12?new Date(((e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3])/1e6+((e[4]&128?-281474976710656:0)+e[6]*1099511627776+e[7]*4294967296+e[8]*16777216+(e[9]<<16)+(e[10]<<8)+e[11])*1e3):new Date("invalid");function fg(e){let t=wn,n=U,r=vn,i=Jn,s=zr,o=Er,a=At,c=new Uint8Array(ie.slice(0,wn)),l=Oe,u=Oe.slice(0,Oe.length),f=qe,d=Wr,h=e();return wn=t,U=n,vn=r,Jn=i,zr=s,Er=o,At=a,ie=c,Wr=d,Oe=l,Oe.splice(0,Oe.length,...u),qe=f,xe=new DataView(ie.buffer,ie.byteOffset,ie.byteLength),h}function Eu(){ie=null,Er=null,Oe=null}const ku=new Array(147);for(let e=0;e<256;e++)ku[e]=+("1e"+Math.floor(45.15-e*.30103));var Ma=new Hs({useRecords:!1});const TR=Ma.unpack;Ma.unpackMultiple,Ma.unpack;let xR=new Float32Array(1);new Uint8Array(xR.buffer,0,4);let Ua;try{Ua=new TextEncoder}catch{}let Su,hg;const Pa=typeof Buffer<"u",Da=Pa?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,dg=Pa?Buffer:Uint8Array,pg=Pa?4294967296:2144337920;let j,Ks,Je,P=0,Wt,nt=null,RR;const IR=21760,OR=/[\u0080-\uFFFF]/,Xi=Symbol("record-id");class NR extends Hs{constructor(t){super(t),this.offset=0;let n,r,i,s,o=dg.prototype.utf8Write?function(k,g){return j.utf8Write(k,g,j.byteLength-g)}:Ua&&Ua.encodeInto?function(k,g){return Ua.encodeInto(k,j.subarray(g)).written}:!1,a=this;t||(t={});let c=t&&t.sequential,l=t.structures||t.saveStructures,u=t.maxSharedStructures;if(u==null&&(u=l?32:0),u>8160)throw new Error("Maximum maxSharedStructure is 8160");t.structuredClone&&t.moreTypes==null&&(this.moreTypes=!0);let f=t.maxOwnStructures;f==null&&(f=l?32:64),!this.structures&&t.useRecords!=!1&&(this.structures=[]);let d=u>32||f+u>64,h=u+64,p=u+f+64;if(p>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let m=[],b=0,_=0;this.pack=this.encode=function(k,g){if(j||(j=new Da(8192),Je=j.dataView||(j.dataView=new DataView(j.buffer,0,8192)),P=0),Wt=j.length-10,Wt-P<2048?(j=new Da(j.length),Je=j.dataView||(j.dataView=new DataView(j.buffer,0,j.length)),Wt=j.length-10,P=0):P=P+7&2147483640,n=P,g&BR&&(P+=g&255),s=a.structuredClone?new Map:null,a.bundleStrings&&typeof k!="string"?(nt=[],nt.size=1/0):nt=null,i=a.structures,i){i.uninitialized&&(i=a._mergeStructures(a.getStructures()));let W=i.sharedLength||0;if(W>u)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let B=0;B$.offset>F.offset?1:-1),Z=B.length,H=-1;for(;W&&Z>0;){let $=B[--Z].offset+n;$W.position+n?H>=0&&(H+=6):(H>=0&&(Je.setUint32(W.position+n,Je.getUint32(W.position+n)+H),H=-1),W=W.previous,Z++)}H>=0&&W&&Je.setUint32(W.position+n,Je.getUint32(W.position+n)+H),P+=B.length*6,P>Wt&&x(P),a.offset=P;let Y=LR(j.subarray(n,P),B);return s=null,Y}return a.offset=P,g&PR?(j.start=n,j.end=P,j):j.subarray(n,P)}catch(W){throw N=W,W}finally{if(i&&(w(),r&&a.saveStructures)){let W=i.sharedLength||0,B=j.subarray(n,P),Z=MR(i,a);if(!N)return a.saveStructures(Z,Z.isCompatible)===!1?a.pack(k,g):(a.lastNamedStructuresLength=W,j.length>1073741824&&(j=null),B)}j.length>1073741824&&(j=null),g&DR&&(P=n)}};const w=()=>{_<10&&_++;let k=i.sharedLength||0;if(i.length>k&&!c&&(i.length=k),b>1e4)i.transitions=null,_=0,b=0,m.length>0&&(m=[]);else if(m.length>0&&!c){for(let g=0,N=m.length;g{var g=k.length;g<16?j[P++]=144|g:g<65536?(j[P++]=220,j[P++]=g>>8,j[P++]=g&255):(j[P++]=221,Je.setUint32(P,g),P+=4);for(let N=0;N{P>Wt&&(j=x(P));var g=typeof k,N;if(g==="string"){let W=k.length;if(nt&&W>=4&&W<4096){if((nt.size+=W)>IR){let Y,$=(nt[0]?nt[0].length*3+nt[1].length:0)+10;P+$>Wt&&(j=x(P+$));let F;nt.position?(F=nt,j[P]=200,P+=3,j[P++]=98,Y=P-n,P+=4,yg(n,S,0),Je.setUint16(Y+n-3,P-n-Y)):(j[P++]=214,j[P++]=98,Y=P-n,P+=4),nt=["",""],nt.previous=F,nt.size=0,nt.position=Y}let H=OR.test(k);nt[H?0:1]+=k,j[P++]=193,S(H?-W:W);return}let B;W<32?B=1:W<256?B=2:W<65536?B=3:B=5;let Z=W*3;if(P+Z>Wt&&(j=x(P+Z)),W<64||!o){let H,Y,$,F=P+B;for(H=0;H>6|192,j[F++]=Y&63|128):(Y&64512)===55296&&(($=k.charCodeAt(H+1))&64512)===56320?(Y=65536+((Y&1023)<<10)+($&1023),H++,j[F++]=Y>>18|240,j[F++]=Y>>12&63|128,j[F++]=Y>>6&63|128,j[F++]=Y&63|128):(j[F++]=Y>>12|224,j[F++]=Y>>6&63|128,j[F++]=Y&63|128);N=F-P-B}else N=o(k,P+B);N<32?j[P++]=160|N:N<256?(B<2&&j.copyWithin(P+2,P+1,P+1+N),j[P++]=217,j[P++]=N):N<65536?(B<3&&j.copyWithin(P+3,P+2,P+2+N),j[P++]=218,j[P++]=N>>8,j[P++]=N&255):(B<5&&j.copyWithin(P+5,P+3,P+3+N),j[P++]=219,Je.setUint32(P,N),P+=4),P+=N}else if(g==="number")if(k>>>0===k)k<32||k<128&&this.useRecords===!1||k<64&&!this.randomAccessStructure?j[P++]=k:k<256?(j[P++]=204,j[P++]=k):k<65536?(j[P++]=205,j[P++]=k>>8,j[P++]=k&255):(j[P++]=206,Je.setUint32(P,k),P+=4);else if(k>>0===k)k>=-32?j[P++]=256+k:k>=-128?(j[P++]=208,j[P++]=k+256):k>=-32768?(j[P++]=209,Je.setInt16(P,k),P+=2):(j[P++]=210,Je.setInt32(P,k),P+=4);else{let W;if((W=this.useFloat32)>0&&k<4294967296&&k>=-2147483648){j[P++]=202,Je.setFloat32(P,k);let B;if(W<4||(B=k*ku[(j[P]&127)<<1|j[P+1]>>7])>>0===B){P+=4;return}else P--}j[P++]=203,Je.setFloat64(P,k),P+=8}else if(g==="object"||g==="function")if(!k)j[P++]=192;else{if(s){let B=s.get(k);if(B){if(!B.id){let Z=s.idsToInsert||(s.idsToInsert=[]);B.id=Z.push(B)}j[P++]=214,j[P++]=112,Je.setUint32(P,B.id),P+=4;return}else s.set(k,{offset:P-n})}let W=k.constructor;if(W===Object)M(k);else if(W===Array)v(k);else if(W===Map)if(this.mapAsEmptyObject)j[P++]=128;else{N=k.size,N<16?j[P++]=128|N:N<65536?(j[P++]=222,j[P++]=N>>8,j[P++]=N&255):(j[P++]=223,Je.setUint32(P,N),P+=4);for(let[B,Z]of k)S(B),S(Z)}else{for(let B=0,Z=Su.length;B(j=$,$=null,P+=ee,P>Wt&&x(P),{target:j,targetView:Je,position:P-ee}),S)}finally{$&&(j=$,Je=F,P=ue,Wt=j.length-10)}Q&&(Q.length+P>Wt&&x(Q.length+P),P=CR(Q,j,P,Y.type));return}}if(Array.isArray(k))v(k);else{if(k.toJSON){const B=k.toJSON();if(B!==k)return S(B)}if(g==="function")return S(this.writeFunction&&this.writeFunction(k));M(k)}}}else if(g==="boolean")j[P++]=k?195:194;else if(g==="bigint"){if(k=-(BigInt(1)<0)j[P++]=207,Je.setBigUint64(P,k);else if(this.largeBigIntToFloat)j[P++]=203,Je.setFloat64(P,Number(k));else{if(this.largeBigIntToString)return S(k.toString());if(this.useBigIntExtension&&k-(BigInt(2)**BigInt(1023))){j[P++]=199,P++,j[P++]=66;let W=[],B;do{let Z=k&BigInt(255);B=(Z&BigInt(128))===(k>=BigInt(8)}while(!((k===BigInt(0)||k===BigInt(-1))&&B));j[P-2]=W.length;for(let Z=W.length;Z>0;)j[P++]=Number(W[--Z]);return}else throw new RangeError(k+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}P+=8}else if(g==="undefined")this.encodeUndefinedAsNil?j[P++]=192:(j[P++]=212,j[P++]=0,j[P++]=0);else throw new Error("Unknown type: "+g)},C=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?k=>{let g;if(this.skipValues){g=[];for(let B in k)(typeof k.hasOwnProperty!="function"||k.hasOwnProperty(B))&&!this.skipValues.includes(k[B])&&g.push(B)}else g=Object.keys(k);let N=g.length;N<16?j[P++]=128|N:N<65536?(j[P++]=222,j[P++]=N>>8,j[P++]=N&255):(j[P++]=223,Je.setUint32(P,N),P+=4);let W;if(this.coercibleKeyAsNumber)for(let B=0;B{j[P++]=222;let g=P-n;P+=2;let N=0;for(let W in k)(typeof k.hasOwnProperty!="function"||k.hasOwnProperty(W))&&(S(W),S(k[W]),N++);if(N>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');j[g+++n]=N>>8,j[g+n]=N&255},I=this.useRecords===!1?C:t.progressiveRecords&&!d?k=>{let g,N=i.transitions||(i.transitions=Object.create(null)),W=P++-n,B;for(let Z in k)if(typeof k.hasOwnProperty!="function"||k.hasOwnProperty(Z)){if(g=N[Z],g)N=g;else{let H=Object.keys(k),Y=N;N=i.transitions;let $=0;for(let F=0,ue=H.length;F{let g,N=i.transitions||(i.transitions=Object.create(null)),W=0;for(let Z in k)(typeof k.hasOwnProperty!="function"||k.hasOwnProperty(Z))&&(g=N[Z],g||(g=N[Z]=Object.create(null),W++),N=g);let B=N[Xi];B?B>=96&&d?(j[P++]=((B-=96)&31)+96,j[P++]=B>>5):j[P++]=B:V(N,N.__keys__||Object.keys(k),W);for(let Z in k)(typeof k.hasOwnProperty!="function"||k.hasOwnProperty(Z))&&S(k[Z])},T=typeof this.useRecords=="function"&&this.useRecords,M=T?k=>{T(k)?I(k):C(k)}:I,x=k=>{let g;if(k>16777216){if(k-n>pg)throw new Error("Packed buffer would be larger than maximum buffer size");g=Math.min(pg,Math.round(Math.max((k-n)*(k>67108864?1.25:2),4194304)/4096)*4096)}else g=(Math.max(k-n<<2,j.length-1)>>12)+1<<12;let N=new Da(g);return Je=N.dataView||(N.dataView=new DataView(N.buffer,0,g)),k=Math.min(k,j.length),j.copy?j.copy(N,0,n,k):N.set(j.slice(n,k)),P-=n,n=0,Wt=N.length-10,j=N},V=(k,g,N)=>{let W=i.nextId;W||(W=64),W=p&&(W=h),i.nextId=W+1);let B=g.highByte=W>=96&&d?W-96>>5:-1;k[Xi]=W,k.__keys__=g,i[W-64]=g,W=0?(j[P++]=(W&31)+96,j[P++]=B):j[P++]=W):(B>=0?(j[P++]=213,j[P++]=114,j[P++]=(W&31)+96,j[P++]=B):(j[P++]=212,j[P++]=114,j[P++]=W),N&&(b+=_*N),m.length>=f&&(m.shift()[Xi]=0),m.push(k),S(g))},oe=(k,g,N,W)=>{let B=j,Z=P,H=Wt,Y=n;j=Ks,P=0,n=0,j||(Ks=j=new Da(8192)),Wt=j.length-10,V(k,g,W),Ks=j;let $=P;if(j=B,P=Z,Wt=H,n=Y,$>1){let F=P+$-1;F>Wt&&x(F);let ue=N+n;j.copyWithin(ue+$,ue+1,P),j.set(Ks.slice(0,$),ue),P=F}else j[N+n]=Ks[0]},O=k=>{let g=RR(k,j,n,P,i,x,(N,W,B)=>{if(B)return r=!0;P=W;let Z=j;return S(N),w(),Z!==j?{position:P,targetView:Je,target:j}:P},this);if(g===0)return M(k);P=g}}useBuffer(t){j=t,j.dataView||(j.dataView=new DataView(j.buffer,j.byteOffset,j.byteLength)),P=0}set position(t){P=t}get position(){return P}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}}hg=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,Jm],Su=[{pack(e,t,n){let r=e.getTime()/1e3;if((this.useTimestamp32||e.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:i,targetView:s,position:o}=t(6);i[o++]=214,i[o++]=255,s.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:i,targetView:s,position:o}=t(10);i[o++]=215,i[o++]=255,s.setUint32(o,e.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),s.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return t(0),n(this.onInvalidDate());let{target:i,targetView:s,position:o}=t(3);i[o++]=212,i[o++]=255,i[o++]=255}else{let{target:i,targetView:s,position:o}=t(15);i[o++]=199,i[o++]=12,i[o++]=255,s.setUint32(o,e.getMilliseconds()*1e6),s.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(e,t,n){if(this.setAsEmptyObject)return t(0),n({});let r=Array.from(e),{target:i,position:s}=t(this.moreTypes?3:0);this.moreTypes&&(i[s++]=212,i[s++]=115,i[s++]=0),n(r)}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),n([e.name,e.message,e.cause])}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),n([e.source,e.flags])}},{pack(e,t){this.moreTypes?mg(e,16,t):gg(Pa?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let n=e.constructor;n!==dg&&this.moreTypes?mg(e,ug.indexOf(n.name),t):gg(e,t)}},{pack(e,t){let{target:n,position:r}=t(1);n[r]=193}}];function mg(e,t,n,r){let i=e.byteLength;if(i+1<256){var{target:s,position:o}=n(4+i);s[o++]=199,s[o++]=i+1}else if(i+1<65536){var{target:s,position:o}=n(5+i);s[o++]=200,s[o++]=i+1>>8,s[o++]=i+1&255}else{var{target:s,position:o,targetView:a}=n(7+i);s[o++]=201,a.setUint32(o,i+1),o+=4}s[o++]=116,s[o++]=t,e.buffer||(e=new Uint8Array(e)),s.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o)}function gg(e,t){let n=e.byteLength;var r,i;if(n<256){var{target:r,position:i}=t(n+2);r[i++]=196,r[i++]=n}else if(n<65536){var{target:r,position:i}=t(n+3);r[i++]=197,r[i++]=n>>8,r[i++]=n&255}else{var{target:r,position:i,targetView:s}=t(n+5);r[i++]=198,s.setUint32(i,n),i+=4}r.set(e,i)}function CR(e,t,n,r){let i=e.length;switch(i){case 1:t[n++]=212;break;case 2:t[n++]=213;break;case 4:t[n++]=214;break;case 8:t[n++]=215;break;case 16:t[n++]=216;break;default:i<256?(t[n++]=199,t[n++]=i):i<65536?(t[n++]=200,t[n++]=i>>8,t[n++]=i&255):(t[n++]=201,t[n++]=i>>24,t[n++]=i>>16&255,t[n++]=i>>8&255,t[n++]=i&255)}return t[n++]=r,t.set(e,n),n+=i,n}function LR(e,t){let n,r=t.length*6,i=e.length-r;for(;n=t.pop();){let s=n.offset,o=n.id;e.copyWithin(s+r,s,i),r-=6;let a=s+r;e[a++]=214,e[a++]=105,e[a++]=o>>24,e[a++]=o>>16&255,e[a++]=o>>8&255,e[a++]=o&255,i=s}return e}function yg(e,t,n){if(nt.length>0){Je.setUint32(nt.position+e,P+n-nt.position-e),nt.stringsPosition=P-e;let r=nt;nt=null,t(r[0]),t(r[1])}}function MR(e,t){return e.isCompatible=n=>{let r=!n||(t.lastNamedStructuresLength||0)===n.length;return r||t._mergeStructures(n),r},e}let _g=new NR({useRecords:!1});const UR=_g.pack;_g.pack;const PR=512,DR=1024,BR=2048;function gi(){return null}function qs(e,t,n={}){if(!E(e))return;const r=[],i=Object.keys(e);for(let s=0;s(e[e.kind=0]="kind",e[e.id=1]="id",e[e.x=2]="x",e[e.y=3]="y",e[e.lx=4]="lx",e[e.ly=5]="ly",e[e.code=6]="code",e[e.name=7]="name",e[e.char=8]="char",e[e.color=9]="color",e[e.bg=10]="bg",e[e.player=11]="player",e[e.bucket=12]="bucket",e[e.pushable=13]="pushable",e[e.collision=14]="collision",e[e.destructible=15]="destructible",e[e.tickertext=16]="tickertext",e[e.tickertime=17]="tickertime",e[e.p1=18]="p1",e[e.p2=19]="p2",e[e.p3=20]="p3",e[e.cycle=21]="cycle",e[e.stepx=22]="stepx",e[e.stepy=23]="stepy",e[e.sender=24]="sender",e[e.arg=25]="arg",e[e.headless=26]="headless",e[e.removed=27]="removed",e))(Au||{});function Ba(e){return qs(e,Au,{category:gi,kinddata:gi})}function Fa(e){return Js(e,Au)}var Tu=(e=>(e[e.width=0]="width",e[e.height=1]="height",e[e.bits=2]="bits",e))(Tu||{});function wg(e){return qs(e,Tu)}function vg(e){return Js(e,Tu)}function Eg(e,t){return{id:ht(),code:e,...t}}var xu=(e=>(e[e.id=0]="id",e[e.code=1]="code",e[e.board=2]="board",e[e.object=3]="object",e[e.terrain=4]="terrain",e[e.charset=5]="charset",e[e.palette=6]="palette",e[e.eighttrack=7]="eighttrack",e))(xu||{});function jR(e){return qs(e,xu,{board:fI,object:Ba,terrain:Ba,charset:wg,palette:wg,stats:gi})}function zR(e){return Js(e,xu,{board:hI,object:Fa,terrain:Fa,charset:vg,palette:vg})}function WR(e){const t={...Xs(e)};return Object.keys(t).forEach(n=>{switch(n){case"type":case"name":delete t[n];break}}),t}function GR(e){return E(e)?(e.stats=void 0,Xs(e)):{}}function Xs(e){var r;if(!E(e))return{};if(E((r=e.stats)==null?void 0:r.type))return e.stats;e.stats={};const t=Pm(e.code);let n=!0;for(let i=0;i(e[e.id=0]="id",e[e.name=1]="name",e[e.timestamp=2]="timestamp",e[e.activelist=3]="activelist",e[e.pages=4]="pages",e[e.flags=5]="flags",e))(Iu||{});function HR(e){return qs(e,Iu,{pages:t=>t.map(jR)})}function VR(e){return Js(e,Iu,{pages:t=>t.map(zR)})}function yi(e,t){if(!E(e))return;const n=De(t);return e.pages.find(i=>i.id===t||n===Xn(i))}function Ou(e,t,n){if(!E(e))return;const r=De(n);return e.pages.find(s=>Zs(s)===t&&(s.id===n||r===Xn(s)))}function KR(e,t){return E(e)?e.pages.filter(n=>Zs(n)===t):[]}function Tg(e,t){if(!E(e)||!E(t))return!1;const n=yi(e,t.id);return E(n)?!1:(e.pages.push(t),!0)}function qR(e,t){const n=yi(e,t);if(E(e)&&E(n)){const r=De(t);return e.pages=e.pages.filter(i=>i.id!==t&&r!==Xn(i)),n}}function Ln(e,t){if(E(t)&&E(t.kind))return E(t.kinddata)||(t.kinddata=E(t.id)?$a(e,t.kind):Rg(e,t.kind)),t.kinddata}function xg(e,t){const n=Ln(e,t);return{char:(t==null?void 0:t.char)??(n==null?void 0:n.char)??1,color:(t==null?void 0:t.color)??(n==null?void 0:n.color)??be.WHITE,bg:(t==null?void 0:t.bg)??(n==null?void 0:n.bg)??be.ONBORROW}}function $a(e,t){const n=t??"",r=Ou(e,Ae.OBJECT,n);if(E(r)){const i=Ru(r);return{..._s(i),name:n,code:r.code}}}function Rg(e,t){const n=t??"",r=Ou(e,Ae.TERRAIN,n);if(E(r)){const i=Ru(r);return{..._s(i),name:n,code:r.code}}}function Zi(e,t){const n=yi(e,t);return Ru(n)}function Yi(e,t){return e?(e.flags[t]=e.flags[t]??{},e.flags[t]):{}}function Nu(e,t){e&&delete e.flags[t]}function Ig(e,t,n){const r=Yi(e,t);return r==null?void 0:r[n]}function JR(e,t,n,r){const i=Yi(e,t);return i&&(i[n]=r),r}function ja(e,t){const n=Ig(e,t,"board");return Zi(e,Ie(n)?n:"")}function Cu(e,t,n){if(!E(e))return;JR(e,t,"board",n);const r=Zi(e,n);E(r)?e.activelist.includes(t)||e.activelist.push(t):e.activelist=e.activelist.filter(i=>i!==t)}function XR(e){const n=((e==null?void 0:e.activelist)??[]).map(r=>{const i=Ig(e,r,"board");return Ie(i)?i:""});return _w(n)}function Og(e){return XR(e).map(n=>Zi(e,n)).filter(E)}function ZR(e,t,n,r){const i=es(t,(n==null?void 0:n.id)??"");if(!E(e)||!E(t)||!E(i)||!E(i.x)||!E(i.y)||!E(t.lookup)||r.x<0||r.x>=ze||r.y<0||r.y>=rn||i.x-r.x===0&&i.y-r.y===0)return!0;const s=r.x+r.y*ze,o=Ln(e,i),a=i.collision??(o==null?void 0:o.collision),c=es(t,t.lookup[s]??"");if(E(c))return!0;const l=t.terrain[s];if(E(l)){const u=Ln(e,l),f=l.collision??(u==null?void 0:u.collision);if(Ch(a,f))return!0}return!1}function YR(e,t,n,r){const i=es(t,(n==null?void 0:n.id)??"");if(!E(e)||!E(t)||!E(i)||!E(i.x)||!E(i.y)||!E(t.lookup)||r.x<0||r.x>=ze||r.y<0||r.y>=rn)return{kind:"edge",collision:Ye.ISSOLID,x:r.x,y:r.y};if(i.x-r.x===0&&i.y-r.y===0)return;const s=i.x+i.y*ze,o=r.x+r.y*ze,a=Ln(e,i),c=i.collision??(a==null?void 0:a.collision),l=es(t,t.lookup[o]??"");if(E(l))return{...l};const u=t.terrain[o];if(E(u)){const f=Ln(e,u),d=u.collision??(f==null?void 0:f.collision);if(Ch(c,d))return{...u,x:r.x,y:r.y}}i.x=r.x,i.y=r.y,E(i.removed)||(t.lookup[s]=void 0,t.lookup[o]=i.id??"")}function Qi(e,t){const n=Ln(e,t);return E(t==null?void 0:t.id)&&E(t.x)&&E(t.y)?De(t.name??(n==null?void 0:n.name)??"object"):De((t==null?void 0:t.name)??(n==null?void 0:n.name)??"terrain")}function Lu(e,t,n,r){if(!E(e)||!E(t)||!E(t.named)||!E(n))return;const i=Qi(e,n);t.named[i]||(t.named[i]=new Set),t.named[i].add((n==null?void 0:n.id)??r??"")}function QR(e,t,n){if(!(!E(e)||!E(t)||!E(t.lookup)||!E(n==null?void 0:n.id))&&!E(n.removed)){const r=n.x??0,i=n.y??0;t.lookup[r+i*ze]=n.id}}function za(e,t){if(!E(e)||!E(t)||E(t.lookup)&&E(t.named))return;const n=new Array(ze*rn).fill(void 0),r={},i=Object.values(t.objects);for(let a=0;a=ze&&(s=0,++o)}t.lookup=n,t.named=r}function Mu(e,t,n){return Qi(e,t)!=="player"&&E(t)?(t.removed=n,!0):!1}function Qs(e,t,n){var r;if(E(e)&&E(t)&&E(n==null?void 0:n.id)){if(E(t.lookup)&&E(n.x)&&E(n.y)){const s=n.x+n.y*ze;t.lookup[s]===n.id&&t.lookup.splice(s,1)}const i=Qi(e,n);E((r=t.named)==null?void 0:r[i])&&E(n.id)&&t.named[i].delete(n.id)}}function eI(e,t,n){const r=[];if(!E(e)||!E(t))return r;const i=Object.values(t.objects);for(let s=0;sPh*5&&(r.push(o.id),Wg(t,o.id))}return r}function tI(e,t,n){const r=[];if(!E(e)||!E(t))return r;t.lookup=void 0,za(e,t);const i=Object.values(t.objects);for(let o=0;obe.WHITE&&ebe[t]).find(t=>E(t)&&tbe[t]).find(t=>E(t)&&t>=be.ONBLACK)}function $g(e){if(En(e))return e;if(Bg(e))return[e];const t=Fg(e);if(E(t))return[t]}function jg(e){const t=L.words[e],n=$g(t);if(En(n))return[n,e+1];const[r,i]=Gt(e),s=$g(r);return En(s)?[s,i]:[void 0,e]}function Ha(e){const t=[];let n=e;const[r,i]=jg(e);if(En(r)&&(t.push(...r),n=i),En(t)&&!Dg(t)){const[s,o]=jg(i);Dg(s)&&(n=o)}return t.length?[t,n]:[void 0,e]}function cI(e){const t={};return e.every(n=>{const r=be[n];E(r)&&(r{})}function uI(e=lw){const t={terrain:lI(),objects:{},id:""};return e(t)}var Du=(e=>(e[e.terrain=0]="terrain",e[e.objects=1]="objects",e[e.isdark=2]="isdark",e[e.over=3]="over",e[e.under=4]="under",e[e.exitnorth=5]="exitnorth",e[e.exitsouth=6]="exitsouth",e[e.exitwest=7]="exitwest",e[e.exiteast=8]="exiteast",e[e.timelimit=9]="timelimit",e[e.restartonzap=10]="restartonzap",e[e.maxplayershots=11]="maxplayershots",e))(Du||{});function fI(e){return qs(e,Du,{terrain:t=>t.map(Ba),objects:t=>Object.values(t).map(Ba),id:gi,named:gi,lookup:gi,codepage:gi})}function hI(e){return Js(e,Du,{terrain:t=>t.map(Fa),objects:t=>{const n={};for(let r=0;r=ze||t.y<0||t.y>=rn)return;const n={...t},r=t.x+t.y*ze;return e.terrain[r]=n,t}function gI(e,t){if(!E(e)||!E(t))return;const n={...t,id:t.id??ht()};return e.objects[n.id]=n,n}function zg(e,t,n){return mI(e,{...t,kind:n})}function Fu(e,t,n,r){return gI(e,{...t,id:r??void 0,kind:n})}function es(e,t){if(e)return e.objects[t]}function $u(e,t,n,r,i){if(!E(e)||!E(t))return{x:0,y:0};const s={x:t.x??0,y:t.y??0},o={x:t.lx??s.x,y:t.ly??s.y},a=Bi(o,s),c=ze-1,l=rn-1;for(let u=0;u(e[e.CATEGORY=0]="CATEGORY",e[e.COLLISION=1]="COLLISION",e[e.COLOR=2]="COLOR",e[e.KIND=3]="KIND",e[e.DIR=4]="DIR",e[e.NUMBER=5]="NUMBER",e[e.STRING=6]="STRING",e[e.NUMBER_OR_STRING=7]="NUMBER_OR_STRING",e[e.MAYBE_CATEGORY=8]="MAYBE_CATEGORY",e[e.MAYBE_COLLISION=9]="MAYBE_COLLISION",e[e.MAYBE_COLOR=10]="MAYBE_COLOR",e[e.MAYBE_KIND=11]="MAYBE_KIND",e[e.MAYBE_DIR=12]="MAYBE_DIR",e[e.MAYBE_NUMBER=13]="MAYBE_NUMBER",e[e.MAYBE_STRING=14]="MAYBE_STRING",e[e.MAYBE_NUMBER_OR_STRING=15]="MAYBE_NUMBER_OR_STRING",e[e.ANY=16]="ANY",e))(q||{});function xt(e,t){throw new Error(`Invalid arg, expected: ${e} but got ${JSON.stringify(t)}`)}function ne(e,t,n){var o,a,c,l;const r=L.words;L.words=e;const i=[];let s=t;for(let u=0;u(Gg(1,e,t),0)).command("synth",(e,t)=>{for(let n=1;n<=8;++n)Zn(n,t);return 0}).command("synth1",(e,t)=>(Zn(1,t),0)).command("synth2",(e,t)=>(Zn(2,t),0)).command("synth3",(e,t)=>(Zn(3,t),0)).command("synth4",(e,t)=>(Zn(4,t),0)).command("synth5",(e,t)=>(Zn(5,t),0)).command("synth6",(e,t)=>(Zn(6,t),0)).command("synth7",(e,t)=>(Zn(7,t),0)).command("synth8",(e,t)=>(Zn(8,t),0)).command("bgplay",(e,t)=>(Gg(0,e,t),0)).command("bgsynth",(e,t)=>(Zn(0,t),0)).command("tts",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.MAYBE_STRING]);return Pb("audio",r??"",n),0});function Ka(e,t,n,r){const i=Ie(t)?t:t.id,s=Ie(t)?void 0:{x:t.x??0,y:t.y??0},o=Ie(n)?n:n.id,a=i??s;E(o)&&E(a)&&e.send(o,r,a)}function wI(e,t,n,r){E(n==null?void 0:n.id)?(n.headless=!0,Qs(e,t,n)):zg(t,r,"empty")}function Hg(e,t,n,r,i){const s=YR(t,n,r,i);if(E(s)){Ka(e,s,e.id(),"thud"),r.kind===We.PLAYER?Ka(e,e.id(),s,"touch"):r.collision===Ye.ISBULLET?Ka(e,e.id(),s,"shot"):Ka(e,e.id(),s,"bump");const o=Ln(t,s);return(s.destructible??(o==null?void 0:o.destructible))&&wI(t,n,s,i),!1}return!0}function Vg(e,t,n){if(!fr(L.element))return 0;const[r,i]=ne(t,0,[q.DIR,q.MAYBE_KIND]),s=i??["bullet"],o=nI(L.book,L.board,s,{x:L.element.x,y:L.element.y});if(E(o)){o.arg=n,o.collision=Ye.ISBULLET,o.stepx=r.x-L.element.x,o.stepy=r.y-L.element.y;const a=Ln(L.book,o),c=o.code??(a==null?void 0:a.code)??"";H_(L.book,L.board,o,c,1),o.x===L.element.x&&o.y===L.element.y?o.headless=!0:e.bucket(o.id)}return e.yield(),0}const vI=lr().command("change",(e,t)=>{if(!E(L.book)||!E(L.board))return 0;const[n,r]=ne(t,0,[q.KIND,q.KIND]);za(L.book,L.board);const i=jo(n)??"",s=ws(L.board,i),o=Mh(s,n),a=jo(r),c=Oh(r),l=Nh(r);return o.forEach(u=>{if(Qi(L.book,u)===a)E(c)&&(u.color=c),E(l)&&(u.bg=l);else{if(E(u.id)&&(Qs(L.book,L.board,u),!Mu(L.book,u,L.timestamp)))return;fr(u)&&Uu(L.book,L.board,r,u)}}),0}).command("put",(e,t)=>{if(!E(L.book)||!E(L.board))return 0;const[n,r]=ne(t,0,[q.DIR,q.KIND]);return za(L.book,L.board),Uu(L.book,L.board,r,n),0}).command("shootwith",(e,t)=>{const[n,r]=ne(t,0,[q.ANY]);return Vg(e,t.slice(r),n)}).command("shoot",Vg).command("throwstar",()=>0);function eo(){return eo=Object.assign||function(e){for(var t=1;t0}function zu(e){Ja++;try{return e()}finally{Ja--,Ja===0&&TI()}}var Wu=!1;function Zg(){return Wu}function Yg(e){Wu=!0;try{e()}finally{Wu=!1}}function AI(e){return function(){return Yg(e)}}var Gu=[];function TI(){var e=[].concat(Gu);Gu=[],Qg(e)}function Qg(e){var t=new Set;e.forEach(function(n){var r;(n.type==="add"||n.type==="delete")&&n.observable[wt].connections.iterate.forEach(function(i){t.add(i)}),(r=n.observable[wt].connections.byKey.get(n.key))==null||r.forEach(function(i){t.add(i)})}),t.forEach(function(n){n.trigger()})}function Xa(e){if(Xg()){Gu.push(e);return}Qg([e])}function e0(e,t){if(e.type==="iterate")e.observable[wt].connections.iterate.add(t);else{var n=e.observable[wt].connections.byKey.get(e.key);n||(n=new Set,e.observable[wt].connections.byKey.set(e.key,n)),n.add(t)}}function Za(e,t){if(!Zg()){var n=Jg();n&&(e0(e,n),n.registerConnection(e)),t&&(e0(e,t),t.registerConnection(e))}}var Hu=Symbol("$skipreactive"),wt=Symbol("$reactive"),kn=Symbol("$reactiveproxy");function to(e,t){return!!(e&&e[kn]&&e[kn].implicitObserver===t)}function Vu(e){return e[Hu]=!0,e}function t0(e){return!!(e&&!to(e)&&e[wt])}function Ku(e,t,n){if(n===void 0&&(n=!1),e[Hu]||to(e,t))return e;var r=xI(e,n);if(!t)return r;var i=r[wt].proxiesWithImplicitObserver.get(t);if(!i){var s={implicitObserver:t};Object.setPrototypeOf(s,n0),i=new Proxy(r[wt].raw,s),r[wt].proxiesWithImplicitObserver.set(t,i)}return i}var no=Ku;function xI(e,t){if(t===void 0&&(t=!1),to(e))return e;if(t0(e))return e[wt].proxy;if(e[wt]||e[kn])throw new Error("unexpected");var n={connections:{iterate:new Set,byKey:new Map},proxy:{},raw:e,proxiesWithImplicitObserver:new Map,shallow:t};Object.defineProperty(e,wt,{enumerable:!1,writable:!0,configurable:!0,value:n});var r=new Proxy(e,n0);return n.proxy=r,r}var n0={has:function(t,n){var r=Reflect.has(t,n);return typeof n=="symbol"||Za({observable:t,key:n,type:"has"},this.implicitObserver),r},get:function(t,n,r){if(n===kn)return{implicitObserver:this.implicitObserver};var i=Reflect.get(t,n,r);if(typeof n=="symbol")return n.toString()==="Symbol($reactiveproxy)"&&console.error("warning, Symbol($reactiveproxy) passed, but does not match $reactiveproxy. Multiple Reactive libraries loaded?"),i;if(n==="length"&&Array.isArray(t)?Za({observable:t,type:"iterate"},this.implicitObserver):Za({observable:t,key:n,type:"get"},this.implicitObserver),t0(i))return Ku(i,this.implicitObserver);if(t[wt].shallow)return i;if(typeof i=="object"&&i!==null&&!to(i,this.implicitObserver)&&!Object.isFrozen(i)){var s=Reflect.getOwnPropertyDescriptor(t,n);if((!s||!(s.writable===!1&&s.configurable===!1))&&(qg()||this.implicitObserver))return Ku(i,this.implicitObserver)}return i},ownKeys:function(t){return Za({observable:t,type:"iterate"},this.implicitObserver),Reflect.ownKeys(t)},set:function(t,n,r,i){return zu(function(){if(typeof n=="symbol")return Reflect.set(t,n,r,i);var s=Object.hasOwnProperty.call(t,n),o=Reflect.get(t,n,i),a=Reflect.set(t,n,r,i);if(!s)Xa({observable:t,key:n,value:r,type:"add"});else if(r!==o)if(n==="length"&&Array.isArray(t)){if(!(onew Map,qu=e=>{const t=Mn();return e.forEach((n,r)=>{t.set(r,n)}),t},Hr=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},CI=(e,t)=>{const n=[];for(const[r,i]of e)n.push(t(i,r));return n},LI=(e,t)=>{for(const[n,r]of e)if(t(r,n))return!0;return!1},ts=()=>new Set,Ju=e=>e[e.length-1],MI=(e,t)=>{for(let n=0;n{this.off(t,r),n(...i)};this.on(t,r)}off(t,n){const r=this._observers.get(t);r!==void 0&&(r.delete(n),r.size===0&&this._observers.delete(t))}emit(t,n){return Vr((this._observers.get(t)||Mn()).values()).forEach(r=>r(...n))}destroy(){this._observers=Mn()}}const Kr=Math.floor,Ya=Math.abs,i0=(e,t)=>ee>t?e:t,s0=e=>e!==0?e<0:1/e<0,o0=1,a0=2,Xu=4,Zu=8,ro=32,kr=64,cn=128,Qa=31,Yu=63,vi=127,DI=2147483647,c0=Number.MAX_SAFE_INTEGER,BI=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&Kr(e)===e),FI=e=>e.toLowerCase(),$I=/^\s*/g,jI=e=>e.replace($I,""),zI=/([A-Z])/g,l0=(e,t)=>jI(e.replace(zI,n=>`${t}${FI(n)}`)),WI=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let i=0;iio.encode(e):WI;let so=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});so&&so.decode(new Uint8Array).length===1&&(so=null);class oo{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const qr=()=>new oo,HI=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(HI(e));let n=0;for(let r=0;r{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Qu=Rt,ve=(e,t)=>{for(;t>vi;)Rt(e,cn|vi&t),t=Kr(t/128);Rt(e,vi&t)},ef=(e,t)=>{const n=s0(t);for(n&&(t=-t),Rt(e,(t>Yu?cn:0)|(n?kr:0)|Yu&t),t=Kr(t/64);t>0;)Rt(e,(t>vi?cn:0)|vi&t),t=Kr(t/128)},tf=new Uint8Array(3e4),KI=tf.length/3,qI=(e,t)=>{if(t.length{const n=unescape(encodeURIComponent(t)),r=n.length;ve(e,r);for(let i=0;i{const n=e.cbuf.length,r=e.cpos,i=i0(n-r,t.length),s=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,s>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(wi(n*2,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)},Pt=(e,t)=>{ve(e,t.byteLength),ec(e,t)},nf=(e,t)=>{VI(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},XI=(e,t)=>nf(e,4).setFloat32(0,t,!1),ZI=(e,t)=>nf(e,8).setFloat64(0,t,!1),YI=(e,t)=>nf(e,8).setBigInt64(0,t,!1),u0=new DataView(new ArrayBuffer(4)),QI=e=>(u0.setFloat32(0,e),u0.getFloat32(0)===e),ao=(e,t)=>{switch(typeof t){case"string":Rt(e,119),ns(e,t);break;case"number":BI(t)&&Ya(t)<=DI?(Rt(e,125),ef(e,t)):QI(t)?(Rt(e,124),XI(e,t)):(Rt(e,123),ZI(e,t));break;case"bigint":Rt(e,122),YI(e,t);break;case"object":if(t===null)Rt(e,126);else if(UI(t)){Rt(e,117),ve(e,t.length);for(let n=0;n0&&ve(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const h0=e=>{e.count>0&&(ef(e.encoder,e.count===1?e.s:-e.s),e.count>1&&ve(e.encoder,e.count-2))};class tc{constructor(){this.encoder=new oo,this.s=0,this.count=0}write(t){this.s===t?this.count++:(h0(this),this.count=1,this.s=t)}toUint8Array(){return h0(this),Un(this.encoder)}}const d0=e=>{if(e.count>0){const t=e.diff*2+(e.count===1?0:1);ef(e.encoder,t),e.count>1&&ve(e.encoder,e.count-2)}};class rf{constructor(){this.encoder=new oo,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(d0(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return d0(this),Un(this.encoder)}}class eO{constructor(){this.sarr=[],this.s="",this.lensE=new tc}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new oo;return this.sarr.push(this.s),this.s="",ns(t,this.sarr.join("")),ec(t,this.lensE.toUint8Array()),Un(t)}}const Jr=e=>new Error(e),Yn=()=>{throw Jr("Method unimplemented")},Qn=()=>{throw Jr("Unexpected case")},p0=Jr("Unexpected end of array"),m0=Jr("Integer out of Range");class nc{constructor(t){this.arr=t,this.pos=0}}const Ei=e=>new nc(e),tO=e=>e.pos!==e.arr.length,nO=(e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Ht=e=>nO(e,Ee(e)),rs=e=>e.arr[e.pos++],Ee=e=>{let t=0,n=1;const r=e.arr.length;for(;e.posc0)throw m0}throw p0},sf=e=>{let t=e.arr[e.pos++],n=t&Yu,r=64;const i=(t&kr)>0?-1:1;if(!(t&cn))return i*n;const s=e.arr.length;for(;e.posc0)throw m0}throw p0},is=so?e=>so.decode(Ht(e)):e=>{let t=Ee(e);if(t===0)return"";{let n=String.fromCodePoint(rs(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(rs(e));else for(;t>0;){const r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},of=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},rO=[e=>{},e=>null,sf,e=>of(e,4).getFloat32(0,!1),e=>of(e,8).getFloat64(0,!1),e=>of(e,8).getBigInt64(0,!1),e=>!1,e=>!0,is,e=>{const t=Ee(e),n={};for(let r=0;r{const t=Ee(e),n=[];for(let r=0;rrO[127-rs(e)](e);class g0 extends nc{constructor(t,n){super(t),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),tO(this)?this.count=Ee(this)+1:this.count=-1),this.count--,this.s}}class rc extends nc{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=sf(this);const t=s0(this.s);this.count=1,t&&(this.s=-this.s,this.count=Ee(this)+2)}return this.count--,this.s}}class af extends nc{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=sf(this),n=t&1;this.diff=Kr(t/2),this.count=1,n&&(this.count=Ee(this)+2)}return this.s+=this.diff,this.count--,this.s}}class iO{constructor(t){this.decoder=new rc(t),this.str=is(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const sO=crypto.getRandomValues.bind(crypto),y0=()=>sO(new Uint32Array(1))[0],oO="10000000-1000-4000-8000"+-1e11,aO=()=>oO.replace(/[018]/g,e=>(e^y0()&15>>e/4).toString(16)),_0=e=>new Promise(e);Promise.all.bind(Promise);const b0=e=>e===void 0?null:e;class cO{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let w0=new cO,lO=!0;try{typeof localStorage<"u"&&localStorage&&(w0=localStorage,lO=!1)}catch{}const uO=w0,fO=Object.assign,hO=Object.keys,dO=(e,t)=>{for(const n in e)t(e[n],n)},v0=e=>hO(e).length,pO=e=>{for(const t in e)return!1;return!0},mO=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},gO=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),yO=(e,t)=>e===t||v0(e)===v0(t)&&mO(e,(n,r)=>(n!==void 0||gO(t,r))&&t[r]===n),_O=Object.freeze,E0=e=>{for(const t in e){const n=e[t];(typeof n=="object"||typeof n=="function")&&E0(e[t])}return _O(e)},cf=(e,t,n=0)=>{try{for(;ne,wO=(e,t)=>t.includes(e);var k0={};const lo=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let er;const vO=()=>{if(er===void 0)if(lo){er=Mn();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");er.set(`--${l0(t,"-")}`,n),er.set(`-${l0(t,"-")}`,n)}})):er=Mn();return er},lf=e=>vO().has(e),ic=e=>b0(lo?k0[e.toUpperCase().replaceAll("-","_")]:uO.getItem(e)),S0=e=>lf("--"+e)||ic(e)!==null;S0("production");const EO=lo&&wO(k0.FORCE_COLOR,["true","1","2"])||!lf("--no-colors")&&!S0("no-color")&&(!lo||process.stdout.isTTY)&&(!lo||lf("--color")||ic("COLORTERM")!==null||(ic("TERM")||"").includes("color")),kO=e=>new Uint8Array(e),SO=e=>{const t=kO(e.byteLength);return t.set(e),t};class AO{constructor(t,n){this.left=t,this.right=n}}const Sr=(e,t)=>new AO(e,t);typeof DOMParser<"u"&&new DOMParser;const TO=e=>CI(e,(t,n)=>`${n}:${t};`).join(""),Ar=Symbol,A0=Ar(),T0=Ar(),xO=Ar(),RO=Ar(),IO=Ar(),x0=Ar(),OO=Ar(),uf=Ar(),NO=Ar(),CO=e=>{var i;e.length===1&&((i=e[0])==null?void 0:i.constructor)===Function&&(e=e[0]());const t=[],n=[];let r=0;for(;r0&&n.push(t.join(""));r{var o;e.length===1&&((o=e[0])==null?void 0:o.constructor)===Function&&(e=e[0]());const t=[],n=[],r=Mn();let i=[],s=0;for(;s0||l.length>0?(t.push("%c"+a),n.push(l)):t.push(a)}else break}}for(s>0&&(i=n,i.unshift(t.join("")));s{console.log(...R0(e)),I0.forEach(t=>t.print(e))},UO=(...e)=>{console.warn(...R0(e)),e.unshift(uf),I0.forEach(t=>t.print(e))},I0=ts(),O0=e=>({[Symbol.iterator](){return this},next:e}),PO=(e,t)=>O0(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),ff=(e,t)=>O0(()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});class hf{constructor(t,n){this.clock=t,this.len=n}}class uo{constructor(){this.clients=new Map}}const N0=(e,t,n)=>t.clients.forEach((r,i)=>{const s=e.doc.store.clients.get(i);for(let o=0;o{let n=0,r=e.length-1;for(;n<=r;){const i=Kr((n+r)/2),s=e[i],o=s.clock;if(o<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&DO(n,t.clock)!==null},df=e=>{e.clients.forEach(t=>{t.sort((i,s)=>i.clock-s.clock);let n,r;for(n=1,r=1;n=s.clock?i.len=wi(i.len,s.clock+s.len-i.clock):(r{const t=new uo;for(let n=0;n{if(!t.clients.has(i)){const s=r.slice();for(let o=n+1;o{Hr(e.clients,t,()=>[]).push(new hf(n,r))},FO=()=>new uo,$O=e=>{const t=FO();return e.clients.forEach((n,r)=>{const i=[];for(let s=0;s0&&t.clients.set(r,i)}),t},ss=(e,t)=>{ve(e.restEncoder,t.clients.size),Vr(t.clients.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{e.resetDsCurVal(),ve(e.restEncoder,n);const i=r.length;ve(e.restEncoder,i);for(let s=0;s{const t=new uo,n=Ee(e.restDecoder);for(let r=0;r0){const o=Hr(t.clients,i,()=>[]);for(let a=0;a{const r=new uo,i=Ee(e.restDecoder);for(let s=0;s0){const s=new ki;return ve(s.restEncoder,0),ss(s,r),s.toUint8Array()}return null},M0=y0;class Tr extends PI{constructor({guid:t=aO(),collectionid:n=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:a=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=M0(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new V0,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=_0(l=>{this.on("load",()=>{this.isLoaded=!0,l(this)})});const c=()=>_0(l=>{const u=f=>{(f===void 0||f===!0)&&(this.off("sync",u),l())};this.on("sync",u)});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const t=this._item;t!==null&&!this.shouldLoad&&Xe(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Vr(this.subdocs).map(t=>t.guid))}transact(t,n=null){return Xe(this,t,n)}get(t,n=at){const r=Hr(this.share,t,()=>{const s=new n;return s._integrate(this,null),s}),i=r.constructor;if(n!==at&&i!==n)if(i===at){const s=new n;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(t,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return r}getArray(t=""){return this.get(t,tr)}getText(t=""){return this.get(t,Dn)}getMap(t=""){return this.get(t,nr)}getXmlElement(t=""){return this.get(t,xr)}getXmlFragment(t=""){return this.get(t,rr)}toJSON(){const t={};return this.share.forEach((n,r)=>{t[r]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,Vr(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new Tr({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,Xe(t.parent.doc,r=>{const i=n.doc;t.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class U0{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return Ee(this.restDecoder)}readDsLen(){return Ee(this.restDecoder)}}class P0 extends U0{readLeftID(){return Ne(Ee(this.restDecoder),Ee(this.restDecoder))}readRightID(){return Ne(Ee(this.restDecoder),Ee(this.restDecoder))}readClient(){return Ee(this.restDecoder)}readInfo(){return rs(this.restDecoder)}readString(){return is(this.restDecoder)}readParentInfo(){return Ee(this.restDecoder)===1}readTypeRef(){return Ee(this.restDecoder)}readLen(){return Ee(this.restDecoder)}readAny(){return co(this.restDecoder)}readBuf(){return SO(Ht(this.restDecoder))}readJSON(){return JSON.parse(is(this.restDecoder))}readKey(){return is(this.restDecoder)}}class jO{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Ee(this.restDecoder),this.dsCurrVal}readDsLen(){const t=Ee(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class os extends jO{constructor(t){super(t),this.keys=[],Ee(t),this.keyClockDecoder=new af(Ht(t)),this.clientDecoder=new rc(Ht(t)),this.leftClockDecoder=new af(Ht(t)),this.rightClockDecoder=new af(Ht(t)),this.infoDecoder=new g0(Ht(t),rs),this.stringDecoder=new iO(Ht(t)),this.parentInfoDecoder=new g0(Ht(t),rs),this.typeRefDecoder=new rc(Ht(t)),this.lenDecoder=new rc(Ht(t))}readLeftID(){return new as(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new as(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return co(this.restDecoder)}readBuf(){return Ht(this.restDecoder)}readJSON(){return co(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{r=wi(r,t[0].id.clock);const i=Pn(t,r);ve(e.restEncoder,t.length-i),e.writeClient(n),ve(e.restEncoder,r);const s=t[i];s.write(e,r-s.id.clock);for(let o=i+1;o{const r=new Map;n.forEach((i,s)=>{It(t,s)>i&&r.set(s,i)}),ac(t).forEach((i,s)=>{n.has(s)||r.set(s,0)}),ve(e.restEncoder,r.size),Vr(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{zO(e,t.clients.get(i),i,s)})},WO=(e,t)=>{const n=Mn(),r=Ee(e.restDecoder);for(let i=0;i{const r=[];let i=Vr(n.keys()).sort((h,p)=>h-p);if(i.length===0)return null;const s=()=>{if(i.length===0)return null;let h=n.get(i[i.length-1]);for(;h.refs.length===h.i;)if(i.pop(),i.length>0)h=n.get(i[i.length-1]);else return null;return h};let o=s();if(o===null)return null;const a=new V0,c=new Map,l=(h,p)=>{const m=c.get(h);(m==null||m>p)&&c.set(h,p)};let u=o.refs[o.i++];const f=new Map,d=()=>{for(const h of r){const p=h.id.client,m=n.get(p);m?(m.i--,a.clients.set(p,m.refs.slice(m.i)),n.delete(p),m.i=0,m.refs=[]):a.clients.set(p,[h]),i=i.filter(b=>b!==p)}r.length=0};for(;;){if(u.constructor!==Sn){const p=Hr(f,u.id.client,()=>It(t,u.id.client))-u.id.clock;if(p<0)r.push(u),l(u.id.client,u.id.clock-1),d();else{const m=u.getMissing(e,t);if(m!==null){r.push(u);const b=n.get(m)||{refs:[],i:0};if(b.refs.length===b.i)l(m,It(t,m)),d();else{u=b.refs[b.i++];continue}}else(p===0||p0)u=r.pop();else if(o!==null&&o.i0){const h=new ki;return mf(h,a,new Map),ve(h.restEncoder,0),{missing:c,update:h.toUint8Array()}}return null},HO=(e,t)=>mf(e,t.doc.store,t.beforeState),VO=(e,t,n,r=new os(e))=>Xe(t,i=>{i.local=!1;let s=!1;const o=i.doc,a=o.store,c=WO(r,o),l=GO(i,a,c),u=a.pendingStructs;if(u){for(const[d,h]of u.missing)if(hh)&&u.missing.set(d,h)}u.update=lc([u.update,l.update])}}else a.pendingStructs=l;const f=L0(r,i,a);if(a.pendingDs){const d=new os(Ei(a.pendingDs));Ee(d.restDecoder);const h=L0(d,i,a);f&&h?a.pendingDs=lc([f,h]):a.pendingDs=f||h}else a.pendingDs=f;if(s){const d=a.pendingStructs.update;a.pendingStructs=null,F0(i.doc,d)}},n,!1),F0=(e,t,n,r=os)=>{const i=Ei(t);VO(i,e,n,new r(i))},KO=(e,t,n)=>F0(e,t,n,P0),qO=(e,t,n=new Map)=>{mf(e,t.store,n),ss(e,$O(t.store))},JO=(e,t=new Uint8Array([0]),n=new ki)=>{const r=$0(t);qO(n,e,r);const i=[n.toUint8Array()];if(e.store.pendingDs&&i.push(e.store.pendingDs),e.store.pendingStructs&&i.push(uN(e.store.pendingStructs.update,t)),i.length>1){if(n.constructor===fo)return cN(i.map((s,o)=>o===0?s:hN(s)));if(n.constructor===ki)return lc(i)}return i[0]},XO=(e,t)=>JO(e,t,new fo),ZO=e=>{const t=new Map,n=Ee(e.restDecoder);for(let r=0;rZO(new U0(Ei(e))),j0=(e,t)=>(ve(e.restEncoder,t.size),Vr(t.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{ve(e.restEncoder,n),ve(e.restEncoder,r)}),e),YO=(e,t)=>j0(e,ac(t.store)),QO=(e,t=new B0)=>(e instanceof Map?j0(t,e):YO(t,e),t.toUint8Array()),eN=e=>QO(e,new D0);class tN{constructor(){this.l=[]}}const z0=()=>new tN,W0=(e,t)=>e.l.push(t),G0=(e,t)=>{const n=e.l,r=n.length;e.l=n.filter(i=>t!==i),r===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},H0=(e,t,n)=>cf(e.l,[t,n]);class as{constructor(t,n){this.client=t,this.clock=n}}const oc=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,Ne=(e,t)=>new as(e,t),nN=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Qn()},cs=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!C0(t.ds,e.id),gf=(e,t)=>{const n=Hr(e.meta,gf,ts),r=e.doc.store;n.has(t)||(t.sv.forEach((i,s)=>{i{}),n.add(t))};class V0{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ac=e=>{const t=new Map;return e.clients.forEach((n,r)=>{const i=n[n.length-1];t.set(r,i.id.clock+i.length)}),t},It=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const r=n[n.length-1];return r.id.clock+r.length},K0=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const r=n[n.length-1];if(r.id.clock+r.length!==t.id.clock)throw Qn()}n.push(t)},Pn=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=Kr(t/(s+i.length-1)*r);for(;n<=r;){if(i=e[o],s=i.id.clock,s<=t){if(t{const n=e.clients.get(t.client);return n[Pn(n,t.clock)]},_f=(e,t,n)=>{const r=Pn(t,n),i=t[r];return i.id.clock{const n=e.doc.store.clients.get(t.client);return n[_f(e,n,t.clock)]},q0=(e,t,n)=>{const r=t.clients.get(n.client),i=Pn(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==ln&&r.splice(i+1,0,_c(e,s,n.clock-s.id.clock+1)),s},rN=(e,t,n)=>{const r=e.clients.get(t.id.client);r[Pn(r,t.id.clock)]=n},J0=(e,t,n,r,i)=>{if(r===0)return;const s=n+r;let o=_f(e,t,n),a;do a=t[o++],st.deleteSet.clients.size===0&&!LI(t.afterState,(n,r)=>t.beforeState.get(r)!==n)?!1:(df(t.deleteSet),HO(e,t),ss(e,t.deleteSet),!0),Z0=(e,t,n)=>{const r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Hr(e.changed,t,ts).add(n)},cc=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof Et&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}const s=t-i;return s&&e.splice(t+1-s,s),s},sN=(e,t,n)=>{for(const[r,i]of e.clients.entries()){const s=t.clients.get(r);for(let o=i.length-1;o>=0;o--){const a=i[o],c=a.clock+a.len;for(let l=Pn(s,a.clock),u=s[l];l{e.clients.forEach((n,r)=>{const i=t.clients.get(r);for(let s=n.length-1;s>=0;s--){const o=n[s],a=i0(i.length-1,1+Pn(i,o.clock+o.len-1));for(let c=a,l=i[c];c>0&&l.id.clock>=o.clock;l=i[c])c-=1+cc(i,c)}})},Y0=(e,t)=>{if(ta.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(n,c)})),a.push(()=>{n.changedParentTypes.forEach((c,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=l,u._path=null}),c.sort((u,f)=>u.path.length-f.path.length),H0(l._dEH,c,n))})}),a.push(()=>r.emit("afterTransaction",[n,r])),cf(a,[]),n._needFormattingCleanup&&TN(n)}finally{r.gc&&sN(s,i,r.gcFilter),oN(s,i),n.afterState.forEach((u,f)=>{const d=n.beforeState.get(f)||0;if(d!==u){const h=i.clients.get(f),p=wi(Pn(h,d),1);for(let m=h.length-1;m>=p;)m-=1+cc(h,m)}});for(let u=o.length-1;u>=0;u--){const{client:f,clock:d}=o[u].id,h=i.clients.get(f),p=Pn(h,d);p+11||p>0&&cc(h,p)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(MO(uf,A0,"[yjs] ",T0,x0,"Changed the client-id because another client seems to be using it."),r.clientID=M0()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const u=new fo;X0(u,n)&&r.emit("update",[u.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const u=new ki;X0(u,n)&&r.emit("updateV2",[u.toUint8Array(),n.origin,r,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:l}=n;(a.size>0||l.size>0||c.size>0)&&(a.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),l.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:c,added:a,removed:l},r,n]),l.forEach(u=>u.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):Y0(e,t+1)}}},Xe=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;e._transaction===null&&(s=!0,e._transaction=new iN(e,n,r),i.push(e._transaction),i.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(s){const a=e._transaction===i[0];e._transaction=null,a&&Y0(i,0)}}return o};function*aN(e){const t=Ee(e.restDecoder);for(let n=0;nlc(e,P0,fo),lN=(e,t)=>{if(e.constructor===ln){const{client:n,clock:r}=e.id;return new ln(Ne(n,r+t),e.length-t)}else if(e.constructor===Sn){const{client:n,clock:r}=e.id;return new Sn(Ne(n,r+t),e.length-t)}else{const n=e,{client:r,clock:i}=n.id;return new Et(Ne(r,i+t),null,Ne(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},lc=(e,t=os,n=ki)=>{if(e.length===1)return e[0];const r=e.map(u=>new t(Ei(u)));let i=r.map(u=>new bf(u,!0)),s=null;const o=new n,a=new wf(o);for(;i=i.filter(d=>d.curr!==null),i.sort((d,h)=>{if(d.curr.id.client===h.curr.id.client){const p=d.curr.id.clock-h.curr.id.clock;return p===0?d.curr.constructor===h.curr.constructor?0:d.curr.constructor===Sn?1:-1:p}else return h.curr.id.client-d.curr.id.client}),i.length!==0;){const u=i[0],f=u.curr.id.client;if(s!==null){let d=u.curr,h=!1;for(;d!==null&&d.id.clock+d.length<=s.struct.id.clock+s.struct.length&&d.id.client>=s.struct.id.client;)d=u.next(),h=!0;if(d===null||d.id.client!==f||h&&d.id.clock>s.struct.id.clock+s.struct.length)continue;if(f!==s.struct.id.client)Zr(a,s.struct,s.offset),s={struct:d,offset:0},u.next();else if(s.struct.id.clock+s.struct.length0&&(s.struct.constructor===Sn?s.struct.length-=p:d=lN(d,p)),s.struct.mergeWith(d)||(Zr(a,s.struct,s.offset),s={struct:d,offset:0},u.next())}}else s={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===f&&d.id.clock===s.struct.id.clock+s.struct.length&&d.constructor!==Sn;d=u.next())Zr(a,s.struct,s.offset),s={struct:d,offset:0}}s!==null&&(Zr(a,s.struct,s.offset),s=null),vf(a);const c=r.map(u=>pf(u)),l=BO(c);return ss(o,l),o.toUint8Array()},uN=(e,t,n=os,r=ki)=>{const i=$0(t),s=new r,o=new wf(s),a=new n(Ei(e)),c=new bf(a,!1);for(;c.curr;){const u=c.curr,f=u.id.client,d=i.get(f)||0;if(c.curr.constructor===Sn){c.next();continue}if(u.id.clock+u.length>d)for(Zr(o,u,wi(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===f;)Zr(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===f&&c.curr.id.clock+c.curr.length<=d;)c.next()}vf(o);const l=pf(a);return ss(s,l),s.toUint8Array()},Q0=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Un(e.encoder.restEncoder)}),e.encoder.restEncoder=qr(),e.written=0)},Zr=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Q0(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),ve(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},vf=e=>{Q0(e);const t=e.encoder.restEncoder;ve(t,e.clientStructs.length);for(let n=0;n{const i=new n(Ei(e)),s=new bf(i,!1),o=new r,a=new wf(o);for(let l=s.curr;l!==null;l=s.next())Zr(a,t(l),0);vf(a);const c=pf(i);return ss(o,c),o.toUint8Array()},hN=e=>fN(e,bO,os,fo),ey="You must not compute changes after the event-handler fired.";class uc{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=dN(this.currentTarget,this.target))}deletes(t){return C0(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Jr(ey);const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(i=>{if(i!==null){const s=n._map.get(i);let o,a;if(this.adds(s)){let c=s.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(s))if(c!==null&&this.deletes(c))o="delete",a=Ju(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",a=Ju(c.content.getContent())):(o="add",a=void 0)}else if(this.deletes(s))o="delete",a=Ju(s.content.getContent());else return;t.set(i,{action:o,oldValue:a})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw Jr(ey);const n=this.target,r=ts(),i=ts(),s=[];if(t={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(n).has(null)){let a=null;const c=()=>{a&&s.push(a)};for(let l=n._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=l.length,i.add(l)):this.adds(l)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(l.content.getContent()),r.add(l)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=l.length);a!==null&&a.retain===void 0&&c()}this._changes=t}return t}}const dN=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let r=0,i=t._item.parent._start;for(;i!==t._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;n.unshift(r)}t=t._item.parent}return n},Dt=()=>{UO("Invalid access: Add Yjs type to a document before reading data.")},ty=80;let Ef=0;class pN{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=Ef++}}const mN=e=>{e.timestamp=Ef++},ny=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Ef++},gN=(e,t,n)=>{if(e.length>=ty){const r=e.reduce((i,s)=>i.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((s,o)=>Ya(t-s.index)t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&Ya(n.index-i){for(let r=e.length-1;r>=0;r--){const i=e[r];if(n>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){e.splice(r,1);continue}i.p=s,s.marker=!0}(t0&&t===i.index)&&(i.index=wi(t,i.index+n))}},hc=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;Hr(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;H0(r._eH,n,t)};class at{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=z0(),this._dEH=z0(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw Yn()}clone(){throw Yn()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){W0(this._eH,t)}observeDeep(t){W0(this._dEH,t)}unobserve(t){G0(this._eH,t)}unobserveDeep(t){G0(this._dEH,t)}toJSON(){}}const ry=(e,t,n)=>{e.doc??Dt(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const i=[];let s=e._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){const o=s.content.getContent();if(o.length<=t)t-=o.length;else{for(let a=t;a0;a++)i.push(o[a]),r--;t=0}}s=s.right}return i},iy=e=>{e.doc??Dt();const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let i=0;i{let n=0,r=e._start;for(e.doc??Dt();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let s=0;s{const n=[];return po(e,(r,i)=>{n.push(t(r,i,e))}),n},yN=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const i=n[r++];return n.length<=r&&(n=null),{done:!1,value:i}}}},oy=(e,t)=>{e.doc??Dt();const n=fc(e,t);let r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t{let i=n;const s=e.doc,o=s.clientID,a=s.store,c=n===null?t._start:n.right;let l=[];const u=()=>{l.length>0&&(i=new Et(Ne(o,It(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Ti(l)),i.integrate(e,0),l=[])};r.forEach(f=>{if(f===null)l.push(f);else switch(f.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(f);break;default:switch(u(),f.constructor){case Uint8Array:case ArrayBuffer:i=new Et(Ne(o,It(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new mo(new Uint8Array(f))),i.integrate(e,0);break;case Tr:i=new Et(Ne(o,It(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new yo(f)),i.integrate(e,0);break;default:if(f instanceof at)i=new Et(Ne(o,It(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Rr(f)),i.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},ay=()=>Jr("Length exceeded!"),cy=(e,t,n,r)=>{if(n>t._length)throw ay();if(n===0)return t._searchMarker&&ho(t._searchMarker,n,r.length),dc(e,t,null,r);const i=n,s=fc(t,n);let o=t._start;for(s!==null&&(o=s.p,n-=s.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let i=(t._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:t._start}).p;if(i)for(;i.right;)i=i.right;return dc(e,t,i,n)},ly=(e,t,n,r)=>{if(r===0)return;const i=n,s=r,o=fc(t,n);let a=t._start;for(o!==null&&(a=o.p,n-=o.index);a!==null&&n>0;a=a.right)!a.deleted&&a.countable&&(n0&&a!==null;)a.deleted||(r0)throw ay();t._searchMarker&&ho(t._searchMarker,i,-s+r)},pc=(e,t,n)=>{const r=t._map.get(n);r!==void 0&&r.delete(e)},kf=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let a;if(r==null)a=new Ti([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:a=new Ti([r]);break;case Uint8Array:a=new mo(r);break;case Tr:a=new yo(r);break;default:if(r instanceof at)a=new Rr(r);else throw new Error("Unexpected content type")}new Et(Ne(o,It(s.store,o)),i,i&&i.lastId,null,null,t,n,a).integrate(e,0)},Sf=(e,t)=>{e.doc??Dt();const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},uy=e=>{const t={};return e.doc??Dt(),e._map.forEach((n,r)=>{n.deleted||(t[r]=n.content.getContent()[n.length-1])}),t},fy=(e,t)=>{e.doc??Dt();const n=e._map.get(t);return n!==void 0&&!n.deleted},bN=(e,t)=>{const n={};return e._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!t.sv.has(s.id.client)||s.id.clock>=(t.sv.get(s.id.client)||0));)s=s.left;s!==null&&cs(s,t)&&(n[i]=s.content.getContent()[s.length-1])}),n},mc=e=>(e.doc??Dt(),PO(e._map.entries(),t=>!t[1].deleted));class wN extends uc{}class tr extends at{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new tr;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new tr}clone(){const t=new tr;return t.insert(0,this.toArray().map(n=>n instanceof at?n.clone():n)),t}get length(){return this.doc??Dt(),this._length}_callObserver(t,n){super._callObserver(t,n),hc(this,t,new wN(this,t))}insert(t,n){this.doc!==null?Xe(this.doc,r=>{cy(r,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?Xe(this.doc,n=>{_N(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?Xe(this.doc,r=>{ly(r,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return oy(this,t)}toArray(){return iy(this)}slice(t=0,n=this.length){return ry(this,t,n)}toJSON(){return this.map(t=>t instanceof at?t.toJSON():t)}map(t){return sy(this,t)}forEach(t){po(this,t)}[Symbol.iterator](){return yN(this)}_write(t){t.writeTypeRef(HN)}}const vN=e=>new tr;class EN extends uc{constructor(t,n,r){super(t,n),this.keysChanged=r}}class nr extends at{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new nr}clone(){const t=new nr;return this.forEach((n,r)=>{t.set(r,n instanceof at?n.clone():n)}),t}_callObserver(t,n){hc(this,t,new EN(this,t,n))}toJSON(){this.doc??Dt();const t={};return this._map.forEach((n,r)=>{if(!n.deleted){const i=n.content.getContent()[n.length-1];t[r]=i instanceof at?i.toJSON():i}}),t}get size(){return[...mc(this)].length}keys(){return ff(mc(this),t=>t[0])}values(){return ff(mc(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return ff(mc(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Dt(),this._map.forEach((n,r)=>{n.deleted||t(n.content.getContent()[n.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?Xe(this.doc,n=>{pc(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?Xe(this.doc,r=>{kf(r,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return Sf(this,t)}has(t){return fy(this,t)}clear(){this.doc!==null?Xe(this.doc,t=>{this.forEach(function(n,r,i){pc(t,i,r)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(VN)}}const kN=e=>new nr,Yr=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&yO(e,t);class Af{constructor(t,n,r,i){this.left=t,this.right=n,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Qn(),this.right.content.constructor){case vt:this.right.deleted||ls(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const hy=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case vt:t.right.deleted||ls(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n{const i=new Map,s=r?fc(t,n):null;if(s){const o=new Af(s.p.left,s.p,s.index,i);return hy(e,o,n-s.index)}else{const o=new Af(null,t._start,0,i);return hy(e,o,n)}},dy=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===vt&&Yr(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=e.doc,s=i.clientID;r.forEach((o,a)=>{const c=n.left,l=n.right,u=new Et(Ne(s,It(i.store,s)),c,c&&c.lastId,l,l&&l.id,t,null,new vt(a,o));u.integrate(e,0),n.right=u,n.forward()})},ls=(e,t)=>{const{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},py=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===vt&&Yr(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},my=(e,t,n,r)=>{const i=e.doc,s=i.clientID,o=new Map;for(const a in r){const c=r[a],l=n.currentAttributes.get(a)??null;if(!Yr(l,c)){o.set(a,l);const{left:u,right:f}=n;n.right=new Et(Ne(s,It(i.store,s)),u,u&&u.lastId,f,f&&f.id,t,null,new vt(a,c)),n.right.integrate(e,0),n.forward()}}return o},Tf=(e,t,n,r,i)=>{n.currentAttributes.forEach((d,h)=>{i[h]===void 0&&(i[h]=null)});const s=e.doc,o=s.clientID;py(n,i);const a=my(e,t,n,i),c=r.constructor===String?new ir(r):r instanceof at?new Rr(r):new Ai(r);let{left:l,right:u,index:f}=n;t._searchMarker&&ho(t._searchMarker,n.index,c.getLength()),u=new Et(Ne(o,It(s.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=f,n.forward(),dy(e,t,n,a)},gy=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;py(n,i);const a=my(e,t,n,i);e:for(;n.right!==null&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===vt));){if(!n.right.deleted)switch(n.right.content.constructor){case vt:{const{key:c,value:l}=n.right.content,u=i[c];if(u!==void 0){if(Yr(u,l))a.delete(c);else{if(r===0)break e;a.set(c,l)}n.right.delete(e)}else n.currentAttributes.set(c,l);break}default:r0){let c="";for(;r>0;r--)c+=` -`;n.right=new Et(Ne(o,It(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new ir(c)),n.right.integrate(e,0),n.forward()}dy(e,t,n,a)},yy=(e,t,n,r,i)=>{let s=t;const o=Mn();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===vt){const l=s.content;o.set(l.key,l)}s=s.right}let a=0,c=!1;for(;t!==s;){if(n===t&&(c=!0),!t.deleted){const l=t.content;switch(l.constructor){case vt:{const{key:u,value:f}=l,d=r.get(u)??null;(o.get(u)!==l||d===f)&&(t.delete(e),a++,!c&&(i.get(u)??null)===f&&d!==f&&(d===null?i.delete(u):i.set(u,d))),!c&&!t.deleted&&ls(i,l);break}}}t=t.right}return a},SN=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===vt){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},AN=e=>{let t=0;return Xe(e.doc,n=>{let r=e._start,i=e._start,s=Mn();const o=qu(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case vt:ls(o,i.content);break;default:t+=yy(n,r,i,s,o),s=qu(o),r=i;break}i=i.right}}),t},TN=e=>{const t=new Set,n=e.doc;for(const[r,i]of e.afterState.entries()){const s=e.beforeState.get(r)||0;i!==s&&J0(e,n.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===vt&&o.constructor!==ln&&t.add(o.parent)})}Xe(n,r=>{N0(e,e.deleteSet,i=>{if(i instanceof ln||!i.parent._hasFormatting||t.has(i.parent))return;const s=i.parent;i.content.constructor===vt?t.add(s):SN(r,i)});for(const i of t)AN(i)})},_y=(e,t,n)=>{const r=n,i=qu(t.currentAttributes),s=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Rr:case Ai:case ir:n{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];Xe(t,r=>{const i=new Map,s=new Map;let o=this.target._start,a=null;const c={};let l="",u=0,f=0;const d=()=>{if(a!==null){let h=null;switch(a){case"delete":f>0&&(h={delete:f}),f=0;break;case"insert":(typeof l=="object"||l.length>0)&&(h={insert:l},i.size>0&&(h.attributes={},i.forEach((p,m)=>{p!==null&&(h.attributes[m]=p)}))),l="";break;case"retain":u>0&&(h={retain:u},pO(c)||(h.attributes=fO({},c))),u=0;break}h&&n.push(h),a=null}};for(;o!==null;){switch(o.content.constructor){case Rr:case Ai:this.adds(o)?this.deletes(o)||(d(),a="insert",l=o.content.getContent()[0],d()):this.deletes(o)?(a!=="delete"&&(d(),a="delete"),f+=1):o.deleted||(a!=="retain"&&(d(),a="retain"),u+=1);break;case ir:this.adds(o)?this.deletes(o)||(a!=="insert"&&(d(),a="insert"),l+=o.content.str):this.deletes(o)?(a!=="delete"&&(d(),a="delete"),f+=o.length):o.deleted||(a!=="retain"&&(d(),a="retain"),u+=o.length);break;case vt:{const{key:h,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const m=i.get(h)??null;Yr(m,p)?p!==null&&o.delete(r):(a==="retain"&&d(),Yr(p,s.get(h)??null)?delete c[h]:c[h]=p)}}else if(this.deletes(o)){s.set(h,p);const m=i.get(h)??null;Yr(m,p)||(a==="retain"&&d(),c[h]=m)}else if(!o.deleted){s.set(h,p);const m=c[h];m!==void 0&&(Yr(m,p)?m!==null&&o.delete(r):(a==="retain"&&d(),p===null?delete c[h]:c[h]=p))}o.deleted||(a==="insert"&&d(),ls(i,o.content));break}}o=o.right}for(d();n.length>0;){const h=n[n.length-1];if(h.retain!==void 0&&h.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Dn extends at{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Dt(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new Dn}clone(){const t=new Dn;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const r=new xN(this,t,n);hc(this,t,r),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Dt();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===ir&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?Xe(this.doc,r=>{const i=new Af(null,this._start,0,new Map);for(let s=0;s0)&&Tf(r,this,i,a,o.attributes||{})}else o.retain!==void 0?gy(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&_y(r,i,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,r){this.doc??Dt();const i=[],s=new Map,o=this.doc;let a="",c=this._start;function l(){if(a.length>0){const f={};let d=!1;s.forEach((p,m)=>{d=!0,f[m]=p});const h={insert:a};d&&(h.attributes=f),i.push(h),a=""}}const u=()=>{for(;c!==null;){if(cs(c,t)||n!==void 0&&cs(c,n))switch(c.content.constructor){case ir:{const f=s.get("ychange");t!==void 0&&!cs(c,t)?(f===void 0||f.user!==c.id.client||f.type!=="removed")&&(l(),s.set("ychange",r?r("removed",c.id):{type:"removed"})):n!==void 0&&!cs(c,n)?(f===void 0||f.user!==c.id.client||f.type!=="added")&&(l(),s.set("ychange",r?r("added",c.id):{type:"added"})):f!==void 0&&(l(),s.delete("ychange")),a+=c.content.str;break}case Rr:case Ai:{l();const f={insert:c.content.getContent()[0]};if(s.size>0){const d={};f.attributes=d,s.forEach((h,p)=>{d[p]=h})}i.push(f);break}case vt:cs(c,t)&&(l(),ls(s,c.content));break}c=c.right}l()};return t||n?Xe(o,f=>{t&&gf(f,t),n&&gf(f,n),u()},"cleanup"):u(),i}insert(t,n,r){if(n.length<=0)return;const i=this.doc;i!==null?Xe(i,s=>{const o=gc(s,this,t,!r);r||(r={},o.currentAttributes.forEach((a,c)=>{r[c]=a})),Tf(s,this,o,n,r)}):this._pending.push(()=>this.insert(t,n,r))}insertEmbed(t,n,r){const i=this.doc;i!==null?Xe(i,s=>{const o=gc(s,this,t,!r);Tf(s,this,o,n,r||{})}):this._pending.push(()=>this.insertEmbed(t,n,r||{}))}delete(t,n){if(n===0)return;const r=this.doc;r!==null?Xe(r,i=>{_y(i,gc(i,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,r){if(n===0)return;const i=this.doc;i!==null?Xe(i,s=>{const o=gc(s,this,t,!1);o.right!==null&&gy(s,this,o,n,r)}):this._pending.push(()=>this.format(t,n,r))}removeAttribute(t){this.doc!==null?Xe(this.doc,n=>{pc(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?Xe(this.doc,r=>{kf(r,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return Sf(this,t)}getAttributes(){return uy(this)}_write(t){t.writeTypeRef(KN)}}const RN=e=>new Dn;class xf{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Dt()}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===xr||n.constructor===rr)&&n._start!==null)t=n._start;else for(;t!==null;)if(t.right!==null){t=t.right;break}else t.parent===this._root?t=null:t=t.parent._item;while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class rr extends at{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new rr}clone(){const t=new rr;return t.insert(0,this.toArray().map(n=>n instanceof at?n.clone():n)),t}get length(){return this.doc??Dt(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new xf(this,t)}querySelector(t){t=t.toUpperCase();const r=new xf(this,i=>i.nodeName&&i.nodeName.toUpperCase()===t).next();return r.done?null:r.value}querySelectorAll(t){return t=t.toUpperCase(),Vr(new xf(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){hc(this,t,new NN(this,n,t))}toString(){return sy(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},r){const i=t.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),po(this,s=>{i.insertBefore(s.toDOM(t,n,r),null)}),i}insert(t,n){this.doc!==null?Xe(this.doc,r=>{cy(r,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)Xe(this.doc,r=>{const i=t&&t instanceof at?t._item:t;dc(r,this,i,n)});else{const r=this._prelimContent,i=t===null?0:r.findIndex(s=>s===t)+1;if(i===0&&t!==null)throw Jr("Reference item not found");r.splice(i,0,...n)}}delete(t,n=1){this.doc!==null?Xe(this.doc,r=>{ly(r,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return iy(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return oy(this,t)}slice(t=0,n=this.length){return ry(this,t,n)}forEach(t){po(this,t)}_write(t){t.writeTypeRef(JN)}}const IN=e=>new rr;class xr extends rr{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new xr(this.nodeName)}clone(){const t=new xr(this.nodeName),n=this.getAttributes();return dO(n,(r,i)=>{typeof r=="string"&&t.setAttribute(i,r)}),t.insert(0,this.toArray().map(r=>r instanceof at?r.clone():r)),t}toString(){const t=this.getAttributes(),n=[],r=[];for(const a in t)r.push(a);r.sort();const i=r.length;for(let a=0;a0?" "+n.join(" "):"";return`<${s}${o}>${super.toString()}`}removeAttribute(t){this.doc!==null?Xe(this.doc,n=>{pc(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?Xe(this.doc,r=>{kf(r,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return Sf(this,t)}hasAttribute(t){return fy(this,t)}getAttributes(t){return t?bN(this,t):uy(this)}toDOM(t=document,n={},r){const i=t.createElement(this.nodeName),s=this.getAttributes();for(const o in s){const a=s[o];typeof a=="string"&&i.setAttribute(o,a)}return po(this,o=>{i.appendChild(o.toDOM(t,n,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(t){t.writeTypeRef(qN),t.writeKey(this.nodeName)}}const ON=e=>new xr(e.readKey());class NN extends uc{constructor(t,n,r){super(t,r),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class us extends nr{constructor(t){super(),this.hookName=t}_copy(){return new us(this.hookName)}clone(){const t=new us(this.hookName);return this.forEach((n,r)=>{t.set(r,n)}),t}toDOM(t=document,n={},r){const i=n[this.hookName];let s;return i!==void 0?s=i.createDom(this):s=document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(s,this),s}_write(t){t.writeTypeRef(XN),t.writeKey(this.hookName)}}const CN=e=>new us(e.readKey());class Si extends Dn{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Si}clone(){const t=new Si;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,r){const i=t.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(t=>{const n=[];for(const i in t.attributes){const s=[];for(const o in t.attributes[i])s.push({key:o,value:t.attributes[i][o]});s.sort((o,a)=>o.keyi.nodeName=0;i--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(ZN)}}const LN=e=>new Si;class Rf{constructor(t,n){this.id=t,this.length=n}get deleted(){throw Yn()}mergeWith(t){return!1}write(t,n,r){throw Yn()}integrate(t,n){throw Yn()}}const MN=0;class ln extends Rf{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),K0(t.doc.store,this)}write(t,n){t.writeInfo(MN),t.writeLen(this.length-n)}getMissing(t,n){return null}}class mo{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new mo(this.content)}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const UN=e=>new mo(e.readBuf());class go{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new go(this.len)}splice(t){const n=new go(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){sc(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const PN=e=>new go(e.readLen()),by=(e,t)=>new Tr({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class yo{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new yo(by(this.doc.guid,this.opts))}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const DN=e=>new yo(by(e.readString(),e.readAny()));class Ai{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Ai(this.embed)}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const BN=e=>new Ai(e.readJSON());class vt{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new vt(this.key,this.value)}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){const r=n.parent;r._searchMarker=null,r._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const FN=e=>new vt(e.readKey(),e.readJSON());class yc{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new yc(this.arr)}splice(t){const n=new yc(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const r=this.arr.length;t.writeLen(r-n);for(let i=n;i{const t=e.readLen(),n=[];for(let r=0;r{const t=e.readLen(),n=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const WN=e=>new ir(e.readString()),GN=[vN,kN,RN,ON,IN,CN,LN],HN=0,VN=1,KN=2,qN=3,JN=4,XN=5,ZN=6;class Rr{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Rr(this.type._copy())}splice(t){throw Yn()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(t.beforeState.get(r.id.client)||0)&&t._mergeStructs.push(r):r.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(t,!0),r=r.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const YN=e=>new Rr(GN[e.readTypeRef()](e)),_c=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new Et(Ne(r,i+n),t,Ne(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&s.markDeleted(),t.keep&&(s.keep=!0),t.redone!==null&&(s.redone=Ne(t.redone.client,t.redone.clock+n)),t.right=s,s.right!==null&&(s.right.left=s),e._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),t.length=n,s};class Et extends Rf{constructor(t,n,r,i,s,o,a,c){super(t,c.getLength()),this.origin=r,this.left=n,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?a0:0}set marker(t){(this.info&Zu)>0!==t&&(this.info^=Zu)}get marker(){return(this.info&Zu)>0}get keep(){return(this.info&o0)>0}set keep(t){this.keep!==t&&(this.info^=o0)}get countable(){return(this.info&a0)>0}get deleted(){return(this.info&Xu)>0}set deleted(t){this.deleted!==t&&(this.info^=Xu)}markDeleted(){this.info|=Xu}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=It(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=It(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===as&&this.id.client!==this.parent.client&&this.parent.clock>=It(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=q0(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Xr(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ln||this.right&&this.right.constructor===ln)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Et&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===Et&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===as){const r=yf(n,this.parent);r.constructor===ln?this.parent=null:this.parent=r.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=q0(t,t.doc.store,Ne(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),oc(this.origin,i.origin)){if(i.id.client{r.p===t&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),sc(t.deleteSet,this.id.client,this.id.clock,this.length),Z0(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw Qn();this.content.gc(t),n?rN(t,this,new ln(this.id,this.length)):this.content=new go(this.length)}write(t,n){const r=n>0?Ne(this.id.client,this.id.clock+n-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&Qa|(r===null?0:cn)|(i===null?0:kr)|(s===null?0:ro);if(t.writeInfo(o),r!==null&&t.writeLeftID(r),i!==null&&t.writeRightID(i),r===null&&i===null){const a=this.parent;if(a._item!==void 0){const c=a._item;if(c===null){const l=nN(a);t.writeParentInfo(!0),t.writeString(l)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else a.constructor===String?(t.writeParentInfo(!0),t.writeString(a)):a.constructor===as?(t.writeParentInfo(!1),t.writeLeftID(a)):Qn();s!==null&&t.writeString(s)}this.content.write(t,n)}}const wy=(e,t)=>QN[t&Qa](e),QN=[()=>{Qn()},PN,$N,UN,WN,BN,FN,YN,zN,DN,()=>{Qn()}],eC=10;class Sn extends Rf{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){Qn()}write(t,n){t.writeInfo(eC),ve(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const vy=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Ey="__ $YJS$ __";vy[Ey]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438"),vy[Ey]=!0;let If,Of,tC=e=>e();function nC(e,t){if(Of)return Of(e,t);tC(e)}function xi(e,t,n){if(If)return If.apply(null,arguments);throw new Error("observable implementation not provided. Call enableReactiveBindings, enableVueBindings or enableMobxBindings.")}function rC(e){If=function(t,n,r){const i=e.createAtom(t);return n&&n(),i},Of=(t,n)=>e.reaction(t,n,{fireImmediately:!1})}const ky=new WeakSet;function iC(e){if(ky.has(e))return e;ky.add(e);let t;const n=new Map;function r(){if(!t){const f=d=>{(d.changes.added.size||d.changes.deleted.size||d.changes.keys.size||d.changes.delta.length)&&t.reportChanged()};t=xi("map",()=>{e.observe(f)},()=>{e.unobserve(f)})}t.reportObserved(e._implicitObserver)}function i(f){let d=n.get(f);if(!d){const h=p=>{d.reportChanged()};d=xi(f+"",()=>{e.observe(h)},()=>{e.unobserve(h)}),n.set(f,d)}d.reportObserved(e._implicitObserver)}const s=e.get;e.get=function(f){if(typeof f!="number")throw new Error("unexpected");return i(f),Reflect.apply(s,this,arguments)};function o(f){const d=e[f];e[f]=function(){return r(),Reflect.apply(d,this,arguments)}}function a(f){let d=e,h=Object.getOwnPropertyDescriptor(d,f);if(h||(d=Object.getPrototypeOf(d),h=Object.getOwnPropertyDescriptor(d,f)),h||(d=Object.getPrototypeOf(d),h=Object.getOwnPropertyDescriptor(d,f)),!h)throw new Error("property not found");const p=h.get;h.get=function(){return this._disableTracking||r(),Reflect.apply(p,this,arguments)},Object.defineProperty(e,f,h)}function c(f,d){let h=e,p=Object.getOwnPropertyDescriptor(h,f);if(p||(h=Object.getPrototypeOf(h),p=Object.getOwnPropertyDescriptor(h,f)),p||(h=Object.getPrototypeOf(h),p=Object.getOwnPropertyDescriptor(h,f)),!p)throw new Error("property not found");Object.defineProperty(e,d,p)}o("forEach"),o("toJSON"),o("toArray"),o("slice"),o("map"),c("length","lengthUntracked"),a("length");const l=e.push;e.push=function(f){this._disableTracking=!0;const d=l.call(this,f);return this._disableTracking=!1,d};const u=e.slice;return e.slice=function(f,d){this._disableTracking=!0;const h=u.call(this,f,d);return this._disableTracking=!1,h},e}const Sy=new WeakSet;function sC(e){if(Sy.has(e))return e;Sy.add(e);let t;function n(){if(!t){let s=Array.from(e.share.keys());const o=a=>{const c=Array.from(e.share.keys());JSON.stringify(s)!==JSON.stringify(c)&&(s=c,t.reportChanged())};t=xi("map",()=>{e.on("beforeObserverCalls",o)},()=>{e.off("beforeObserverCalls",o)})}t.reportObserved(e._implicitObserver)}const r=e.get;e.get=function(s){if(typeof s!="string")throw new Error("unexpected");const o=Reflect.apply(r,this,arguments);return bc(o),o};function i(s){const o=e[s];let a;e[s]=function(){let c,l=arguments;return n(),a&&a.removeObservers(),a=nC(()=>(c=Reflect.apply(o,e,l),c),()=>t.reportChanged()),c}}return i("toJSON"),Object.defineProperty(e,"keys",{get:()=>(n(),Object.keys(e.share))}),e}const Ay=new WeakSet;function oC(e){if(Ay.has(e))return e;Ay.add(e);let t;const n=new Map;function r(){if(!t){const a=c=>{(c.changes.added.size||c.changes.deleted.size||c.changes.keys.size||c.changes.delta.length)&&t.reportChanged()};t=xi("map",()=>{e.observe(a)},()=>{e.unobserve(a)})}t.reportObserved(e._implicitObserver)}function i(a){let c=n.get(a);if(!c){const l=u=>{u.keysChanged.has(a)&&(u.changes.added.size||u.changes.deleted.size||u.changes.keys.size||u.changes.delta.length)&&c.reportChanged()};c=xi(a,()=>{e.observe(l)},()=>{e.unobserve(l)}),n.set(a,c)}c.reportObserved(e._implicitObserver)}const s=e.get;e.get=function(a){if(typeof a!="string")throw new Error("unexpected");return i(a),Reflect.apply(s,this,arguments)};function o(a){const c=e[a];e[a]=function(){return r(),Reflect.apply(c,this,arguments)}}return o("values"),o("entries"),o("keys"),o("forEach"),o("toJSON"),e}const Ty=new WeakSet;function xy(e){if(Ty.has(e))return e;Ty.add(e);let t;const n=i=>{t.reportChanged()};t=xi("text",()=>{e.observe(n)},()=>{e.unobserve(n)});function r(i){const s=e[i];e[i]=function(){return t.reportObserved(this._implicitObserver),Reflect.apply(s,this,arguments)}}return r("toString"),r("toJSON"),e}const Ry=new WeakSet;function Iy(e){if(Ry.has(e))return e;Ry.add(e);let t;const n=s=>{(s.changes.added.size||s.changes.deleted.size||s.changes.keys.size||s.changes.delta.length)&&t.reportChanged()};t=xi("xml",()=>{e.observe(n)},()=>{e.unobserve(n)});function r(s){const o=e[s];e[s]=function(){return t.reportObserved(this._implicitObserver),Reflect.apply(o,this,arguments)}}function i(s){let o=e,a=Object.getOwnPropertyDescriptor(o,s);if(a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),!a)throw new Error("property not found");const c=a.get;a.get=function(){return t.reportObserved(this._implicitObserver),Reflect.apply(c,this,arguments)},Object.defineProperty(e,s,a)}return r("toString"),r("toDOM"),r("toArray"),r("getAttribute"),i("firstChild"),e}function bc(e){return e instanceof Si||e instanceof Dn?xy(e):e instanceof tr?iC(e):e instanceof nr?oC(e):e instanceof Tr||Object.prototype.hasOwnProperty.call(e,"autoLoad")?sC(e):e instanceof rr||e instanceof xr?Iy(e):e}function Oy(e){e.share.forEach(t=>{t.constructor!==at&&bc(t)})}function Ny(e,t){for(let r=e.length-1;r>=t;r--){let i=e[r];if(!i.deleted){var n;if(i instanceof ln)continue;(n=i.content)==null||n.getContent().forEach(s=>{s instanceof at&&bc(s)})}}}const Cy=new WeakSet;function aC(e){Cy.has(e)||(Cy.add(e),bc(e),e.store.clients.forEach(t=>{t&&Ny(t,0)}),Oy(e),e.on("beforeObserverCalls",t=>{Oy(e),t.afterState.forEach((n,r)=>{const i=t.beforeState.get(r)||0;if(i!==n){const s=t.doc.store.clients.get(r);if(!s)return;const o=Pn(s,i);Ny(s,o)}})}))}class _o{constructor(t){this.value=void 0,this.value=t}}function cC(e){return ArrayBuffer.isView(e)?new _o(e):new _o(Object.freeze(e))}function lC(e){const t=function(){var a;let c=(a=this[kn])==null?void 0:a.implicitObserver;return e._implicitObserver=c,e.slice.bind(e).apply(e,arguments).map(u=>{const f=wc(u,c);return c&&typeof f=="object"?no(f,c):f})},n=function(a){return a.map(c=>{const l=Nf(c);let u=Ri(l)||l;if(u instanceof _o&&(u=u.value),u instanceof at&&u.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return u})},r=function(){return[].findIndex.apply(t.apply(this),arguments)},i={slice:t,unshift:(...o)=>(e.unshift(n(o)),e.lengthUntracked),push:(...o)=>(e.push(n(o)),e.lengthUntracked),insert:e.insert.bind(e),toJSON:e.toJSON.bind(e),forEach:function(){return[].forEach.apply(t.apply(this),arguments)},every:function(){return[].every.apply(t.apply(this),arguments)},filter:function(){return[].filter.apply(t.apply(this),arguments)},find:function(){return[].find.apply(t.apply(this),arguments)},findIndex:r,some:function(){return[].some.apply(t.apply(this),arguments)},includes:function(){return[].includes.apply(t.apply(this),arguments)},map:function(){return[].map.apply(t.apply(this),arguments)},indexOf:function(){const o=arguments[0];return r.call(this,a=>pC(a,o))},splice:function(){let o=arguments[0]<0?e.length-Math.abs(arguments[0]):arguments[0],a=arguments[1],c=Array.from(Array.from(arguments).slice(2)),l=t.apply(this,[o,Number.isInteger(a)?o+a:void 0]);return e.doc?e.doc.transact(()=>{e.delete(o,a),e.insert(o,n(c))}):(e.delete(o,a),e.insert(o,n(c))),l}},s=[];for(let o in i)s[o]=i[o];return s}function bo(e){if(typeof e=="string"&&e.trim().length){const t=Number(e);if(Number.isInteger(t))return t}return e}function Ly(e,t=new tr){if(t[wt])throw new Error("unexpected");const n=lC(t),r=new Proxy(n,{set:(i,s,o)=>{throw typeof bo(s)!="number"?new Error:new Error("array assignment is not implemented / supported")},get:(i,s,o)=>{const a=bo(s);if(a===vc)return t;if(typeof a=="number"){let u;if(o&&o[kn]){var c;u=(c=o[kn])==null?void 0:c.implicitObserver,t._implicitObserver=u}let f=t.get(a);return f=wc(f,u),f}if(a===Symbol.toStringTag)return"Array";if(a===Symbol.iterator){const u=t.slice();return Reflect.get(u,a)}return a==="length"?t.length:Reflect.get(i,a,o)},deleteProperty:(i,s)=>{const o=bo(s);if(typeof o!="number")throw new Error;return o=0?(t.delete(o),!0):!1},has:(i,s)=>{const o=bo(s);return typeof o!="number"?Reflect.has(i,o):o=0},getOwnPropertyDescriptor(i,s){const o=bo(s);if(o==="length")return{enumerable:!1,configurable:!1,writable:!0};if(typeof o=="number"&&o>=0&&o{const s=[];for(let o=0;o{if(typeof i!="string")throw new Error;const o=Nf(s);let a=Ri(o)||o;if(a instanceof _o&&(a=a.value),a instanceof at&&a.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return t.set(i,a),!0},get:(r,i,s)=>{if(i===vc)return t;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[kn]){var a;o=(a=s[kn])==null?void 0:a.implicitObserver,t._implicitObserver=o}let c=t.get(i);return c=wc(c,o),c},deleteProperty:(r,i)=>{if(typeof i!="string")throw new Error;return t.has(i)?(t.delete(i),!0):!1},has:(r,i)=>!!(typeof i=="string"&&t.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&t.has(i))return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(t.keys())});wo.set(t,n);for(let r in e)n[r]=e[r];return n}function uC(e){return e instanceof at}const wo=new WeakMap;function wc(e,t){if(uC(e)){if(e._implicitObserver=t,e instanceof tr||e instanceof nr){if(!wo.has(e)){const n=Nf(e);wo.set(e,n)}e=wo.get(e)}else if(e instanceof xr||e instanceof rr||e instanceof Si||e instanceof us||e instanceof Dn)Vu(e),e.__v_skip=!0;else throw new Error("unknown YType");return e}else{if(e===null)return null;if(typeof e=="object")return cC(e)}return e}function Nf(e){if(e==null)return e;if(e=Ri(e)||e,e instanceof tr)return Ly([],e);if(e instanceof nr)return My({},e);if(typeof e=="string")return e;if(Array.isArray(e))return Ly(e);if(e instanceof xr||e instanceof rr||e instanceof Si||e instanceof us)return e;if(e instanceof Dn)return e;if(typeof e=="object")return e instanceof _o?e:My(e);if(typeof e=="number"||typeof e=="boolean")return e;throw new Error("invalid")}function fC(e){for(let[t,n]of Object.entries(e))if(Array.isArray(n)){if(n.length!==0)throw new Error("Root Array initializer must always be empty array")}else if(n&&typeof n=="object"){if(Object.keys(n).length!==0||Object.getPrototypeOf(n)!==Object.prototype)throw new Error("Root Object initializer must always be {}")}else if(n!=="xml"&&n!=="text")throw new Error("unknown Root initializer")}function Uy(e,t,n){let r=t[n];if(!r){n!=="__v_raw"&&n!=="__v_isRef"&&n!=="__v_isReadonly"&&console.warn("property not found on root doc",n);return}return r==="xml"?e.getXmlFragment(n):r==="text"?e.getText(n):Array.isArray(r)?e.getArray(n):e.getMap(n)}function hC(e,t){if(e[wt])throw new Error("unexpected");fC(t);const n=new Proxy({},{set:(r,i,s)=>{throw typeof i!="string"?new Error:new Error("cannot set new elements on root doc")},get:(r,i,s)=>{if(i===vc)return e;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[kn]){var a;o=(a=s[kn])==null?void 0:a.implicitObserver,e._implicitObserver=o}if(i==="toJSON"){for(let u of Object.keys(t))Uy(e,t,u);return Reflect.get(e,i)}let c=Uy(e,t,i);return c=wc(c,o),c},deleteProperty:(r,i)=>{throw new Error("deleteProperty not available for doc")},has:(r,i)=>!!(typeof i=="string"&&e.share.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&e.share.has(i)||i==="toJSON")return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(e.share.keys())});return wo.set(e,n),n}rC(NI);const vc=Symbol("INTERNAL_SYMBOL");function Py(e,t){const n=Ri(e)||e;if(!n)throw new Error("not a valid synced object");return n instanceof Tr?(n.on("update",t),()=>{n.off("update",t)}):(n.observeDeep(t),()=>{n.unobserveDeep(t)})}function dC(e){const t=Ri(e);if(!(t instanceof Tr))throw new Error("store is not a valid syncedStore that maps to a Y.Doc");return t}function Ri(e){if(typeof e!="object"||e===null)return;const t=e[vc];return t&&(Vu(t),t.__v_skip=!0),t}function pC(e,t){if(e===t)return!0;if(typeof e=="object"&&typeof t=="object"){const n=Ri(e),r=Ri(t);return!n||!r?!1:n===r}return!1}function mC(e,t=new Tr){return aC(t),hC(t,e)}var Re={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var vo=Symbol.for("react.element"),gC=Symbol.for("react.portal"),yC=Symbol.for("react.fragment"),_C=Symbol.for("react.strict_mode"),bC=Symbol.for("react.profiler"),wC=Symbol.for("react.provider"),vC=Symbol.for("react.context"),EC=Symbol.for("react.forward_ref"),kC=Symbol.for("react.suspense"),SC=Symbol.for("react.memo"),AC=Symbol.for("react.lazy"),Dy=Symbol.iterator;function TC(e){return e===null||typeof e!="object"?null:(e=Dy&&e[Dy]||e["@@iterator"],typeof e=="function"?e:null)}var By={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Fy=Object.assign,$y={};function fs(e,t,n){this.props=e,this.context=t,this.refs=$y,this.updater=n||By}fs.prototype.isReactComponent={},fs.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},fs.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function jy(){}jy.prototype=fs.prototype;function Cf(e,t,n){this.props=e,this.context=t,this.refs=$y,this.updater=n||By}var Lf=Cf.prototype=new jy;Lf.constructor=Cf,Fy(Lf,fs.prototype),Lf.isPureReactComponent=!0;var zy=Array.isArray,Wy=Object.prototype.hasOwnProperty,Mf={current:null},Gy={key:!0,ref:!0,__self:!0,__source:!0};function Hy(e,t,n){var r,i={},s=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(s=""+t.key),t)Wy.call(t,r)&&!Gy.hasOwnProperty(r)&&(i[r]=t[r]);var a=arguments.length-2;if(a===1)i.children=n;else if(1{ve(e,Df);const n=eN(t);Pt(e,n)},Xy=(e,t,n)=>{ve(e,qy),Pt(e,XO(t,n))},CC=(e,t,n)=>Xy(t,n,Ht(e)),Zy=(e,t,n)=>{try{KO(t,Ht(e),n)}catch(r){console.error("Caught error while handling a Yjs update",r)}},LC=(e,t)=>{ve(e,Jy),Pt(e,t)},MC=Zy,UC=(e,t,n,r)=>{const i=Ee(e);switch(i){case Df:CC(e,t,n);break;case qy:Zy(e,n,r);break;case Jy:MC(e,n,r);break;default:throw new Error("Unknown message type")}return i},Ir=mC({shared:[]});function Ac(e,t,n){return e.find(r=>r.key===t&&r.type===n)}function Yy(e,t,n){const r=Ac(Ir.shared,e,t);E(r)||Ir.shared.push({key:e,type:t,value:n})}function PC(e,t){Yy(e,0,t)}function Qy(e,t){const n=new Dn(t);Yy(e,1,n)}function DC(e,t){const n=Ac(Ir.shared,e,0);if(E(n)){n.value=t;return}Ir.shared.push({key:e,type:0,value:t})}function BC(e,t){const n=new Dn(t),r=Ac(Ir.shared,e,1);if(E(r)){r.value=n;return}Ir.shared.push({key:e,type:1,value:n})}function e_(e,t,n){let r;function i(){const o=Ac(Ir.shared,e,t);E(o)&&(s(),r=Py(o,()=>n(o.value)))}const s=Py(Ir.shared,i);return i(),()=>r==null?void 0:r()}function FC(e,t){return e_(e,0,t)}function t_(e,t){return e_(e,1,n=>t(n.toJSON()))}function Tc(e){return Un(e)}let n_=!1;const Qr=dC(Ir),Or=Po("modem",["second"],e=>{switch(e.target){case"second":!n_&&e.data%2===0&&Or.emit("modem:join");break;case"join":if(e.sender!==Or.id()){Or.reply(e,"joinack");const t=qr();NC(t,Qr),Or.reply(e,"sync",Tc(t));const n=qr();Xy(n,Qr),Or.reply(e,"sync",Tc(n))}break;case"joinack":n_=!0;break;case"sync":{if(E(e.data)&&e.sender!==Or.id()){const t=Ei(e.data),n=qr();UC(t,n,Qr,Or)===Df&&Or.emit("modem:sync",Tc(n))}break}}});function r_(e){const t=qr();LC(t,e),Or.emit("modem:sync",Tc(t))}Qr.on("update",r_),Qr.on("destroy",()=>{Qr==null||Qr.off("update",r_)});const $C=navigator.userAgent.includes("Mac")?"cmd":"ctrl",ei="$dkpurple",jC="$196",zC="$205";function un(e,t){return`$${e}${t}$blue`}function i_(e,t){return`$${e}${t}$ondkblue`}function rt(e,t){Nt(e,t)}function WC(e,t){const n=jC.repeat(t);rt(e,`${ei}${n}`)}function Bf(e,t){const n=zC.repeat(t);rt(e,`${ei}${n}`)}function Eo(e,t){rt(e,`${ei} ${" ".repeat(t.length)} `),WC(e,t.length+2),rt(e,`${ei} $white${t} `),Bf(e,t.length+2)}function Nr(e,t){rt(e,`${ei} ${" ".repeat(t.length)} `),rt(e,`${ei} $gray${t} `),Bf(e,t.length+2)}function Me(e,t,n){rt(e,`${ei} $white${t} $blue${n}`)}function Fe(e,t){rt(e,`${ei}$blue${t}`)}const GC=lr().command("send",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.ANY]);switch(n){case"helpmenu":Eo("cli","H E L P"),Me("cli","#help controls","zss controls and inputs"),rt("cli","!helpcontrols;read help controls"),rt("cli",""),Me("cli","#help text","text formatting"),rt("cli","!helptext;read help text"),rt("cli",""),Me("cli","#help developer","developer commands"),rt("cli","!helpdeveloper;read help developer"),rt("cli",""),Me("cli","#help player","player settings"),rt("cli","!helpplayer;read help player"),Nr("cli","keyboard input"),Me("cli","?","open console"),Me("cli","esc","close console"),Me("cli","tab","move console"),Me("cli","up / down arrow keys","navigate console items"),Me("cli","left / right arrow keys","change console items"),Me("cli","enter","interact with console items"),Me("cli","alt + arrow keys","skip words and console lines"),Me("cli",`${$C} + up / down arrow keys`,"input history");break;case"helpcontrols":Eo("cli","zss controls and inputs"),Nr("cli","keyboard input"),Me("cli","arrow keys","move"),Me("cli","shift + arrow keys","shoot"),Me("cli","enter","ok / accept"),Me("cli","escape","cancel / close"),Me("cli","tab","menu / action"),Nr("cli","mouse input"),Fe("cli","todo ???"),Nr("cli","controller input"),Me("cli","left stick","move"),Me("cli","right stick","aim"),Me("cli","a","ok / accept"),Me("cli","b","cancel / close"),Me("cli","y","menu / action"),Me("cli","x","shoot"),Me("cli","triggers","shoot");break;case"helptext":Eo("cli","text formatting"),Nr("cli","typography"),Fe("cli","plain text"),Fe("cli","$centering text"),Fe("cli",'"\\"@quoted strings for special chars\\""'),Fe("cli","$$0-255 for ascii chars $159$176$240"),Fe("cli",`use color names like ${un("red","$$red")} to change foreground color`),Fe("cli",`use color names like ${i_("ongreen","$$ongreen")} to change background color`),Fe("cli",`use clear ${i_("onclear","to change background to")} transparent`),Nr("cli","hyperlinks"),Fe("cli",`${un("white",'"!hotkey"')} message shortcut;${un("gray","Label")}`),Fe("cli",`${un("white",'"!range"')} flag [labelmin] [labelmax];${un("gray","Input Label")}`),Fe("cli",`${un("white",'"!select"')} flag ...list of values;${un("gray","Input Label")}`),Fe("cli",`${un("white",'"!number"')} flag [minvalue] [maxvalue];${un("gray","Input Label")}`),Fe("cli",`${un("white",'"!text"')} flag;${un("gray","Input Label")}`),Fe("cli",`${un("white",'"!copyit"')} flag;${un("gray","Input Label")}`);break;case"helpdeveloper":Eo("cli","developer commands"),Me("cli","#books","list books in memory"),Me("cli","#pages","list pages in opened book"),Me("cli","@[pagetype:]page name","create & edit a new codepage in the currently opened book"),Me("cli","#trash","list books and pages from open book you can delete"),Me("cli","#save","flush state to register");break;case"helpplayer":Eo("cli","player settings"),Fe("cli","todo");break;default:Nt("$2",`${n} ${r??""}`);break}return 0}).command("stat",(e,t)=>{let n;const[r,...i]=t.map(Ot),s=i.join(" ");switch(De(r)){case bn(fe.LOADER):n=Mi(We.CONTENT,s,Ae.LOADER);break;default:n=Mi(We.CONTENT,[r,...i].join(" "),Ae.OBJECT);break;case bn(fe.BOARD):n=Mi(We.CONTENT,s,Ae.BOARD);break;case bn(fe.OBJECT):n=Mi(We.CONTENT,s,Ae.OBJECT);break;case bn(fe.TERRAIN):n=Mi(We.CONTENT,s,Ae.TERRAIN);break;case bn(fe.CHARSET):n=Mi(We.CONTENT,s,Ae.CHARSET);break;case bn(fe.PALETTE):n=Mi(We.CONTENT,s,Ae.PALETTE);break}return E(n)&&e.command("pageopen",n.id),0}).command("text",(e,t)=>{const n=t.map(Ot).join(" ");return Nt("$2",n),0}).command("hyperlink",(e,t)=>{const[n,...r]=t,i=Ot(n),s=r.map(Ot).join(" ");return Nt("$2",`!${s};${i}`),0}).command("dev",()=>(Dr("cli"),Cb("cli",L.player),0)).command("share",()=>(Dr("cli"),Lb("cli",L.player),0)).command("bookcreate",(e,t)=>{const[n]=ne(t,0,[q.MAYBE_STRING]),r=j_(n);return E(r)&&e.command("bookopen",r.id),0}).command("bookopen",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=ni(n);return E(r)?(Fe("cli",`opened [book] ${r.name}`),Bc(We.MAIN,r.id),e.command("pages")):et("cli","bookopen",`book ${n} not found`,L.player),0}).command("booktrash",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=Kt(We.MAIN),i=ni(n);return E(i)&&(r===i&&Bc(We.MAIN,""),OM(n),Fe("cli",`trashed [book] ${i.name}`),Dr("cli"),e.command("pages")),0}).command("pageopen",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=Bn(We.MAIN);if(!E(r))return 0;const i=yi(r,n);if(E(i)){const s=Xn(i),o=Ys(i);Fe("cli",`opened [${o}] ${s}`),Qy(mh(r.id,i.id),i.code);const a=Ys(i);$b("cli",r.id,i.id,a,`${s} - ${r.name}`,L.player)}else et("cli","pageopen",`page ${n} not found`,L.player);return 0}).command("pagetrash",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=Bn(We.MAIN),i=qR(r,n);if(E(n)){const s=Xn(i),o=Ys(i);Fe("cli",`trashed [${o}] ${s}`),Dr("cli"),e.command("pages")}return 0}).command("help",(e,t)=>{const n=t.map(Ot).join(" ")||"menu";return e.command(`help${n}`),0}).command("books",()=>{Nr("cli","books");const e=Kt(We.MAIN);Me("cli","main",`${(e==null?void 0:e.name)??"empty"} $GREEN${(e==null?void 0:e.id)??""}`);const t=Kt(We.CONTENT);Me("cli","content",`${(t==null?void 0:t.name)??"empty"} ${(t==null?void 0:t.id)??""}`),Bf("cli",7);const n=Dc();return n.length?n.forEach(r=>{rt("cli",`!bookopen ${r.id};${r.name}`)}):Fe("cli","no books found"),rt("cli","!bookcreate;create a new book"),0}).command("pages",()=>{Nr("cli","pages");const e=Bn(We.MAIN);return E(e)&&(Me("cli","main",`${e.name} $GREEN${e.id}`),e.pages.length?e.pages.forEach(t=>{const n=Xn(t),r=Ys(t);rt("cli",`!pageopen ${t.id};[${r}] ${n}`)}):(rt("cli",""),Fe("cli","no pages found"),Fe("cli","use @ to create a page"),Fe("cli","@board name of board"),Fe("cli","@object name of object"),Fe("cli","@terrain name of terrain"),Fe("cli","You can omit the type and it will default to object"),Fe("cli","@object name of object"),Fe("cli","@name of object"))),0}).command("trash",()=>{Nr("cli","$REDTRASH"),Fe("cli","books");const e=Dc();e.length&&(e.forEach(n=>{rt("cli",`!booktrash ${n.id};$REDTRASH ${n.name}`)}),rt("cli",""));const t=Kt(We.MAIN);return E(t)&&(Fe("cli",`pages in open ${t.name} book`),t.pages.forEach(n=>{const r=Xn(n);rt("cli",`!pagetrash ${n.id};$REDTRASH ${r}`)}),rt("cli","")),0}).command("save",()=>(Dr("cli"),0)).command("savewith",(e,t)=>{const[n]=ne(t,0,[q.STRING]);return Dr("cli",n),0}).command("nuke",()=>(Ub("cli"),0));function HC(e){const t=Ng[e];if(E(t))return t;const n=Ug[e];if(E(n))return n;const r=Ga[e];if(E(r))return r;const i=Sh[e];if(E(i))return i}const VC=lr({get(e,t){const n=HC(t);return E(n)?[!0,n]:[!1,void 0]}}),KC=new Set(["inputmove","inputalt","inputctrl","inputshift","inputok","inputcancel","inputmenu"]),s_=new Set(["player","pushable","collision","destructible","p1","p2","p3","cycle","stepx","stepy","sender","arg"]),qC=["NORTH","SOUTH","WEST","EAST"];function JC(e){const t=ms(e);if(He(t.inputqueue)||(t.inputqueue=[],t.inputcurrent=0),ke(t.inputcurrent)&&t.inputcurrent>0)return;const[n]=t.inputqueue,[r=Ft.NONE,i=0]=n??[Ft.NONE,0];switch(t.inputmove=[],t.inputok=0,t.inputcancel=0,t.inputmenu=0,t.inputalt=i&Ab?1:0,t.inputctrl=i&Tb?1:0,t.inputshift=i&xb?1:0,r){case Ft.MOVE_UP:case Ft.MOVE_DOWN:case Ft.MOVE_LEFT:case Ft.MOVE_RIGHT:t.inputmove=[qC[r-Ft.MOVE_UP]];break;case Ft.OK_BUTTON:t.inputok=1;break;case Ft.CANCEL_BUTTON:t.inputcancel=1;break;case Ft.MENU_BUTTON:t.inputmenu=1;break}t.inputcurrent=r,t.inputqueue=t.inputqueue.filter(s=>{const[o]=s;return o!==Ft.NONE&&o!==r})}const XC=lr({get(e,t){var s;L.isplayer&&KC.has(t)&&JC(e.id());const n=(s=L.element)==null?void 0:s[t];if(E(n)||s_.has(t))return[!0,n];const i=ms(L.player)[t];return[E(i),i]},set(e,t,n){var s;const r=(s=L.element)==null?void 0:s[t];if(E(r)||s_.has(t))return E(L.element)&&(L.element[t]=n),[!0,n];const i=ms(L.player);return i[t]=n,[!0,n]},everytick(e){var t,n;E((t=L.element)==null?void 0:t.x)&&E(L.element.y)&&E(L.element.stepx)&&E(L.element.stepy)&&Hg(e,L.book,L.board,L.element,{x:L.element.x+L.element.stepx,y:L.element.y+L.element.stepy})===!1&&(L.element.stepx=0,L.element.stepy=0),(n=L.element)!=null&&n.headless&&e.command("die")}}).command("become",(e,t)=>{var i,s;const n={x:((i=L.element)==null?void 0:i.x)??0,y:((s=L.element)==null?void 0:s.y)??0},[r]=ne(t,0,[q.KIND]);return za(L.book,L.board),Qs(L.book,L.board,L.element),Mu(L.book,L.element,L.timestamp)&&Uu(L.book,L.board,r,n),e.endofprogram(),0}).command("bind",()=>0).command("char",(e,t)=>{const[n]=ne(t,0,[q.NUMBER]);return E(L.element)&&(L.element.char=n),0}).command("color",(e,t)=>{const[n]=ne(t,0,[q.COLOR]);return E(L.element)&&E(n)&&Va(L.element,n),0}).command("go",(e,t)=>{if(E(L.element)){const[n]=ne(t,0,[q.DIR]);if(Hg(e,L.book,L.board,L.element,n),e.yield(),L.element.x===n.x&&L.element.y===n.y)return 0}return 1}).command("try",(e,t)=>{const[,n]=ne(t,0,[q.DIR]);return e.command("go",...t)&&n{if(!E(L.element))return 0;const[n]=ne(t,0,[q.DIR]),r=L.element.x??0,i=L.element.y??0;return L.element.stepx=n.x-r,L.element.stepy=n.y-i,0}),ZC=lr().command("clear",(e,t)=>(t.forEach(n=>e.set(Ot(n),0)),0)).command("set",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.ANY]);return e.set(n,r),0}).command("take",(e,t)=>{const[n,r,i]=ne(t,0,[q.STRING,q.MAYBE_NUMBER]),s=e.get(n),o=r??1;if(!ke(s))return 1;const a=s-o;return a<0?(i{const[n,r,i]=ne(t,0,[q.STRING,q.MAYBE_NUMBER]),s=e.get(n),o=ke(s)?s:0,a=r??1;if(!ke(a))return 0;const c=s===void 0?1:0;return c&&i0&&b<_.lastIndexOf(" ")?c.low.call(p):p})},sentence:function(h,p,m){return h=l.lower(h).replace(a.sentence,function(b,_,w){return _+c.up.call(w)}),p&&p.forEach(function(b){h=h.replace(new RegExp("\\b"+l.lower(b)+"\\b","g"),c.cap)}),m&&m.forEach(function(b){h=h.replace(new RegExp("(\\b"+l.lower(b)+"\\. +)(\\w)"),function(_,w,v){return w+c.low.call(v)})}),h}};u.squish=u.pascal,l.default=l;for(var f in u)l.type(f,u[f]);var d=typeof d=="function"?d:function(){};d(e.exports?e.exports=l:this.Case=l)}).call(Bt)})(o_);var YC=o_.exports,QC=Pi(YC);const ti={};function xc(e){return{player:e,layers:[],panels:[],reset:!0,focus:"scroll"}}function a_(e){e.text=[],Object.values(ti[e.id]??{}).forEach(t=>t==null?void 0:t()),ti[e.id]={}}function c_(e){const t=e.panels.find(n=>n.name===e.focus);if(!t){const n={id:ht(),name:e.focus,edge:fn.RIGHT,size:20,text:[]};return e.panels.push(n),e.reset=!1,n}return t}const eL=new Set(["hk","hotkey","rn","range","sl","select","nm","number","tx","text"]),tL=new Set(["rn","range","sl","select","nm","number","tx","text"]),nL=new Set(["tx","text"]),rL={rn:1,range:1,sl:0,select:0,nm:0,number:0,tx:"",text:""},l_={};let u_=e=>{let t=l_[e];return E(t)||(l_[e]=t=xc(e)),t};function iL(e){u_=e}function Ii(e){return u_(e)}function sL(e){const t=Ii(e);t.panels=t.panels.filter(n=>n.edge!==fn.SCROLL)}function oL(e,t,n){Object.values(ti).forEach(r=>{if(r[t]!==void 0){const i=dh(e.id(),t);ke(n)&&DC(i,n),Ie(n)&&BC(i,n)}})}function aL(e){let t="";const n=Ii(e);return n.panels=n.panels.filter(r=>{if(r.edge===fn.SCROLL){const[i]=r.text;return Ie(i)&&r.text.length===1&&(t=i),r.text.length>1}return!0}),t}function Ff(e,t,n,r,i){const s=Ii(e),o=r,a=i??QC.capital(t),c=s.panels.find(l=>l.name===a);if(c)s.reset=!0,s.focus=a,ke(o)&&(c.size=o);else switch(n){case fn.START:break;case fn.LEFT:case fn.RIGHT:case fn.TOP:case fn.BOTTOM:case fn.SCROLL:{const l={id:ht(),name:a,edge:n,size:o??Sb[n],text:[]};s.panels.push(l),s.focus=a;break}}}function cL(e,t){const n=Ii(e),r=c_(n);n.reset&&(n.reset=!1,a_(r)),r.text.push(t)}function lL(e,t,n,r,i){const s=Ii(e),o=c_(s);s.reset&&(s.reset=!1,a_(o));const a=De(r),c=[t.id(),n,...eL.has(a)?[a]:["hyperlink",r],...i],l=c[2];if(tL.has(l)){const u=`${c[3]??""}`;ti[o.id]=ti[o.id]??{};const f=t.get(u)??rL[l];if(ti[o.id][u]===void 0){const d=dh(t.id(),u);ke(f)&&PC(d,f),Ie(f)&&Qy(d,f),nL.has(l)?ti[o.id][u]=t_(d,h=>{E(h)&&h!==t.get(u)&&t.set(u,h)}):ti[o.id][u]=FC(d,h=>{E(h)&&h!==t.get(u)&&t.set(u,h)})}}o.text.push(c)}const uL=lr({get(){return[!1,void 0]},set(e,t,n){return oL(e,t,n),[!1,void 0]},tick(){var t;const e=((t=L.element)==null?void 0:t.name)??"scroll";Ff(L.player,"scroll",fn.SCROLL,void 0,e)},everytick(){const e=aL(L.player);if(e&&E(L.element)){L.element.tickertext=e,L.element.tickertime=L.timestamp;const t=xg(L.book,L.element);Nt(`$${be[t.color]}$${t.char}`,e)}}}).command("send",(e,t)=>{var u,f;const[n,r]=ne(t,0,[q.STRING,q.ANY]),[i,s]=n.split(":"),o=E(s)?i:"self",a=s??i;function c(d){d.forEach(h=>{E(h.id)&&e.send(h.id,a,r)})}const l=De(o);switch(l){case"all":for(const d of Object.keys(((u=L.board)==null?void 0:u.objects)??{}))e.send(d,a,r);break;case"self":e.message({id:ht(),sender:e.id(),target:a,data:r});break;case"others":for(const d of Object.keys(((f=L.board)==null?void 0:f.objects)??{}))d!==e.id()&&e.send(d,a,r);break;default:{c(nl(L.board,[o]));const d=e.get(l);He(d)?c(nl(L.board,d)):c(nl(L.board,[d]));break}}return 0}).command("stat",(e,t)=>{const n=Dm(t.map(Ot));switch(n.type){case fe.OBJECT:E(L.element)&&(L.element.name=n.values.join(" "));break}return 0}).command("text",(e,t)=>{const n=t.map(Ot).join("");return cL(L.player,n),0}).command("hyperlink",(e,t)=>{const[n,r,...i]=t,s=Ot(n),o=Ot(r);return lL(L.player,e,s,o,i),0}).command("gadget",(e,t)=>{const[n]=ne(t,0,[q.STRING]),r=kb[De(n)];if(r===fn.SCROLL){const[i,s]=ne(t,1,[q.MAYBE_STRING,q.MAYBE_NUMBER]);Ff(L.player,n,r,s,i)}else if(E(r)){const[i,s]=ne(t,1,[q.MAYBE_NUMBER,q.MAYBE_STRING]);Ff(L.player,n,r,i,s)}return 0}),fL=lr().command("idle",e=>(e.yield(),0)).command("end",e=>(e.endofprogram(),0)).command("endwith",(e,t)=>{const[n]=ne(t,0,[q.ANY]);return e.set("arg",n),e.command("end")}).command("lock",e=>(e.lock(e.id()),0)).command("restore",(e,t)=>(e.restore(Ot(t[0])),0)).command("unlock",e=>(e.unlock(),0)).command("zap",(e,t)=>(e.zap(Ot(t[0])),0)).command("cycle",(e,t)=>{if(E(L.element)){const[n]=ne(t,0,[q.NUMBER]);L.element.cycle=si(Math.round(n),1,255)}return 0}).command("die",e=>{var t;return(t=L.element)!=null&&t.headless&&Qs(L.book,L.board,L.element),Mu(L.book,L.element,L.timestamp),e.endofprogram(),0}).command("endgame",()=>(jb("element",L.player),0)).command("run",(e,t)=>{const[n]=ne(t,0,[q.STRING]);return Fc(n),0}).command("runwith",(e,t)=>{const[n,r]=ne(t,0,[q.ANY,q.STRING]);return e.set("arg",n),Fc(r),0});function f_(e,t){if(!E(e))return;const n=De(t),r=n.endsWith("le");switch(n){case"float32":case"float32le":{const i=e.dataview.getFloat32(e.cursor,r);return e.cursor+=4,i}case"float64":case"float64le":{const i=e.dataview.getFloat64(e.cursor,r);return e.cursor+=8,i}case"int8":case"int8le":{const i=e.dataview.getInt8(e.cursor);return e.cursor+=1,i}case"int16":case"int16le":{const i=e.dataview.getInt16(e.cursor,r);return e.cursor+=2,i}case"int32":case"int32le":{const i=e.dataview.getInt32(e.cursor,r);return e.cursor+=4,i}case"int64":case"int64le":{const i=e.dataview.getBigInt64(e.cursor,r);return e.cursor+=8,i}case"uint8":case"uint8le":{const i=e.dataview.getUint8(e.cursor);return e.cursor+=1,i}case"uint16":case"uint16le":{const i=e.dataview.getUint16(e.cursor,r);return e.cursor+=2,i}case"uint32":case"uint32le":{const i=e.dataview.getUint32(e.cursor,r);return e.cursor+=4,i}case"uint64":case"uint64le":{const i=e.dataview.getBigUint64(e.cursor,r);return e.cursor+=8,i}}}const hL=(e,t)=>{const n=V_(e.id());if(!E(n))return 0;const[r]=ne(t,0,[q.STRING]),i=De(r);switch(i){case"seek":{const[s]=ne(t,1,[q.NUMBER]);n.cursor=s;break}case"float32":case"float32le":case"float64":case"float64le":case"int8":case"int8le":case"int16":case"int16le":case"int32":case"int32le":case"int64":case"int64le":case"uint8":case"uint8le":case"uint16":case"uint16le":case"uint32":case"uint32le":case"uint64":case"uint64le":{const[s]=ne(t,1,[q.STRING]);e.set(s,f_(n,i));break}case"text":{const[s,o]=ne(t,1,[q.STRING,q.STRING]),a=f_(n,s);if(ke(a)&&Ie(o)){const c=new Uint8Array(n.bytes.buffer,n.cursor,a),u=new TextDecoder("utf-8").decode(c);e.set(o,u),n.cursor+=a}break}}return 0},dL=lr({get(e,t){const n=V_(e.id());if(E(n))switch(De(t)){case"filename":return[E(n.filename),n.filename];case"cursor":return[E(n.cursor),n.cursor]}return[!1,void 0]}}).command("send",(e,t)=>{const[n,r]=ne(t,0,[q.STRING,q.ANY]);return e.message({id:ht(),sender:e.id(),target:n,data:r}),0}).command("stat",()=>0).command("text",(e,t)=>{const n=t.map(Ot).join(" ");return Nt("$2",n),0}).command("hyperlink",(e,t)=>{const[n,...r]=t,i=Ot(n),s=r.map(Ot).join(" ");return Nt("$2",`!${s};${i}`),0}).command("load",(e,t)=>{const n=t.map(Ot).join(" "),r=e.get(n)??n;return Bn(We.CONTENT,r),0}).command("reload",(e,t)=>{const n=t.map(Ot).join(" "),r=e.get(n)??n,i=Bn(We.CONTENT,r);return i.pages=[],0}).command("bin",hL);var ko=(e=>(e[e.ERROR=0]="ERROR",e[e.CLI=1]="CLI",e[e.LOADER=2]="LOADER",e[e.CODE_PAGE=3]="CODE_PAGE",e))(ko||{});const pL={audio:bI,board:vI,cli:GC,const:VC,element:XC,flags:ZC,gadget:uL,lifecycle:fL,loader:dL},$f=["const","flags","audio","board","lifecycle","element"],mL={0:[],1:["cli",...$f],2:["loader",...$f],3:["gadget",...$f]},gL={0:new Map,1:new Map,2:new Map,3:new Map};function So(e){return(mL[e]??[]).map(n=>pL[n]).filter(E)}function yL(e,t){const n=gL[e];if(!n.has(t)){let r;const i=So(e);for(let s=0;s>>=y_,i>0&&(r|=kL),n+=vL.encode(r);while(i>0);return n};var Ao={};(function(e){function t(I,T,M){if(T in I)return I[T];if(arguments.length===3)return M;throw new Error('"'+T+'" is a required argument.')}e.getArg=t;const n=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(I){const T=I.match(n);return T?{scheme:T[1],auth:T[2],host:T[3],port:T[4],path:T[5]}:null}e.urlParse=i;function s(I){let T="";return I.scheme&&(T+=I.scheme+":"),T+="//",I.auth&&(T+=I.auth+"@"),I.host&&(T+=I.host),I.port&&(T+=":"+I.port),I.path&&(T+=I.path),T}e.urlGenerate=s;const o=32;function a(I){const T=[];return function(M){for(let V=0;Vo&&T.pop(),x}}const c=a(function(T){let M=T;const x=i(T);if(x){if(!x.path)return T;M=x.path}const V=e.isAbsolute(M),oe=[];let O=0,k=0;for(;;)if(O=k,k=M.indexOf("/",O),k===-1){oe.push(M.slice(O));break}else for(oe.push(M.slice(O,k));k=0;k--){const N=oe[k];N==="."?oe.splice(k,1):N===".."?g++:g>0&&(N===""?(oe.splice(k+1,g),g=0):(oe.splice(k,2),g--))}return M=oe.join("/"),M===""&&(M=V?"/":"."),x?(x.path=M,s(x)):M});e.normalize=c;function l(I,T){I===""&&(I="."),T===""&&(T=".");const M=i(T),x=i(I);if(x&&(I=x.path||"/"),M&&!M.scheme)return x&&(M.scheme=x.scheme),s(M);if(M||T.match(r))return T;if(x&&!x.host&&!x.path)return x.host=T,s(x);const V=T.charAt(0)==="/"?T:c(I.replace(/\/+$/,"")+"/"+T);return x?(x.path=V,s(x)):V}e.join=l,e.isAbsolute=function(I){return I.charAt(0)==="/"||n.test(I)};function u(I,T){I===""&&(I="."),I=I.replace(/\/$/,"");let M=0;for(;T.indexOf(I+"/")!==0;){const x=I.lastIndexOf("/");if(x<0||(I=I.slice(0,x),I.match(/^([^\/]+:\/)?\/*$/)))return T;++M}return Array(M+1).join("../")+T.substr(I.length+1)}e.relative=u;const f=function(){return!("__proto__"in Object.create(null))}();function d(I){return I}function h(I){return m(I)?"$"+I:I}e.toSetString=f?d:h;function p(I){return m(I)?I.slice(1):I}e.fromSetString=f?d:p;function m(I){if(!I)return!1;const T=I.length;if(T<9||I.charCodeAt(T-1)!==95||I.charCodeAt(T-2)!==95||I.charCodeAt(T-3)!==111||I.charCodeAt(T-4)!==116||I.charCodeAt(T-5)!==111||I.charCodeAt(T-6)!==114||I.charCodeAt(T-7)!==112||I.charCodeAt(T-8)!==95||I.charCodeAt(T-9)!==95)return!1;for(let M=T-10;M>=0;M--)if(I.charCodeAt(M)!==36)return!1;return!0}function b(I,T,M){let x=w(I.source,T.source);return x!==0||(x=I.originalLine-T.originalLine,x!==0)||(x=I.originalColumn-T.originalColumn,x!==0||M)||(x=I.generatedColumn-T.generatedColumn,x!==0)||(x=I.generatedLine-T.generatedLine,x!==0)?x:w(I.name,T.name)}e.compareByOriginalPositions=b;function _(I,T,M){let x=I.generatedLine-T.generatedLine;return x!==0||(x=I.generatedColumn-T.generatedColumn,x!==0||M)||(x=w(I.source,T.source),x!==0)||(x=I.originalLine-T.originalLine,x!==0)||(x=I.originalColumn-T.originalColumn,x!==0)?x:w(I.name,T.name)}e.compareByGeneratedPositionsDeflated=_;function w(I,T){return I===T?0:I===null?1:T===null?-1:I>T?1:-1}function v(I,T){let M=I.generatedLine-T.generatedLine;return M!==0||(M=I.generatedColumn-T.generatedColumn,M!==0)||(M=w(I.source,T.source),M!==0)||(M=I.originalLine-T.originalLine,M!==0)||(M=I.originalColumn-T.originalColumn,M!==0)?M:w(I.name,T.name)}e.compareByGeneratedPositionsInflated=v;function S(I){return JSON.parse(I.replace(/^\)]}'[^\n]*\n/,""))}e.parseSourceMapInput=S;function C(I,T,M){if(T=T||"",I&&(I[I.length-1]!=="/"&&T[0]!=="/"&&(I+="/"),T=I+T),M){const x=i(M);if(!x)throw new Error("sourceMapURL could not be parsed");if(x.path){const V=x.path.lastIndexOf("/");V>=0&&(x.path=x.path.substring(0,V+1))}T=l(s(x),T)}return c(T)}e.computeSourceURL=C})(Ao);var jf={};let AL=class Q_{constructor(){this._array=[],this._set=new Map}static fromArray(t,n){const r=new Q_;for(let i=0,s=t.length;i=0)return n;throw new Error('"'+t+'" is not in the set.')}at(t){if(t>=0&&tn||r==n&&s>=i||w_.compareByGeneratedPositionsInflated(e,t)<=0}let xL=class{constructor(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}unsortedForEach(t,n){this._array.forEach(t,n)}add(t){TL(this._last,t)?(this._last=t,this._array.push(t)):(this._sorted=!1,this._array.push(t))}toArray(){return this._sorted||(this._array.sort(w_.compareByGeneratedPositionsInflated),this._sorted=!0),this._array}};b_.MappingList=xL;const To=p_,pt=Ao,Rc=jf.ArraySet,RL=b_.MappingList;let v_=class eb{constructor(t){t||(t={}),this._file=pt.getArg(t,"file",null),this._sourceRoot=pt.getArg(t,"sourceRoot",null),this._skipValidation=pt.getArg(t,"skipValidation",!1),this._sources=new Rc,this._names=new Rc,this._mappings=new RL,this._sourcesContents=null}static fromSourceMap(t){const n=t.sourceRoot,r=new eb({file:t.file,sourceRoot:n});return t.eachMapping(function(i){const s={generated:{line:i.generatedLine,column:i.generatedColumn}};i.source!=null&&(s.source=i.source,n!=null&&(s.source=pt.relative(n,s.source)),s.original={line:i.originalLine,column:i.originalColumn},i.name!=null&&(s.name=i.name)),r.addMapping(s)}),t.sources.forEach(function(i){let s=i;n!==null&&(s=pt.relative(n,i)),r._sources.has(s)||r._sources.add(s);const o=t.sourceContentFor(i);o!=null&&r.setSourceContent(i,o)}),r}addMapping(t){const n=pt.getArg(t,"generated"),r=pt.getArg(t,"original",null);let i=pt.getArg(t,"source",null),s=pt.getArg(t,"name",null);this._skipValidation||this._validateMapping(n,r,i,s),i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),s!=null&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:i,name:s})}setSourceContent(t,n){let r=t;this._sourceRoot!=null&&(r=pt.relative(this._sourceRoot,r)),n!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[pt.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[pt.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))}applySourceMap(t,n,r){let i=n;if(n==null){if(t.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);i=t.file}const s=this._sourceRoot;s!=null&&(i=pt.relative(s,i));const o=this._mappings.toArray().length>0?new Rc:this._sources,a=new Rc;this._mappings.unsortedForEach(function(c){if(c.source===i&&c.originalLine!=null){const f=t.originalPositionFor({line:c.originalLine,column:c.originalColumn});f.source!=null&&(c.source=f.source,r!=null&&(c.source=pt.join(r,c.source)),s!=null&&(c.source=pt.relative(s,c.source)),c.originalLine=f.line,c.originalColumn=f.column,f.name!=null&&(c.name=f.name))}const l=c.source;l!=null&&!o.has(l)&&o.add(l);const u=c.name;u!=null&&!a.has(u)&&a.add(u)},this),this._sources=o,this._names=a,t.sources.forEach(function(c){const l=t.sourceContentFor(c);l!=null&&(r!=null&&(c=pt.join(r,c)),s!=null&&(c=pt.relative(s,c)),this.setSourceContent(c,l))},this)}_validateMapping(t,n,r,i){if(n&&typeof n.line!="number"&&typeof n.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(t&&"line"in t&&"column"in t&&t.line>0&&t.column>=0&&!n&&!r&&!i)){if(!(t&&"line"in t&&"column"in t&&n&&"line"in n&&"column"in n&&t.line>0&&t.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:t,source:r,original:n,name:i}))}}_serializeMappings(){let t=0,n=1,r=0,i=0,s=0,o=0,a="",c,l,u,f;const d=this._mappings.toArray();for(let h=0,p=d.length;h0){if(!pt.compareByGeneratedPositionsInflated(l,d[h-1]))continue;c+=","}c+=To.encode(l.generatedColumn-t),t=l.generatedColumn,l.source!=null&&(f=this._sources.indexOf(l.source),c+=To.encode(f-o),o=f,c+=To.encode(l.originalLine-1-i),i=l.originalLine-1,c+=To.encode(l.originalColumn-r),r=l.originalColumn,l.name!=null&&(u=this._names.indexOf(l.name),c+=To.encode(u-s),s=u)),a+=c}return a}_generateSourcesContent(t,n){return t.map(function(r){if(!this._sourcesContents)return null;n!=null&&(r=pt.relative(n,r));const i=pt.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null},this)}toJSON(){const t={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(t.file=this._file),this._sourceRoot!=null&&(t.sourceRoot=this._sourceRoot),this._sourcesContents&&(t.sourcesContent=this._generateSourcesContent(t.sources,t.sourceRoot)),t}toString(){return JSON.stringify(this.toJSON())}};v_.prototype._version=3,d_.SourceMapGenerator=v_;var E_={};(function(e){e.GREATEST_LOWER_BOUND=1,e.LEAST_UPPER_BOUND=2;function t(n,r,i,s,o,a){const c=Math.floor((r-n)/2)+n,l=o(i,s[c],!0);return l===0?c:l>0?r-c>1?t(c,r,i,s,o,a):a==e.LEAST_UPPER_BOUND?r1?t(n,c,i,s,o,a):a==e.LEAST_UPPER_BOUND?c:n<0?-1:n}e.search=function(r,i,s,o){if(i.length===0)return-1;let a=t(-1,i.length,r,i,s,o||e.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&s(i[a],i[a-1],!0)===0;)--a;return a}})(E_);var xo={exports:{}},IL={},OL=Object.freeze({__proto__:null,default:IL}),k_=tb(OL);if((function(){return typeof window<"u"&&this===window}).call()){let e=null;xo.exports=function(){if(typeof e=="string")return fetch(e).then(n=>n.arrayBuffer());if(e instanceof ArrayBuffer)return Promise.resolve(e);throw new Error("You must provide the string URL or ArrayBuffer contents of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer")},xo.exports.initialize=t=>e=t}else{const e=k_,t=k_;xo.exports=function(){return new Promise((r,i)=>{const s=t.join(__dirname,"mappings.wasm");e.readFile(s,null,(o,a)=>{if(o){i(o);return}r(a.buffer)})})},xo.exports.initialize=n=>{console.debug("SourceMapConsumer.initialize is a no-op when running in node.js")}}var S_=xo.exports;const NL=S_;function CL(){this.generatedLine=0,this.generatedColumn=0,this.lastGeneratedColumn=null,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}let Ro=null;var LL=function(){if(Ro)return Ro;const t=[];return Ro=NL().then(n=>WebAssembly.instantiate(n,{env:{mapping_callback(r,i,s,o,a,c,l,u,f,d){const h=new CL;h.generatedLine=r+1,h.generatedColumn=i,s&&(h.lastGeneratedColumn=o-1),a&&(h.source=c,h.originalLine=l+1,h.originalColumn=u,f&&(h.name=d)),t[t.length-1](h)},start_all_generated_locations_for(){console.time("all_generated_locations_for")},end_all_generated_locations_for(){console.timeEnd("all_generated_locations_for")},start_compute_column_spans(){console.time("compute_column_spans")},end_compute_column_spans(){console.timeEnd("compute_column_spans")},start_generated_location_for(){console.time("generated_location_for")},end_generated_location_for(){console.timeEnd("generated_location_for")},start_original_location_for(){console.time("original_location_for")},end_original_location_for(){console.timeEnd("original_location_for")},start_parse_mappings(){console.time("parse_mappings")},end_parse_mappings(){console.timeEnd("parse_mappings")},start_sort_by_generated_location(){console.time("sort_by_generated_location")},end_sort_by_generated_location(){console.timeEnd("sort_by_generated_location")},start_sort_by_original_location(){console.time("sort_by_original_location")},end_sort_by_original_location(){console.timeEnd("sort_by_original_location")}}})).then(n=>({exports:n.instance.exports,withMappingCallback:(r,i)=>{t.push(r);try{i()}finally{t.pop()}}})).then(null,n=>{throw Ro=null,n}),Ro};const he=Ao,zf=E_,Ic=jf.ArraySet,ML=S_,UL=LL,Wf=Symbol("smcInternal");class ut{constructor(t,n){return t==Wf?Promise.resolve(this):DL(t,n)}static initialize(t){ML.initialize(t["lib/mappings.wasm"])}static fromSourceMap(t,n){return BL(t,n)}static async with(t,n,r){const i=await new ut(t,n);try{return await r(i)}finally{i.destroy()}}_parseMappings(t,n){throw new Error("Subclasses must implement _parseMappings")}eachMapping(t,n,r){throw new Error("Subclasses must implement eachMapping")}allGeneratedPositionsFor(t){throw new Error("Subclasses must implement allGeneratedPositionsFor")}destroy(){throw new Error("Subclasses must implement destroy")}}ut.prototype._version=3,ut.GENERATED_ORDER=1,ut.ORIGINAL_ORDER=2,ut.GREATEST_LOWER_BOUND=1,ut.LEAST_UPPER_BOUND=2;class Io extends ut{constructor(t,n){return super(Wf).then(r=>{let i=t;typeof t=="string"&&(i=he.parseSourceMapInput(t));const s=he.getArg(i,"version");let o=he.getArg(i,"sources");const a=he.getArg(i,"names",[]);let c=he.getArg(i,"sourceRoot",null);const l=he.getArg(i,"sourcesContent",null),u=he.getArg(i,"mappings"),f=he.getArg(i,"file",null);if(s!=r._version)throw new Error("Unsupported version: "+s);return c&&(c=he.normalize(c)),o=o.map(String).map(he.normalize).map(function(d){return c&&he.isAbsolute(c)&&he.isAbsolute(d)?he.relative(c,d):d}),r._names=Ic.fromArray(a.map(String),!0),r._sources=Ic.fromArray(o,!0),r._absoluteSources=r._sources.toArray().map(function(d){return he.computeSourceURL(c,d,n)}),r.sourceRoot=c,r.sourcesContent=l,r._mappings=u,r._sourceMapURL=n,r.file=f,r._computedColumnSpans=!1,r._mappingsPtr=0,r._wasm=null,UL().then(d=>(r._wasm=d,r))})}_findSourceIndex(t){let n=t;if(this.sourceRoot!=null&&(n=he.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);for(let r=0;r{a.source!==null&&(a.source=this._sources.at(a.source),a.source=he.computeSourceURL(o,a.source,this._sourceMapURL),a.name!==null&&(a.name=this._names.at(a.name))),t.call(i,a)},()=>{switch(s){case ut.GENERATED_ORDER:this._wasm.exports.by_generated_location(this._getMappingsPtr());break;case ut.ORIGINAL_ORDER:this._wasm.exports.by_original_location(this._getMappingsPtr());break;default:throw new Error("Unknown order of iteration.")}})}allGeneratedPositionsFor(t){let n=he.getArg(t,"source");const r=he.getArg(t,"line"),i=t.column||0;if(n=this._findSourceIndex(n),n<0)return[];if(r<1)throw new Error("Line numbers must be >= 1");if(i<0)throw new Error("Column numbers must be >= 0");const s=[];return this._wasm.withMappingCallback(o=>{let a=o.lastGeneratedColumn;this._computedColumnSpans&&a===null&&(a=1/0),s.push({line:o.generatedLine,column:o.generatedColumn,lastColumn:a})},()=>{this._wasm.exports.all_generated_locations_for(this._getMappingsPtr(),n,r-1,"column"in t,i)}),s}destroy(){this._mappingsPtr!==0&&(this._wasm.exports.free_mappings(this._mappingsPtr),this._mappingsPtr=0)}computeColumnSpans(){this._computedColumnSpans||(this._wasm.exports.compute_column_spans(this._getMappingsPtr()),this._computedColumnSpans=!0)}originalPositionFor(t){const n={generatedLine:he.getArg(t,"line"),generatedColumn:he.getArg(t,"column")};if(n.generatedLine<1)throw new Error("Line numbers must be >= 1");if(n.generatedColumn<0)throw new Error("Column numbers must be >= 0");let r=he.getArg(t,"bias",ut.GREATEST_LOWER_BOUND);r==null&&(r=ut.GREATEST_LOWER_BOUND);let i;if(this._wasm.withMappingCallback(s=>i=s,()=>{this._wasm.exports.original_location_for(this._getMappingsPtr(),n.generatedLine-1,n.generatedColumn,r)}),i&&i.generatedLine===n.generatedLine){let s=he.getArg(i,"source",null);s!==null&&(s=this._sources.at(s),s=he.computeSourceURL(this.sourceRoot,s,this._sourceMapURL));let o=he.getArg(i,"name",null);return o!==null&&(o=this._names.at(o)),{source:s,line:he.getArg(i,"originalLine",null),column:he.getArg(i,"originalColumn",null),name:o}}return{source:null,line:null,column:null,name:null}}hasContentsOfAllSources(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(t){return t==null}):!1}sourceContentFor(t,n){if(!this.sourcesContent)return null;const r=this._findSourceIndex(t);if(r>=0)return this.sourcesContent[r];let i=t;this.sourceRoot!=null&&(i=he.relative(this.sourceRoot,i));let s;if(this.sourceRoot!=null&&(s=he.urlParse(this.sourceRoot))){const o=i.replace(/^file:\/\//,"");if(s.scheme=="file"&&this._sources.has(o))return this.sourcesContent[this._sources.indexOf(o)];if((!s.path||s.path=="/")&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(n)return null;throw new Error('"'+i+'" is not in the SourceMap.')}generatedPositionFor(t){let n=he.getArg(t,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};const r={source:n,originalLine:he.getArg(t,"line"),originalColumn:he.getArg(t,"column")};if(r.originalLine<1)throw new Error("Line numbers must be >= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");let i=he.getArg(t,"bias",ut.GREATEST_LOWER_BOUND);i==null&&(i=ut.GREATEST_LOWER_BOUND);let s;if(this._wasm.withMappingCallback(o=>s=o,()=>{this._wasm.exports.generated_location_for(this._getMappingsPtr(),r.source,r.originalLine-1,r.originalColumn,i)}),s&&s.source===r.source){let o=s.lastGeneratedColumn;return this._computedColumnSpans&&o===null&&(o=1/0),{line:he.getArg(s,"generatedLine",null),column:he.getArg(s,"generatedColumn",null),lastColumn:o}}return{line:null,column:null,lastColumn:null}}}Io.prototype.consumer=ut;class PL extends ut{constructor(t,n){return super(Wf).then(r=>{let i=t;typeof t=="string"&&(i=he.parseSourceMapInput(t));const s=he.getArg(i,"version"),o=he.getArg(i,"sections");if(s!=r._version)throw new Error("Unsupported version: "+s);r._sources=new Ic,r._names=new Ic,r.__generatedMappings=null,r.__originalMappings=null,r.__generatedMappingsUnsorted=null,r.__originalMappingsUnsorted=null;let a={line:-1,column:0};return Promise.all(o.map(c=>{if(c.url)throw new Error("Support for url field in sections not implemented.");const l=he.getArg(c,"offset"),u=he.getArg(l,"line"),f=he.getArg(l,"column");if(u({generatedOffset:{generatedLine:u+1,generatedColumn:f+1},consumer:h}))})).then(c=>(r._sections=c,r))})}get _generatedMappings(){return this.__generatedMappings||this._sortGeneratedMappings(),this.__generatedMappings}get _originalMappings(){return this.__originalMappings||this._sortOriginalMappings(),this.__originalMappings}get _generatedMappingsUnsorted(){return this.__generatedMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappingsUnsorted}get _originalMappingsUnsorted(){return this.__originalMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappingsUnsorted}_sortGeneratedMappings(){const t=this._generatedMappingsUnsorted;t.sort(he.compareByGeneratedPositionsDeflated),this.__generatedMappings=t}_sortOriginalMappings(){const t=this._originalMappingsUnsorted;t.sort(he.compareByOriginalPositions),this.__originalMappings=t}get sources(){const t=[];for(let n=0;na.push(c));for(let c=0;c= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");const i=[];let s=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",he.compareByOriginalPositions,zf.LEAST_UPPER_BOUND);if(s>=0){let o=this._originalMappings[s];if(t.column===void 0){const a=o.originalLine;for(;o&&o.originalLine===a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:he.getArg(o,"generatedLine",null),column:he.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}else{const a=o.originalColumn;for(;o&&o.originalLine===n&&o.originalColumn==a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:he.getArg(o,"generatedLine",null),column:he.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}}return i}destroy(){for(let t=0;t=0;n--)this.prepend(t[n]);else if(t[hs]||typeof t=="string")this.children.unshift(t);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+t);return this}walk(t){let n;for(let r=0,i=this.children.length;r0){for(n=[],r=0;rString.fromCharCode(e)),HL=on({name:"Whitespace",pattern:/ +/}),VL=on({name:"WhitespaceSkipped",pattern:/ +/,group:bt.SKIPPED}),Gf=on({name:"Newline",line_breaks:!0,start_chars_hint:[` -`,"\r"],pattern:/\n|\r\n?/}),T_=on({name:"StringLiteral",pattern:/[^ $;\r\n]+/,start_chars_hint:GL}),Hf=on({name:"StringLiteralDouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),Vf=on({name:"EscapedDollar",pattern:"$$"}),Kf=on({name:"MaybeFlag",pattern:/\$[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/}),qf=on({name:"NumberLiteral",pattern:/\$-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?\+?/}),x_=on({name:"HyperLinkText",pattern:/;[^;\r\n]*/,start_chars_hint:[";"]});function KL(e,t=""){return on({name:t||e,pattern:new RegExp(e.toLowerCase(),"i")})}const R_=Object.keys(Ga).map(e=>KL(`\\$(${e})`,e)),qL=[HL,Gf,...R_,Hf,T_,qf,Vf,x_,Kf],JL=new bt(qL,{skipValidations:!qn,ensureOptimizations:qn}),XL=new bt([VL,Gf,...R_,Hf,T_,qf,Vf,x_,Kf],{skipValidations:!qn,ensureOptimizations:qn});function Jf(e,t=!1){return t?XL.tokenize(e):JL.tokenize(e)}function I_(e,t,n,r,i,s,o,a){return{disablewrap:!1,measureonly:!1,measuredwidth:0,writefullwidth:void 0,x:0,y:0,iseven:!0,active:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},reset:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},width:e,height:t,char:[],color:[],bg:[],changed(){}}}function O_(e){e.active={...e.reset}}function N_(e,t){const n=t.y;function r(){++t.x;const a=t.active.rightedge??t.width-1;!t.disablewrap&&t.x>a&&(t.x=t.active.leftedge??0,++t.y),t.x>t.measuredwidth&&(t.measuredwidth=t.x)}function i(){return t.x>=(t.active.leftedge??0)&&t.x<=(t.active.rightedge??t.width-1)&&t.y>=(t.active.topedge??0)&&t.y<=(t.active.bottomedge??t.height-1)}function s(a){for(let c=0;ct.measuredwidth&&(t.measuredwidth=t.x+1);const o=t.active.leftedge??0;if(E(t.writefullwidth)&&(t.x>o||t.y===n)){const c=(t.active.rightedge??t.width-1)-t.x;if(c>0){O_(t);const l=String.fromCharCode(t.writefullwidth).repeat(c),u=t.x+t.y*t.width;eM(u,u+l.length,t.active.color,t.active.bg,t),QL(u,l,t)}}}function ZL(e,t,n){const r=Jf(e);r.tokens&&(N_(r.tokens,t),O_(t))}function YL(e,t,n){const r=Jf(e);if(!r.tokens)return;const i=I_(t,n,be.WHITE,be.BLACK);return i.measureonly=!0,N_(r.tokens,i),i.x>0&&++i.y,i}function QL(e,t,n){let r=0;const i=e+t.length;for(let s=e;s{this.MANY(()=>this.SUBRULE(this.line))}));ye(this,"line",this.RULED("line",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt)},{ALT:()=>this.CONSUME(js)}])}));ye(this,"stmt",this.RULED("stmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.short_commands)),this.MANY(()=>this.SUBRULE(this.commands))}}])}));ye(this,"inline",this.RULED("inline",()=>{this.SUBRULE(this.instmt)}));ye(this,"instmt",this.RULED("instmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}])}));ye(this,"stmt_label",this.RULED("stmt_label",()=>{this.CONSUME(cm)}));ye(this,"stmt_stat",this.RULED("stmt_stat",()=>{this.CONSUME(Yl)}));ye(this,"stmt_text",this.RULED("stmt_text",()=>{this.OR([{ALT:()=>this.CONSUME(om)}])}));ye(this,"stmt_comment",this.RULED("stmt_comment",()=>{this.CONSUME(am)}));ye(this,"stmt_hyperlink",this.RULED("stmt_hyperlink",()=>{this.CONSUME(lm),this.SUBRULE(this.words),this.CONSUME(um)}));ye(this,"stmt_command",this.RULED("stmt_command",()=>{this.CONSUME(Ki),this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}));ye(this,"short_commands",this.RULED("short_commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)}])}));ye(this,"commands",this.RULED("commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.words)},{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)},{ALT:()=>this.SUBRULE(this.command_play)},{ALT:()=>this.SUBRULE(this.structured_cmd)}])}));ye(this,"structured_cmd",this.RULED("structured_cmd",()=>{this.OR([{ALT:()=>this.SUBRULE(this.command_debugger)},{ALT:()=>this.SUBRULE(this.command_if)},{ALT:()=>this.SUBRULE(this.command_while)},{ALT:()=>this.SUBRULE(this.command_repeat)},{ALT:()=>this.SUBRULE(this.command_waitfor)},{ALT:()=>this.SUBRULE(this.command_foreach)},{ALT:()=>this.SUBRULE(this.command_break)},{ALT:()=>this.SUBRULE(this.command_continue)}])}));ye(this,"short_go",this.RULED("short_go",()=>{this.CONSUME(iu),this.SUBRULE(this.words)}));ye(this,"short_try",this.RULED("short_try",()=>{this.CONSUME(km),this.SUBRULE(this.words)}));ye(this,"command_debugger",this.RULED("command_debugger",()=>{this.CONSUME(xm)}));ye(this,"command_if",this.RULED("command_if",()=>{this.CONSUME(su),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_if_block))}));ye(this,"command_if_block",this.RULED("command_if_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(Oa),this.MANY(()=>this.SUBRULE(this.line)),this.MANY2({GATE:this.BACKTRACK(this.command_else_if),DEF:()=>this.SUBRULE(this.command_else_if)}),this.OPTION(()=>this.SUBRULE(this.command_else)),this.MANY3(()=>this.CONSUME3(js)),this.CONSUME4(Ki),this.CONSUME4(ou)}}])}));ye(this,"command_block",this.RULED("command_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(Oa),this.MANY(()=>this.SUBRULE(this.line)),this.CONSUME(Ki),this.CONSUME(ou)}}])}));ye(this,"command_fork",this.RULED("command_fork",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(Oa),this.MANY({GATE:this.BACKTRACK(this.line),DEF:()=>this.SUBRULE(this.line)})}}])}));ye(this,"command_else_if",this.RULED("command_else_if",()=>{this.CONSUME(Ki),this.CONSUME(au),this.CONSUME(su),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_fork))}));ye(this,"command_else",this.RULED("command_else",()=>{this.CONSUME(Ki),this.CONSUME(au),this.OPTION(()=>this.SUBRULE(this.command_fork))}));ye(this,"command_while",this.RULED("command_while",()=>{this.CONSUME(Rm),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_repeat",this.RULED("command_repeat",()=>{this.CONSUME(Im),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_waitfor",this.RULED("command_waitfor",()=>{this.CONSUME(Om),this.SUBRULE(this.words)}));ye(this,"command_foreach",this.RULED("command_foreach",()=>{this.CONSUME(Nm),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_break",this.RULED("command_break",()=>{this.CONSUME(Cm)}));ye(this,"command_continue",this.RULED("command_continue",()=>{this.CONSUME(Lm)}));ye(this,"command_play",this.RULED("command_play",()=>{this.CONSUME(Tm)}));ye(this,"expr",this.RULED("expr",()=>{this.SUBRULE1(this.and_test),this.MANY(()=>{this.CONSUME(Ql),this.SUBRULE2(this.and_test)})}));ye(this,"and_test",this.RULED("and_test",()=>{this.SUBRULE1(this.not_test),this.MANY(()=>{this.CONSUME(tu),this.SUBRULE2(this.not_test)})}));ye(this,"not_test",this.RULED("not_test",()=>{this.OR([{ALT:()=>{this.CONSUME(eu),this.SUBRULE1(this.not_test)}},{ALT:()=>this.SUBRULE2(this.comparison)}])}));ye(this,"comparison",this.RULED("comparison",()=>{this.SUBRULE1(this.arith_expr),this.MANY(()=>{this.SUBRULE(this.comp_op),this.SUBRULE2(this.arith_expr)})}));ye(this,"comp_op",this.RULED("comp_op",()=>{this.OR([{ALT:()=>this.CONSUME(dm)},{ALT:()=>this.CONSUME(pm)},{ALT:()=>this.CONSUME(mm)},{ALT:()=>this.CONSUME(gm)},{ALT:()=>this.CONSUME(ym)},{ALT:()=>this.CONSUME(_m)}])}));ye(this,"expr_value",this.RULED("expr_value",()=>{this.SUBRULE1(this.and_test_value),this.MANY(()=>{this.CONSUME(Ql),this.SUBRULE2(this.and_test_value)})}));ye(this,"and_test_value",this.RULED("and_test_value",()=>{this.SUBRULE1(this.not_test_value),this.MANY(()=>{this.CONSUME(tu),this.SUBRULE2(this.not_test_value)})}));ye(this,"not_test_value",this.RULED("not_test_value",()=>{this.OR([{ALT:()=>{this.CONSUME(eu),this.SUBRULE1(this.not_test_value)}},{ALT:()=>this.SUBRULE2(this.arith_expr)}])}));ye(this,"arith_expr",this.RULED("arith_expr",()=>{this.SUBRULE1(this.term),this.MANY(()=>this.SUBRULE2(this.arith_expr_item))}));ye(this,"arith_expr_item",this.RULED("arith_expr_item",()=>{this.OR([{ALT:()=>this.CONSUME(nu)},{ALT:()=>this.CONSUME(ru)}]),this.SUBRULE(this.term)}));ye(this,"term",this.RULED("term",()=>{this.SUBRULE1(this.factor),this.MANY(()=>this.SUBRULE2(this.term_item))}));ye(this,"term_item",this.RULED("term_item",()=>{this.OR([{ALT:()=>this.CONSUME(wm)},{ALT:()=>this.CONSUME(iu)},{ALT:()=>this.CONSUME(vm)},{ALT:()=>this.CONSUME(Em)}]),this.SUBRULE(this.factor)}));ye(this,"factor",this.RULED("factor",()=>{this.OR1([{ALT:()=>{this.OR2([{ALT:()=>this.CONSUME(nu)},{ALT:()=>this.CONSUME(ru)}]),this.SUBRULE(this.factor)}},{ALT:()=>this.SUBRULE(this.power)}])}));ye(this,"power",this.RULED("power",()=>{this.SUBRULE(this.token),this.OPTION(()=>{this.CONSUME(bm),this.SUBRULE(this.factor)})}));ye(this,"words",this.RULED("words",()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.expr))}));ye(this,"token",this.RULED("token",()=>{this.OR([{ALT:()=>this.CONSUME(fm)},{ALT:()=>this.CONSUME(zt)},{ALT:()=>this.CONSUME(hm)},{ALT:()=>{this.CONSUME(Sm),this.SUBRULE(this.expr),this.CONSUME(Am)}}])}));this.performSelfAnalysis()}PEEK(n,r,...i){console.info(n,i.map(s=>[s.image,s.tokenType]),r)}RULED(n,r,i){const s=tM.some(o=>n.includes(o));return this.RULE(n,()=>{const a=(C_++).toString().padStart(3),c=s?"font-weight: bold;":"";if(L_&&!this.RECORDING_PHASE){const l=[this.LA(1),this.LA(2),this.LA(3)].map(u=>`[${u.tokenType.name} ${u.image.replaceAll(` -`,"\\n")}]`);console.info(`${a}%c> ${n} ${l.join(" ")}`,c)}r(),L_&&!this.RECORDING_PHASE&&console.info(`${a}%c< ${n} `,c),C_--},i)}}const ds=new nM;if(Hx){const e=ds.getGAstProductions(),t=Gx(e);console.info(t)}const rM=ds.getBaseCstVisitorConstructor();var se=(e=>(e[e.PROGRAM=0]="PROGRAM",e[e.API=1]="API",e[e.LINE=2]="LINE",e[e.MARK=3]="MARK",e[e.GOTO=4]="GOTO",e[e.COUNT=5]="COUNT",e[e.TEXT=6]="TEXT",e[e.LABEL=7]="LABEL",e[e.HYPERLINK=8]="HYPERLINK",e[e.STAT=9]="STAT",e[e.MOVE=10]="MOVE",e[e.COMMAND=11]="COMMAND",e[e.LITERAL=12]="LITERAL",e[e.IF=13]="IF",e[e.IF_CHECK=14]="IF_CHECK",e[e.IF_BLOCK=15]="IF_BLOCK",e[e.ELSE_IF=16]="ELSE_IF",e[e.ELSE=17]="ELSE",e[e.WHILE=18]="WHILE",e[e.BREAK=19]="BREAK",e[e.CONTINUE=20]="CONTINUE",e[e.REPEAT=21]="REPEAT",e[e.WAITFOR=22]="WAITFOR",e[e.FOREACH=23]="FOREACH",e[e.OR=24]="OR",e[e.AND=25]="AND",e[e.NOT=26]="NOT",e[e.COMPARE=27]="COMPARE",e[e.COMPARE_ITEM=28]="COMPARE_ITEM",e[e.OPERATOR=29]="OPERATOR",e[e.OPERATOR_ITEM=30]="OPERATOR_ITEM",e[e.EXPR=31]="EXPR",e))(se||{}),Oi=(e=>(e[e.IS_EQ=0]="IS_EQ",e[e.IS_NOT_EQ=1]="IS_NOT_EQ",e[e.IS_LESS_THAN=2]="IS_LESS_THAN",e[e.IS_GREATER_THAN=3]="IS_GREATER_THAN",e[e.IS_LESS_THAN_OR_EQ=4]="IS_LESS_THAN_OR_EQ",e[e.IS_GREATER_THAN_OR_EQ=5]="IS_GREATER_THAN_OR_EQ",e))(Oi||{}),sr=(e=>(e[e.EMPTY=0]="EMPTY",e[e.PLUS=1]="PLUS",e[e.MINUS=2]="MINUS",e[e.POWER=3]="POWER",e[e.MULTIPLY=4]="MULTIPLY",e[e.DIVIDE=5]="DIVIDE",e[e.MOD_DIVIDE=6]="MOD_DIVIDE",e[e.FLOOR_DIVIDE=7]="FLOOR_DIVIDE",e[e.UNI_PLUS=8]="UNI_PLUS",e[e.UNI_MINUS=9]="UNI_MINUS",e))(sr||{}),Nc=(e=>(e[e.NUMBER=0]="NUMBER",e[e.STRING=1]="STRING",e[e.TEMPLATE=2]="TEMPLATE",e))(Nc||{});function iM(e){return!!(e!=null&&e.tokenType)}function Cr(e,t){const[n]=e??[];return((n==null?void 0:n.image)??t).trimStart().replaceAll(/^"|"$/g,"")}class sM extends rM{constructor(){super();ye(this,"unique",0);qn&&this.validateVisitor()}getnodelocation(n){const r=Object.values(n).flat().filter(i=>!!i).map(i=>i&&iM(i)?{startLine:i.startLine,startColumn:i.startColumn,startOffset:i.startOffset,endLine:i.endLine,endColumn:i.endColumn,endOffset:i.endOffset}:i!=null&&i.location?{...i.location}:{startLine:0,startColumn:0,startOffset:0,endLine:0,endColumn:0,endOffset:0}).filter(i=>i.startLine!==0&&i.endLine!==0);return{startLine:Math.min(...r.map(i=>i.startLine??1)),startColumn:Math.min(...r.map(i=>i.startColumn??1)),startOffset:Math.min(...r.map(i=>i.startOffset??1)),endLine:Math.max(...r.map(i=>i.endLine??1)),endColumn:Math.max(...r.map(i=>i.endColumn??1)),endOffset:Math.max(...r.map(i=>i.endOffset??1))}}createcodenode(n,r){return[{...r,...this.getnodelocation(n),lineindex:0}]}createstringnode(n,r){return this.createcodenode(n,{type:12,literal:1,value:r})}createmarknode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:3,id:r,comment:i}))}creategotonode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:4,id:r,comment:i}))}createlinenode(n,r){return this.createcodenode(n,{type:2,stmts:r})}createapinode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:1,words:i,method:r}))}createlogicnode(n,r,i,s){return this.createlinenode(n,this.createcodenode(n,{type:14,skip:i,words:s,method:r}))}createcountnode(n){return this.createcodenode(n,{type:5,index:this.unique++})}go(n){return Array.isArray(n)?n.map(r=>this.visit(r)).flat():E(n)?[this.visit(n)].flat():[]}program(n){return this.unique=0,this.createcodenode(n,{type:0,lines:[this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:"restart"})),this.go(n.line)].flat()})}line(n){return n.stmt?this.go(n.stmt):[]}stmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.short_commands?[this.go(n.short_commands),this.go(n.commands)].flat():[]}inline(n){return this.go(n.instmt)}instmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.commands?this.go(n.commands):[]}stmt_label(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:Cr(n.token_label,":").slice(1).trim()}))}stmt_stat(n){return this.createlinenode(n,this.createcodenode(n,{type:9,value:Cr(n.token_stat,"@").slice(1)}))}stmt_text(n){return this.createlinenode(n,this.createcodenode(n,{type:6,value:Cr(n.token_text,"")}))}stmt_comment(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!1,name:Cr(n.token_comment,"'").slice(1).trim()}))}stmt_hyperlink(n){return this.createlinenode(n,this.createcodenode(n,{type:8,link:this.go(n.words),text:Cr(n.token_hyperlinktext,";").slice(1)}))}stmt_command(n){return n.commands?this.go(n.commands):[]}short_commands(n){return n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):[]}commands(n){return n.words?this.createlinenode(n,this.createcodenode(n,{type:11,words:this.go(n.words)})):n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):n.command_play?this.go(n.command_play):n.structured_cmd?this.go(n.structured_cmd):[]}structured_cmd(n){return n.command_if?this.go(n.command_if):n.command_while?this.go(n.command_while):n.command_repeat?this.go(n.command_repeat):n.command_waitfor?this.go(n.command_waitfor):n.command_foreach?this.go(n.command_foreach):n.command_break?this.go(n.command_break):n.command_continue?this.go(n.command_continue):[]}short_go(n){return n.token_divide?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!0,words:this.go(n.words)})):[]}short_try(n){return n.token_query?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!1,words:this.go(n.words)})):[]}command_if(n){const[r]=this.createlogicnode(n,"if","",this.go(n.words)),[i]=this.go(n.command_if_block)??[];return this.createcodenode(n,{type:13,check:r,block:i})}command_if_block(n){const r=ht(),i=ht();return this.createcodenode(n,{type:15,skip:r,done:i,lines:[this.go(n.inline),this.go(n.line),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"alt logic")].flat(),altlines:[this.go(n.command_else_if),this.go(n.command_else),this.createmarknode(n,i,"end of if")].flat()})}command_block(n){return[this.go(n.inline),this.go(n.line)].flat()}command_fork(n){return[this.go(n.inline),this.go(n.line)].flat()}command_else_if(n){const r=ht(),i=ht();return this.createcodenode(n,{type:16,done:i,lines:[this.createlogicnode(n,"if",r,this.go(n.words)),this.go(n.command_fork),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"skip")].flat()})}command_else(n){return this.createcodenode(n,{type:17,lines:this.go(n.command_fork)})}command_while(n){const r=ht(),i=ht();return this.createcodenode(n,{type:18,loop:r,done:i,lines:[this.createmarknode(n,r,"start of while"),this.createlogicnode(n,"if",i,this.go(n.words)),this.go(n.command_block),this.creategotonode(n,r,"loop of while"),this.createmarknode(n,i,"end of while")].flat()})}command_repeat(n){const r=ht(),i=ht(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:21,loop:r,done:i,lines:[this.createapinode(n,"repeatstart",o),this.createmarknode(n,r,"start of repeat"),this.createlogicnode(n,"repeat",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of repeat"),this.createmarknode(n,i,"end of repeat")].flat()})}command_foreach(n){const r=ht(),i=ht(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:23,loop:r,done:i,lines:[this.createapinode(n,"foreachstart",o),this.createmarknode(n,r,"start of foreach"),this.createlogicnode(n,"foreach",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of foreach"),this.createmarknode(n,i,"end of foreach")].flat()})}command_waitfor(n){return this.createcodenode(n,{type:22,words:this.go(n.words)})}command_break(n){return this.createcodenode(n,{type:19,goto:0})}command_continue(n){return this.createcodenode(n,{type:20,goto:0})}command_play(n){const r=Cr(n.token_command_play,""),i=r.replace("bgplay","").replace("play","").trim(),s=r.includes("bgplay");return this.createlinenode(n,this.createcodenode(n,{type:11,words:[this.createstringnode(n,s?"bgplay":"play"),this.createstringnode(n,i)].flat()}))}expr(n){return n.and_test.length===1?this.go(n.and_test):this.createcodenode(n,{type:24,items:this.go(n.and_test)})}and_test(n){return n.not_test.length===1?this.go(n.not_test):this.createcodenode(n,{type:25,items:this.go(n.not_test)})}not_test(n){return n.comparison?this.go(n.comparison):n.not_test?this.createcodenode(n,{type:26,items:this.go(n.not_test)}):[]}comparison(n){if(n.arith_expr.length===1)return this.go(n.arith_expr);const[r,i]=this.go(n.arith_expr),[s]=this.go(n.comp_op);return this.createcodenode(n,{type:27,lhs:r,compare:s,rhs:i})}comp_op(n){return n.token_iseq?this.createcodenode(n,{type:28,method:0}):n.token_isnoteq?this.createcodenode(n,{type:28,method:1}):n.token_islessthan?this.createcodenode(n,{type:28,method:2}):n.token_isgreaterthan?this.createcodenode(n,{type:28,method:3}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:4}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:5}):[]}expr_value(n){return n.and_test_value.length===1?this.go(n.and_test_value):this.createcodenode(n,{type:24,items:this.go(n.and_test_value)})}and_test_value(n){return n.not_test_value.length===1?this.go(n.not_test_value):this.createcodenode(n,{type:25,items:this.go(n.not_test_value)})}not_test_value(n){return n.arith_expr?this.go(n.arith_expr):n.not_test_value?this.createcodenode(n,{type:26,items:this.go(n.not_test_value)}):[]}arith_expr(n){const r=this.go(n.term);return n.arith_expr_item?this.createcodenode(n,{type:29,lhs:r[0],items:this.go(n.arith_expr_item)}):r}arith_expr_item(n){return this.createcodenode(n,{type:30,operator:n.token_plus?1:2,rhs:this.go(n.term)[0]})}term(n){return n.term_item?this.createcodenode(n,{type:29,lhs:this.go(n.factor)[0],items:this.go(n.term_item)}):this.go(n.factor)}term_item(n){let r=0;return n.token_multiply&&(r=4),n.token_divide&&(r=5),n.token_moddivide&&(r=6),n.token_floordivide&&(r=7),this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})}factor(n){if(n.power)return this.go(n.power);let r=0;return n.token_plus&&(r=8),n.token_minus&&(r=9),this.createcodenode(n,{type:29,lhs:void 0,items:this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})})}power(n){const r=this.go(n.token);return n.factor?this.createcodenode(n,{type:29,lhs:r[0],items:this.createcodenode(n,{type:30,operator:3,rhs:this.go(n.factor)[0]})}):r}words(n){return this.go(n.expr)}token(n){if(n.token_stringliteraldouble){const r=Cr(n.token_stringliteraldouble,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:2,value:r})}if(n.token_stringliteral){const r=Cr(n.token_stringliteral,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:1,value:r})}if(n.token_numberliteral){const r=parseFloat(Cr(n.token_numberliteral,"0"));return this.createcodenode(n,{type:12,literal:0,value:r})}return n.token_lparen?this.createcodenode(n,{type:31,words:this.go(n.expr)}):[]}}const oM=new sM,nn={labels:{},internal:0,lineindex:0,linelookup:{},isfirststat:!1},Cc="zss.js";function Ce(e,t){return new WL(e.startLine??1,e.startColumn??1,Cc,t)}function Xf(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Zf(e){return`'${Xf(e)}'`}function Lc(e){if(e.startsWith('"'))return Lc(e.replaceAll(/(^"|"$)/g,""));const t=Jf(e);return t.errors.length?e:`['${t.tokens.map(r=>r.tokenType===Kf?`', api.get('${Xf(r.image.substring(1))}'), '`:Xf(r.image)).join("")}'].join('')`}function Ni(e){return e.filter(t=>t!==void 0).map(Be)}function M_(e){return Ce(e,"")}function aM(e,t){const n=[];return e.forEach(r=>{n.push(r,t)}),n.pop(),n}function mt(e,t,n){return Ce(e,[`api.${t}(`,...aM(n,", "),")"])}function cM(e){if(e.type===se.COMPARE&&e.compare.type===se.COMPARE_ITEM)switch(e.compare.method){case Oi.IS_EQ:return mt(e,"isEq",[Be(e.lhs),Be(e.rhs)]);case Oi.IS_NOT_EQ:return mt(e,"isNotEq",[Be(e.lhs),Be(e.rhs)]);case Oi.IS_LESS_THAN:return mt(e,"isLessThan",[Be(e.lhs),Be(e.rhs)]);case Oi.IS_GREATER_THAN:return mt(e,"isGreaterThan",[Be(e.lhs),Be(e.rhs)]);case Oi.IS_LESS_THAN_OR_EQ:return mt(e,"isLessThanOrEq",[Be(e.lhs),Be(e.rhs)]);case Oi.IS_GREATER_THAN_OR_EQ:return mt(e,"isGreaterThanOrEq",[Be(e.lhs),Be(e.rhs)])}return Ce(e,"")}function Ci(e,t,n){return e.prepend(`api.${t}(`),e.add([", ",Be(n),")"])}function U_(e,t,n){return e.prepend(`api.${t}(`),e.add([Be(n),")"])}function lM(e,t){if(e.type===se.OPERATOR_ITEM)switch(e.operator){case sr.PLUS:return Ci(t,"opPlus",e.rhs);case sr.MINUS:return Ci(t,"opMinus",e.rhs);case sr.POWER:return Ci(t,"opPower",e.rhs);case sr.MULTIPLY:return Ci(t,"opMultiply",e.rhs);case sr.DIVIDE:return Ci(t,"opDivide",e.rhs);case sr.MOD_DIVIDE:return Ci(t,"opModDivide",e.rhs);case sr.FLOOR_DIVIDE:return Ci(t,"opFloorDivide",e.rhs);case sr.UNI_PLUS:return U_(t,"opUniPlus",e.rhs);case sr.UNI_MINUS:return U_(t,"opUniMinus",e.rhs)}return Ce(e,"")}function uM(e){if(e.type===se.OPERATOR){const t=e.lhs?Be(e.lhs):Ce(e,"");return e.items.forEach(n=>lM(n,t)),t}return Ce(e,"")}function Mc(e,t){return Ce(e,[mt(e,"jump",[`${t}`]),"; continue;"])}function Lr(e){return nn.linelookup[e??""]??-1}function Yf(e,t){nn.linelookup[e]=t}function Oo(e,t,n){for(let r=0;rr.add(Be(i))),P_(n.altlines,se.ELSE_IF,Lr(n.done)),n.altlines.forEach(i=>r.add(Be(i))),r}return Ce(e,Be(e.check))}case se.IF_CHECK:{const n=Lr(e.skip);return n===-1?Ce(e,[" ",mt(e,e.method,Ni(e.words)),`; -`]):Ce(e,[" if (!",mt(e,e.method,Ni(e.words)),") { ",Mc(e,n),` } -`])}case se.ELSE_IF:case se.ELSE:{const n=Ce(e,"");return e.lines.forEach(r=>n.add(Be(r))),n}case se.WHILE:{const n=Lr(e.loop),r=Lr(e.done),i=Ce(e,"");return Oo(e.lines,se.IF_CHECK,e.done),e.lines.forEach(s=>{switch(s.type){case se.BREAK:s.goto=r;break;case se.CONTINUE:s.goto=n;break}i.add(Be(s))}),i}case se.REPEAT:{const n=Lr(e.loop),r=Lr(e.done),i=Ce(e,"");return Oo(e.lines,se.IF_CHECK,e.done),e.lines.forEach(s=>{switch(s.type){case se.BREAK:s.goto=r;break;case se.CONTINUE:s.goto=n;break}i.add(Be(s))}),i}case se.WAITFOR:{const n=Ce(e,"");return n.add([" if (!",mt(e,"if",Ni(e.words)),`) { api.i(${e.lineindex-1}); } -`]),n}case se.FOREACH:{const n=Lr(e.loop),r=Lr(e.done),i=Ce(e,"");return Oo(e.lines,se.IF_CHECK,e.done),e.lines.forEach(s=>{switch(s.type){case se.BREAK:s.goto=r;break;case se.CONTINUE:s.goto=n;break}i.add(Be(s))}),i}case se.BREAK:return Ce(e,[" ",Mc(e,e.goto),` -`]);case se.CONTINUE:return Ce(e,[" ",Mc(e,e.goto),` -`]);case se.OR:return mt(e,"or",e.items.map(Be));case se.AND:return mt(e,"and",e.items.map(Be));case se.NOT:return mt(e,"not",e.items.map(Be));case se.COMPARE:return cM(e);case se.OPERATOR:return uM(e);case se.EXPR:return mt(e,"expr",e.words.map(Be));default:return console.error("",e.type,e),M_(e)}}function or(e){if(E(e))switch(e.type===se.LINE&&++nn.lineindex,e.lineindex=nn.lineindex,e.type){case se.PROGRAM:e.lines.forEach(or);break;case se.LINE:e.stmts.forEach(or);break;case se.MARK:Yf(e.id,e.lineindex);break;case se.IF:or(e.check),or(e.block);break;case se.IF_BLOCK:e.lines.forEach(or),e.altlines.forEach(or);break;case se.ELSE_IF:e.lines.forEach(or);break;case se.ELSE:case se.WHILE:case se.REPEAT:case se.FOREACH:e.lines.forEach(or);break;case se.MOVE:case se.COMMAND:case se.WAITFOR:case se.IF_CHECK:e.words.forEach(or);break}}function fM(e){return nn.labels={},nn.internal=1,nn.lineindex=0,nn.isfirststat=!0,or(e),{...Be(e).toStringWithSourceMap({file:`${Cc}.map`}),...nn}}const Uc={HALT_AT_COUNT:256};function hM(e){return He(e)?e.length>0?1:0:e??0}function Ot(e){return`${e??""}`}function D_(e){return`${e}_chip`}function dM(e,t,n){var c,l;const r=D_(e),i=ms(r);let s;He(i.lb)||(i.lb=_s(Object.entries(n.labels??{})),i.lk="",i.mg=void 0,i.ec=1,i.lc=0,i.ys=0,i.ps=0,i.es=(((c=n.errors)==null?void 0:c.length)??0)!==0?1:0);function o(u,f){L.words=f;const d=yL(t,u);return E(d)?d(a,f):u!=="send"?o("send",[u,...f]):0}const a={halt(){RM(r)},id(){return e},senderid(u=e){return`vm:${u??e}`},set(u,f){const[d,h]=bL(t,a,u,f);if(d)return h},get(u){const[f,d]=_L(t,a,u);if(f)return d},bucket(u){const f=a.get("bucket");He(f)?f.push(u):a.set("bucket",[u])},tick(u){const f=ke(i.ps)?i.ps:0,d=f%u===0;if(i.ps=f+1,d===!1)return!1;if(a.shouldtick()===!1)return h_(t,a),!1;i.lc=0,i.ys=0,L.get=a.get,wL(t,a);try{const h=s==null?void 0:s.next();h!=null&&h.done&&(et("chip","crash","generator logic unexpectedly exited"),i.es=1)}catch(h){et("chip","crash",h.message),i.es=1}return h_(t,a),!0},isended(){return i.es===1},shouldtick(){return i.es===0||a.hm()!==0},shouldhalt(){return ke(i.lc)?++i.lc>Uc.HALT_AT_COUNT:!0},hm(){if(He(i.mg)&&He(i.lb)){const[,u]=i.mg;if(E(u))for(let f=0;fke(p)&&p>0)??0}}return 0},yield(){i.ys=1},jump(u){i.ec=u},sy(){return!!i.ys||a.shouldhalt()},emit(u,f,d){Pe.emit(u,a.senderid(),f,d)},send(u,f,d,h){Pe.emit(`${a.senderid(u)}:${f}`,e,d,h)},lock(u){i.lk=u},unlock(){i.lk=""},message(u){i.lk&&u.sender!==i.lk||(i.mg=[u.id,u.target,u.data,u.sender,u.player])},zap(u){if(He(i.lb))for(let f=0;fm>0);p>=0&&(h[p]*=-1)}}},restore(u){if(He(i.lb))for(let f=0;fh.fileName===Cc);return{line:(d==null?void 0:d.lineNumber)??0,column:(d==null?void 0:d.columnNumber)??0}},text(u){return o("text",[u])},stat(...u){return o("stat",u)},hyperlink(...u){return o("hyperlink",u)},command(...u){if(u.length===0)return 0;const[f,...d]=u;return o(Ot(f),d)},if(...u){const[f,d]=ne(u,0,[q.ANY]),h=hM(f);return h&&d0,m=i[d];return p&&He(m)&&a.command(...m),p?1:0},foreachstart(u,...f){const[d,h,p,m]=ne(f,0,[q.STRING,q.NUMBER,q.NUMBER,q.MAYBE_NUMBER]);let b=Math.min(h,p),_=Math.max(h,p);const w=(m??0)||1;if(w<0){const v=b;b=_,_=v}return a.set(d,b-w),0},foreach(u,...f){const[d,h,p,m,b]=ne(f,0,[q.STRING,q.NUMBER,q.NUMBER,q.MAYBE_NUMBER]);let _=Math.min(h,p),w=Math.max(h,p);const v=(m??0)||1;if(v<0){const I=_;_=w,w=I}let S=a.get(d);!ke(S)||S<_||S>w?S=_:S+=v;const C=S<=w?1:0;return C&&(a.set(d,S),bh?1:0},isLessThanOrEq(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d<=h?1:0},isGreaterThanOrEq(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d>=h?1:0},opPlus(u,f){const[d]=ne([u],0,[q.ANY]),[h]=ne([f],0,[q.ANY]);return d+h},opMinus(u,f){const[d]=ne([u],0,[q.ANY]),[h]=ne([f],0,[q.ANY]);return d-h},opPower(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return Math.pow(d,h)},opMultiply(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d*h},opDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d/h},opModDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d%h},opFloorDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return Math.floor(d/h)},opUniPlus(u){const[f]=ne([u],0,[q.NUMBER]);return+f},opUniMinus(u){const[f]=ne([u],0,[q.NUMBER]);return-f}};return s=(l=n.code)==null?void 0:l.call(n,a),a}function Pc(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var B_={exports:{}};/*! - - JSZip v3.10.1 - A JavaScript class for generating and reading zip files - - - (c) 2009-2016 Stuart Knightley - Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. - - JSZip uses the library pako released under the MIT license : - https://github.com/nodeca/pako/blob/main/LICENSE - */(function(e,t){(function(n){e.exports=n()})(function(){return function n(r,i,s){function o(l,u){if(!i[l]){if(!r[l]){var f=typeof Pc=="function"&&Pc;if(!u&&f)return f(l,!0);if(a)return a(l,!0);var d=new Error("Cannot find module '"+l+"'");throw d.code="MODULE_NOT_FOUND",d}var h=i[l]={exports:{}};r[l][0].call(h.exports,function(p){var m=r[l][1][p];return o(m||p)},h,h.exports,n,r,i,s)}return i[l].exports}for(var a=typeof Pc=="function"&&Pc,c=0;c>2,h=(3&l)<<4|u>>4,p=1>6:64,m=2>4,u=(15&d)<<4|(h=a.indexOf(c.charAt(m++)))>>2,f=(3&h)<<6|(p=a.indexOf(c.charAt(m++))),w[b++]=l,h!==64&&(w[b++]=u),p!==64&&(w[b++]=f);return w}},{"./support":30,"./utils":32}],2:[function(n,r,i){var s=n("./external"),o=n("./stream/DataWorker"),a=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function l(u,f,d,h,p){this.compressedSize=u,this.uncompressedSize=f,this.crc32=d,this.compression=h,this.compressedContent=p}l.prototype={getContentWorker:function(){var u=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),f=this;return u.on("end",function(){if(this.streamInfo.data_length!==f.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},l.createWorkerFrom=function(u,f,d){return u.pipe(new a).pipe(new c("uncompressedSize")).pipe(f.compressWorker(d)).pipe(new c("compressedSize")).withStreamInfo("compression",f)},r.exports=l},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,i){var s=n("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,i){var s=n("./utils"),o=function(){for(var a,c=[],l=0;l<256;l++){a=l;for(var u=0;u<8;u++)a=1&a?3988292384^a>>>1:a>>>1;c[l]=a}return c}();r.exports=function(a,c){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(l,u,f,d){var h=o,p=d+f;l^=-1;for(var m=d;m>>8^h[255&(l^u[m])];return-1^l}(0|c,a,a.length,0):function(l,u,f,d){var h=o,p=d+f;l^=-1;for(var m=d;m>>8^h[255&(l^u.charCodeAt(m))];return-1^l}(0|c,a,a.length,0):0}},{"./utils":32}],5:[function(n,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(n,r,i){var s=null;s=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:s}},{lie:37}],7:[function(n,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=n("pako"),a=n("./utils"),c=n("./stream/GenericWorker"),l=s?"uint8array":"array";function u(f,d){c.call(this,"FlateWorker/"+f),this._pako=null,this._pakoAction=f,this._pakoOptions=d,this.meta={}}i.magic="\b\0",a.inherits(u,c),u.prototype.processChunk=function(f){this.meta=f.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(l,f.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var f=this;this._pako.onData=function(d){f.push({data:d,meta:f.meta})}},i.compressWorker=function(f){return new u("Deflate",f)},i.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,i){function s(h,p){var m,b="";for(m=0;m>>=8;return b}function o(h,p,m,b,_,w){var v,S,C=h.file,I=h.compression,T=w!==l.utf8encode,M=a.transformTo("string",w(C.name)),x=a.transformTo("string",l.utf8encode(C.name)),V=C.comment,oe=a.transformTo("string",w(V)),O=a.transformTo("string",l.utf8encode(V)),k=x.length!==C.name.length,g=O.length!==V.length,N="",W="",B="",Z=C.dir,H=C.date,Y={crc32:0,compressedSize:0,uncompressedSize:0};p&&!m||(Y.crc32=h.crc32,Y.compressedSize=h.compressedSize,Y.uncompressedSize=h.uncompressedSize);var $=0;p&&($|=8),T||!k&&!g||($|=2048);var F=0,ue=0;Z&&(F|=16),_==="UNIX"?(ue=798,F|=function(ee,Se){var je=ee;return ee||(je=Se?16893:33204),(65535&je)<<16}(C.unixPermissions,Z)):(ue=20,F|=function(ee){return 63&(ee||0)}(C.dosPermissions)),v=H.getUTCHours(),v<<=6,v|=H.getUTCMinutes(),v<<=5,v|=H.getUTCSeconds()/2,S=H.getUTCFullYear()-1980,S<<=4,S|=H.getUTCMonth()+1,S<<=5,S|=H.getUTCDate(),k&&(W=s(1,1)+s(u(M),4)+x,N+="up"+s(W.length,2)+W),g&&(B=s(1,1)+s(u(oe),4)+O,N+="uc"+s(B.length,2)+B);var Q="";return Q+=` -\0`,Q+=s($,2),Q+=I.magic,Q+=s(v,2),Q+=s(S,2),Q+=s(Y.crc32,4),Q+=s(Y.compressedSize,4),Q+=s(Y.uncompressedSize,4),Q+=s(M.length,2),Q+=s(N.length,2),{fileRecord:f.LOCAL_FILE_HEADER+Q+M+N,dirRecord:f.CENTRAL_FILE_HEADER+s(ue,2)+Q+s(oe.length,2)+"\0\0\0\0"+s(F,4)+s(b,4)+M+N+oe}}var a=n("../utils"),c=n("../stream/GenericWorker"),l=n("../utf8"),u=n("../crc32"),f=n("../signature");function d(h,p,m,b){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=p,this.zipPlatform=m,this.encodeFileName=b,this.streamFiles=h,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(d,c),d.prototype.push=function(h){var p=h.meta.percent||0,m=this.entriesCount,b=this._sources.length;this.accumulate?this.contentBuffer.push(h):(this.bytesWritten+=h.data.length,c.prototype.push.call(this,{data:h.data,meta:{currentFile:this.currentFile,percent:m?(p+100*(m-b-1))/m:100}}))},d.prototype.openedSource=function(h){this.currentSourceOffset=this.bytesWritten,this.currentFile=h.file.name;var p=this.streamFiles&&!h.file.dir;if(p){var m=o(h,p,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:m.fileRecord,meta:{percent:0}})}else this.accumulate=!0},d.prototype.closedSource=function(h){this.accumulate=!1;var p=this.streamFiles&&!h.file.dir,m=o(h,p,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(m.dirRecord),p)this.push({data:function(b){return f.DATA_DESCRIPTOR+s(b.crc32,4)+s(b.compressedSize,4)+s(b.uncompressedSize,4)}(h),meta:{percent:100}});else for(this.push({data:m.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},d.prototype.flush=function(){for(var h=this.bytesWritten,p=0;p=this.index;c--)l=(l<<8)+this.byteAt(c);return this.index+=a,l},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},r.exports=o},{"../utils":32}],19:[function(n,r,i){var s=n("./Uint8ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,i){var s=n("./DataReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(n,r,i){var s=n("./ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,i){var s=n("../utils"),o=n("../support"),a=n("./ArrayReader"),c=n("./StringReader"),l=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(f){var d=s.getTypeOf(f);return s.checkSupport(d),d!=="string"||o.uint8array?d==="nodebuffer"?new l(f):o.uint8array?new u(s.transformTo("uint8array",f)):new a(s.transformTo("array",f)):new c(f)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,i){var s=n("./GenericWorker"),o=n("../utils");function a(c){s.call(this,"ConvertWorker to "+c),this.destType=c}o.inherits(a,s),a.prototype.processChunk=function(c){this.push({data:o.transformTo(this.destType,c.data),meta:c.meta})},r.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,i){var s=n("./GenericWorker"),o=n("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(a,s),a.prototype.processChunk=function(c){this.streamInfo.crc32=o(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(c){o.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}s.inherits(a,o),a.prototype.processChunk=function(c){if(c){var l=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=l+c.data.length}o.prototype.processChunk.call(this,c)},r.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(c){o.call(this,"DataWorker");var l=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){l.dataIsReady=!0,l.data=u,l.max=u&&u.length||0,l.type=s.getTypeOf(u),l.isPaused||l._tickAndRepeat()},function(u){l.error(u)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,l=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,l);break;case"uint8array":c=this.data.subarray(this.index,l);break;case"array":case"nodebuffer":c=this.data.slice(this.index,l)}return this.index=l,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var c=0;c "+o:o}},r.exports=s},{}],29:[function(n,r,i){var s=n("../utils"),o=n("./ConvertWorker"),a=n("./GenericWorker"),c=n("../base64"),l=n("../support"),u=n("../external"),f=null;if(l.nodestream)try{f=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function d(p,m){return new u.Promise(function(b,_){var w=[],v=p._internalType,S=p._outputType,C=p._mimeType;p.on("data",function(I,T){w.push(I),m&&m(T)}).on("error",function(I){w=[],_(I)}).on("end",function(){try{var I=function(T,M,x){switch(T){case"blob":return s.newBlob(s.transformTo("arraybuffer",M),x);case"base64":return c.encode(M);default:return s.transformTo(T,M)}}(S,function(T,M){var x,V=0,oe=null,O=0;for(x=0;x"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!n("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,i){for(var s=n("./utils"),o=n("./support"),a=n("./nodejsUtils"),c=n("./stream/GenericWorker"),l=new Array(256),u=0;u<256;u++)l[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;l[254]=l[254]=1;function f(){c.call(this,"utf-8 decode"),this.leftOver=null}function d(){c.call(this,"utf-8 encode")}i.utf8encode=function(h){return o.nodebuffer?a.newBufferFrom(h,"utf-8"):function(p){var m,b,_,w,v,S=p.length,C=0;for(w=0;w>>6:(b<65536?m[v++]=224|b>>>12:(m[v++]=240|b>>>18,m[v++]=128|b>>>12&63),m[v++]=128|b>>>6&63),m[v++]=128|63&b);return m}(h)},i.utf8decode=function(h){return o.nodebuffer?s.transformTo("nodebuffer",h).toString("utf-8"):function(p){var m,b,_,w,v=p.length,S=new Array(2*v);for(m=b=0;m>10&1023,S[b++]=56320|1023&_)}return S.length!==b&&(S.subarray?S=S.subarray(0,b):S.length=b),s.applyFromCharCode(S)}(h=s.transformTo(o.uint8array?"uint8array":"array",h))},s.inherits(f,c),f.prototype.processChunk=function(h){var p=s.transformTo(o.uint8array?"uint8array":"array",h.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var m=p;(p=new Uint8Array(m.length+this.leftOver.length)).set(this.leftOver,0),p.set(m,this.leftOver.length)}else p=this.leftOver.concat(p);this.leftOver=null}var b=function(w,v){var S;for((v=v||w.length)>w.length&&(v=w.length),S=v-1;0<=S&&(192&w[S])==128;)S--;return S<0||S===0?v:S+l[w[S]]>v?S:v}(p),_=p;b!==p.length&&(o.uint8array?(_=p.subarray(0,b),this.leftOver=p.subarray(b,p.length)):(_=p.slice(0,b),this.leftOver=p.slice(b,p.length))),this.push({data:i.utf8decode(_),meta:h.meta})},f.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=f,s.inherits(d,c),d.prototype.processChunk=function(h){this.push({data:i.utf8encode(h.data),meta:h.meta})},i.Utf8EncodeWorker=d},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,i){var s=n("./support"),o=n("./base64"),a=n("./nodejsUtils"),c=n("./external");function l(m){return m}function u(m,b){for(var _=0;_>8;this.dir=!!(16&this.externalFileAttributes),h==0&&(this.dosPermissions=63&this.externalFileAttributes),h==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var h=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=h.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=h.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=h.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=h.readInt(4))}},readExtraFields:function(h){var p,m,b,_=h.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});h.index+4<_;)p=h.readInt(2),m=h.readInt(2),b=h.readData(m),this.extraFields[p]={id:p,length:m,value:b};h.setIndex(_)},handleUTF8:function(){var h=f.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=l.utf8decode(this.fileName),this.fileCommentStr=l.utf8decode(this.fileComment);else{var p=this.findExtraFieldUnicodePath();if(p!==null)this.fileNameStr=p;else{var m=o.transformTo(h,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(m)}var b=this.findExtraFieldUnicodeComment();if(b!==null)this.fileCommentStr=b;else{var _=o.transformTo(h,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(_)}}},findExtraFieldUnicodePath:function(){var h=this.extraFields[28789];if(h){var p=s(h.value);return p.readInt(1)!==1||c(this.fileName)!==p.readInt(4)?null:l.utf8decode(p.readData(h.length-5))}return null},findExtraFieldUnicodeComment:function(){var h=this.extraFields[25461];if(h){var p=s(h.value);return p.readInt(1)!==1||c(this.fileComment)!==p.readInt(4)?null:l.utf8decode(p.readData(h.length-5))}return null}},r.exports=d},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,r,i){function s(p,m,b){this.name=p,this.dir=b.dir,this.date=b.date,this.comment=b.comment,this.unixPermissions=b.unixPermissions,this.dosPermissions=b.dosPermissions,this._data=m,this._dataBinary=b.binary,this.options={compression:b.compression,compressionOptions:b.compressionOptions}}var o=n("./stream/StreamHelper"),a=n("./stream/DataWorker"),c=n("./utf8"),l=n("./compressedObject"),u=n("./stream/GenericWorker");s.prototype={internalStream:function(p){var m=null,b="string";try{if(!p)throw new Error("No output type specified.");var _=(b=p.toLowerCase())==="string"||b==="text";b!=="binarystring"&&b!=="text"||(b="string"),m=this._decompressWorker();var w=!this._dataBinary;w&&!_&&(m=m.pipe(new c.Utf8EncodeWorker)),!w&&_&&(m=m.pipe(new c.Utf8DecodeWorker))}catch(v){(m=new u("error")).error(v)}return new o(m,b,"")},async:function(p,m){return this.internalStream(p).accumulate(m)},nodeStream:function(p,m){return this.internalStream(p||"nodebuffer").toNodejsStream(m)},_compressWorker:function(p,m){if(this._data instanceof l&&this._data.compression.magic===p.magic)return this._data.getCompressedWorker();var b=this._decompressWorker();return this._dataBinary||(b=b.pipe(new c.Utf8EncodeWorker)),l.createWorkerFrom(b,p,m)},_decompressWorker:function(){return this._data instanceof l?this._data.getContentWorker():this._data instanceof u?this._data:new a(this._data)}};for(var f=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],d=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},h=0;h>>6:(h<65536?d[b++]=224|h>>>12:(d[b++]=240|h>>>18,d[b++]=128|h>>>12&63),d[b++]=128|h>>>6&63),d[b++]=128|63&h);return d},i.buf2binstring=function(f){return u(f,f.length)},i.binstring2buf=function(f){for(var d=new s.Buf8(f.length),h=0,p=d.length;h>10&1023,w[p++]=56320|1023&m)}return u(w,p)},i.utf8border=function(f,d){var h;for((d=d||f.length)>f.length&&(d=f.length),h=d-1;0<=h&&(192&f[h])==128;)h--;return h<0||h===0?d:h+c[f[h]]>d?h:d}},{"./common":41}],43:[function(n,r,i){r.exports=function(s,o,a,c){for(var l=65535&s|0,u=s>>>16&65535|0,f=0;a!==0;){for(a-=f=2e3>>1:o>>>1;a[c]=o}return a}();r.exports=function(o,a,c,l){var u=s,f=l+c;o^=-1;for(var d=l;d>>8^u[255&(o^a[d])];return-1^o}},{}],46:[function(n,r,i){var s,o=n("../utils/common"),a=n("./trees"),c=n("./adler32"),l=n("./crc32"),u=n("./messages"),f=0,d=4,h=0,p=-2,m=-1,b=4,_=2,w=8,v=9,S=286,C=30,I=19,T=2*S+1,M=15,x=3,V=258,oe=V+x+1,O=42,k=113,g=1,N=2,W=3,B=4;function Z(y,K){return y.msg=u[K],K}function H(y){return(y<<1)-(4y.avail_out&&(G=y.avail_out),G!==0&&(o.arraySet(y.output,K.pending_buf,K.pending_out,G,y.next_out),y.next_out+=G,K.pending_out+=G,y.total_out+=G,y.avail_out-=G,K.pending-=G,K.pending===0&&(K.pending_out=0))}function F(y,K){a._tr_flush_block(y,0<=y.block_start?y.block_start:-1,y.strstart-y.block_start,K),y.block_start=y.strstart,$(y.strm)}function ue(y,K){y.pending_buf[y.pending++]=K}function Q(y,K){y.pending_buf[y.pending++]=K>>>8&255,y.pending_buf[y.pending++]=255&K}function ee(y,K){var G,R,A=y.max_chain_length,D=y.strstart,J=y.prev_length,X=y.nice_match,z=y.strstart>y.w_size-oe?y.strstart-(y.w_size-oe):0,te=y.window,le=y.w_mask,re=y.prev,de=y.strstart+V,Ze=te[D+J-1],Ue=te[D+J];y.prev_length>=y.good_match&&(A>>=2),X>y.lookahead&&(X=y.lookahead);do if(te[(G=K)+J]===Ue&&te[G+J-1]===Ze&&te[G]===te[D]&&te[++G]===te[D+1]){D+=2,G++;do;while(te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&Dz&&--A!=0);return J<=y.lookahead?J:y.lookahead}function Se(y){var K,G,R,A,D,J,X,z,te,le,re=y.w_size;do{if(A=y.window_size-y.lookahead-y.strstart,y.strstart>=re+(re-oe)){for(o.arraySet(y.window,y.window,re,re,0),y.match_start-=re,y.strstart-=re,y.block_start-=re,K=G=y.hash_size;R=y.head[--K],y.head[K]=re<=R?R-re:0,--G;);for(K=G=re;R=y.prev[--K],y.prev[K]=re<=R?R-re:0,--G;);A+=re}if(y.strm.avail_in===0)break;if(J=y.strm,X=y.window,z=y.strstart+y.lookahead,te=A,le=void 0,le=J.avail_in,te=x)for(D=y.strstart-y.insert,y.ins_h=y.window[D],y.ins_h=(y.ins_h<=x&&(y.ins_h=(y.ins_h<=x)if(R=a._tr_tally(y,y.strstart-y.match_start,y.match_length-x),y.lookahead-=y.match_length,y.match_length<=y.max_lazy_match&&y.lookahead>=x){for(y.match_length--;y.strstart++,y.ins_h=(y.ins_h<=x&&(y.ins_h=(y.ins_h<=x&&y.match_length<=y.prev_length){for(A=y.strstart+y.lookahead-x,R=a._tr_tally(y,y.strstart-1-y.prev_match,y.prev_length-x),y.lookahead-=y.prev_length-1,y.prev_length-=2;++y.strstart<=A&&(y.ins_h=(y.ins_h<y.pending_buf_size-5&&(G=y.pending_buf_size-5);;){if(y.lookahead<=1){if(Se(y),y.lookahead===0&&K===f)return g;if(y.lookahead===0)break}y.strstart+=y.lookahead,y.lookahead=0;var R=y.block_start+G;if((y.strstart===0||y.strstart>=R)&&(y.lookahead=y.strstart-R,y.strstart=R,F(y,!1),y.strm.avail_out===0)||y.strstart-y.block_start>=y.w_size-oe&&(F(y,!1),y.strm.avail_out===0))return g}return y.insert=0,K===d?(F(y,!0),y.strm.avail_out===0?W:B):(y.strstart>y.block_start&&(F(y,!1),y.strm.avail_out),g)}),new _e(4,4,8,4,je),new _e(4,5,16,8,je),new _e(4,6,32,32,je),new _e(4,4,16,16,we),new _e(8,16,32,32,we),new _e(8,16,128,128,we),new _e(8,32,128,256,we),new _e(32,128,258,1024,we),new _e(32,258,258,4096,we)],i.deflateInit=function(y,K){return kt(y,K,w,15,8,0)},i.deflateInit2=kt,i.deflateReset=gt,i.deflateResetKeep=$e,i.deflateSetHeader=function(y,K){return y&&y.state?y.state.wrap!==2?p:(y.state.gzhead=K,h):p},i.deflate=function(y,K){var G,R,A,D;if(!y||!y.state||5>8&255),ue(R,R.gzhead.time>>16&255),ue(R,R.gzhead.time>>24&255),ue(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),ue(R,255&R.gzhead.os),R.gzhead.extra&&R.gzhead.extra.length&&(ue(R,255&R.gzhead.extra.length),ue(R,R.gzhead.extra.length>>8&255)),R.gzhead.hcrc&&(y.adler=l(y.adler,R.pending_buf,R.pending,0)),R.gzindex=0,R.status=69):(ue(R,0),ue(R,0),ue(R,0),ue(R,0),ue(R,0),ue(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),ue(R,3),R.status=k);else{var J=w+(R.w_bits-8<<4)<<8;J|=(2<=R.strategy||R.level<2?0:R.level<6?1:R.level===6?2:3)<<6,R.strstart!==0&&(J|=32),J+=31-J%31,R.status=k,Q(R,J),R.strstart!==0&&(Q(R,y.adler>>>16),Q(R,65535&y.adler)),y.adler=1}if(R.status===69)if(R.gzhead.extra){for(A=R.pending;R.gzindex<(65535&R.gzhead.extra.length)&&(R.pending!==R.pending_buf_size||(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending!==R.pending_buf_size));)ue(R,255&R.gzhead.extra[R.gzindex]),R.gzindex++;R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),R.gzindex===R.gzhead.extra.length&&(R.gzindex=0,R.status=73)}else R.status=73;if(R.status===73)if(R.gzhead.name){A=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending===R.pending_buf_size)){D=1;break}D=R.gzindexA&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),D===0&&(R.gzindex=0,R.status=91)}else R.status=91;if(R.status===91)if(R.gzhead.comment){A=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending===R.pending_buf_size)){D=1;break}D=R.gzindexA&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),D===0&&(R.status=103)}else R.status=103;if(R.status===103&&(R.gzhead.hcrc?(R.pending+2>R.pending_buf_size&&$(y),R.pending+2<=R.pending_buf_size&&(ue(R,255&y.adler),ue(R,y.adler>>8&255),y.adler=0,R.status=k)):R.status=k),R.pending!==0){if($(y),y.avail_out===0)return R.last_flush=-1,h}else if(y.avail_in===0&&H(K)<=H(G)&&K!==d)return Z(y,-5);if(R.status===666&&y.avail_in!==0)return Z(y,-5);if(y.avail_in!==0||R.lookahead!==0||K!==f&&R.status!==666){var X=R.strategy===2?function(z,te){for(var le;;){if(z.lookahead===0&&(Se(z),z.lookahead===0)){if(te===f)return g;break}if(z.match_length=0,le=a._tr_tally(z,0,z.window[z.strstart]),z.lookahead--,z.strstart++,le&&(F(z,!1),z.strm.avail_out===0))return g}return z.insert=0,te===d?(F(z,!0),z.strm.avail_out===0?W:B):z.last_lit&&(F(z,!1),z.strm.avail_out===0)?g:N}(R,K):R.strategy===3?function(z,te){for(var le,re,de,Ze,Ue=z.window;;){if(z.lookahead<=V){if(Se(z),z.lookahead<=V&&te===f)return g;if(z.lookahead===0)break}if(z.match_length=0,z.lookahead>=x&&0z.lookahead&&(z.match_length=z.lookahead)}if(z.match_length>=x?(le=a._tr_tally(z,1,z.match_length-x),z.lookahead-=z.match_length,z.strstart+=z.match_length,z.match_length=0):(le=a._tr_tally(z,0,z.window[z.strstart]),z.lookahead--,z.strstart++),le&&(F(z,!1),z.strm.avail_out===0))return g}return z.insert=0,te===d?(F(z,!0),z.strm.avail_out===0?W:B):z.last_lit&&(F(z,!1),z.strm.avail_out===0)?g:N}(R,K):s[R.level].func(R,K);if(X!==W&&X!==B||(R.status=666),X===g||X===W)return y.avail_out===0&&(R.last_flush=-1),h;if(X===N&&(K===1?a._tr_align(R):K!==5&&(a._tr_stored_block(R,0,0,!1),K===3&&(Y(R.head),R.lookahead===0&&(R.strstart=0,R.block_start=0,R.insert=0))),$(y),y.avail_out===0))return R.last_flush=-1,h}return K!==d?h:R.wrap<=0?1:(R.wrap===2?(ue(R,255&y.adler),ue(R,y.adler>>8&255),ue(R,y.adler>>16&255),ue(R,y.adler>>24&255),ue(R,255&y.total_in),ue(R,y.total_in>>8&255),ue(R,y.total_in>>16&255),ue(R,y.total_in>>24&255)):(Q(R,y.adler>>>16),Q(R,65535&y.adler)),$(y),0=G.w_size&&(D===0&&(Y(G.head),G.strstart=0,G.block_start=0,G.insert=0),te=new o.Buf8(G.w_size),o.arraySet(te,K,le-G.w_size,G.w_size,0),K=te,le=G.w_size),J=y.avail_in,X=y.next_in,z=y.input,y.avail_in=le,y.next_in=0,y.input=K,Se(G);G.lookahead>=x;){for(R=G.strstart,A=G.lookahead-(x-1);G.ins_h=(G.ins_h<>>=x=M>>>24,v-=x,(x=M>>>16&255)===0)N[u++]=65535&M;else{if(!(16&x)){if(!(64&x)){M=S[(65535&M)+(w&(1<>>=x,v-=x),v<15&&(w+=g[c++]<>>=x=M>>>24,v-=x,!(16&(x=M>>>16&255))){if(!(64&x)){M=C[(65535&M)+(w&(1<>>=x,v-=x,(x=u-f)>3,w&=(1<<(v-=V<<3))-1,s.next_in=c,s.next_out=u,s.avail_in=c>>24&255)+(O>>>8&65280)+((65280&O)<<8)+((255&O)<<24)}function w(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(O){var k;return O&&O.state?(k=O.state,O.total_in=O.total_out=k.total=0,O.msg="",k.wrap&&(O.adler=1&k.wrap),k.mode=p,k.last=0,k.havedict=0,k.dmax=32768,k.head=null,k.hold=0,k.bits=0,k.lencode=k.lendyn=new s.Buf32(m),k.distcode=k.distdyn=new s.Buf32(b),k.sane=1,k.back=-1,d):h}function S(O){var k;return O&&O.state?((k=O.state).wsize=0,k.whave=0,k.wnext=0,v(O)):h}function C(O,k){var g,N;return O&&O.state?(N=O.state,k<0?(g=0,k=-k):(g=1+(k>>4),k<48&&(k&=15)),k&&(k<8||15=B.wsize?(s.arraySet(B.window,k,g-B.wsize,B.wsize,0),B.wnext=0,B.whave=B.wsize):(N<(W=B.wsize-B.wnext)&&(W=N),s.arraySet(B.window,k,g-N,W,B.wnext),(N-=W)?(s.arraySet(B.window,k,g-N,N,0),B.wnext=N,B.whave=B.wsize):(B.wnext+=W,B.wnext===B.wsize&&(B.wnext=0),B.whave>>8&255,g.check=a(g.check,D,2,0),F=$=0,g.mode=2;break}if(g.flags=0,g.head&&(g.head.done=!1),!(1&g.wrap)||(((255&$)<<8)+($>>8))%31){O.msg="incorrect header check",g.mode=30;break}if((15&$)!=8){O.msg="unknown compression method",g.mode=30;break}if(F-=4,y=8+(15&($>>>=4)),g.wbits===0)g.wbits=y;else if(y>g.wbits){O.msg="invalid window size",g.mode=30;break}g.dmax=1<>8&1),512&g.flags&&(D[0]=255&$,D[1]=$>>>8&255,g.check=a(g.check,D,2,0)),F=$=0,g.mode=3;case 3:for(;F<32;){if(H===0)break e;H--,$+=N[B++]<>>8&255,D[2]=$>>>16&255,D[3]=$>>>24&255,g.check=a(g.check,D,4,0)),F=$=0,g.mode=4;case 4:for(;F<16;){if(H===0)break e;H--,$+=N[B++]<>8),512&g.flags&&(D[0]=255&$,D[1]=$>>>8&255,g.check=a(g.check,D,2,0)),F=$=0,g.mode=5;case 5:if(1024&g.flags){for(;F<16;){if(H===0)break e;H--,$+=N[B++]<>>8&255,g.check=a(g.check,D,2,0)),F=$=0}else g.head&&(g.head.extra=null);g.mode=6;case 6:if(1024&g.flags&&(H<(ee=g.length)&&(ee=H),ee&&(g.head&&(y=g.head.extra_len-g.length,g.head.extra||(g.head.extra=new Array(g.head.extra_len)),s.arraySet(g.head.extra,N,B,ee,y)),512&g.flags&&(g.check=a(g.check,N,ee,B)),H-=ee,B+=ee,g.length-=ee),g.length))break e;g.length=0,g.mode=7;case 7:if(2048&g.flags){if(H===0)break e;for(ee=0;y=N[B+ee++],g.head&&y&&g.length<65536&&(g.head.name+=String.fromCharCode(y)),y&&ee>9&1,g.head.done=!0),O.adler=g.check=0,g.mode=12;break;case 10:for(;F<32;){if(H===0)break e;H--,$+=N[B++]<>>=7&F,F-=7&F,g.mode=27;break}for(;F<3;){if(H===0)break e;H--,$+=N[B++]<>>=1)){case 0:g.mode=14;break;case 1:if(V(g),g.mode=20,k!==6)break;$>>>=2,F-=2;break e;case 2:g.mode=17;break;case 3:O.msg="invalid block type",g.mode=30}$>>>=2,F-=2;break;case 14:for($>>>=7&F,F-=7&F;F<32;){if(H===0)break e;H--,$+=N[B++]<>>16^65535)){O.msg="invalid stored block lengths",g.mode=30;break}if(g.length=65535&$,F=$=0,g.mode=15,k===6)break e;case 15:g.mode=16;case 16:if(ee=g.length){if(H>>=5,F-=5,g.ndist=1+(31&$),$>>>=5,F-=5,g.ncode=4+(15&$),$>>>=4,F-=4,286>>=3,F-=3}for(;g.have<19;)g.lens[J[g.have++]]=0;if(g.lencode=g.lendyn,g.lenbits=7,G={bits:g.lenbits},K=l(0,g.lens,0,19,g.lencode,0,g.work,G),g.lenbits=G.bits,K){O.msg="invalid code lengths set",g.mode=30;break}g.have=0,g.mode=19;case 19:for(;g.have>>16&255,Ge=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>>=we,F-=we,g.lens[g.have++]=Ge;else{if(Ge===16){for(R=we+2;F>>=we,F-=we,g.have===0){O.msg="invalid bit length repeat",g.mode=30;break}y=g.lens[g.have-1],ee=3+(3&$),$>>>=2,F-=2}else if(Ge===17){for(R=we+3;F>>=we)),$>>>=3,F-=3}else{for(R=we+7;F>>=we)),$>>>=7,F-=7}if(g.have+ee>g.nlen+g.ndist){O.msg="invalid bit length repeat",g.mode=30;break}for(;ee--;)g.lens[g.have++]=y}}if(g.mode===30)break;if(g.lens[256]===0){O.msg="invalid code -- missing end-of-block",g.mode=30;break}if(g.lenbits=9,G={bits:g.lenbits},K=l(u,g.lens,0,g.nlen,g.lencode,0,g.work,G),g.lenbits=G.bits,K){O.msg="invalid literal/lengths set",g.mode=30;break}if(g.distbits=6,g.distcode=g.distdyn,G={bits:g.distbits},K=l(f,g.lens,g.nlen,g.ndist,g.distcode,0,g.work,G),g.distbits=G.bits,K){O.msg="invalid distances set",g.mode=30;break}if(g.mode=20,k===6)break e;case 20:g.mode=21;case 21:if(6<=H&&258<=Y){O.next_out=Z,O.avail_out=Y,O.next_in=B,O.avail_in=H,g.hold=$,g.bits=F,c(O,Q),Z=O.next_out,W=O.output,Y=O.avail_out,B=O.next_in,N=O.input,H=O.avail_in,$=g.hold,F=g.bits,g.mode===12&&(g.back=-1);break}for(g.back=0;_e=(A=g.lencode[$&(1<>>16&255,Ge=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>$e)])>>>16&255,Ge=65535&A,!($e+(we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>>=$e,F-=$e,g.back+=$e}if($>>>=we,F-=we,g.back+=we,g.length=Ge,_e===0){g.mode=26;break}if(32&_e){g.back=-1,g.mode=12;break}if(64&_e){O.msg="invalid literal/length code",g.mode=30;break}g.extra=15&_e,g.mode=22;case 22:if(g.extra){for(R=g.extra;F>>=g.extra,F-=g.extra,g.back+=g.extra}g.was=g.length,g.mode=23;case 23:for(;_e=(A=g.distcode[$&(1<>>16&255,Ge=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>$e)])>>>16&255,Ge=65535&A,!($e+(we=A>>>24)<=F);){if(H===0)break e;H--,$+=N[B++]<>>=$e,F-=$e,g.back+=$e}if($>>>=we,F-=we,g.back+=we,64&_e){O.msg="invalid distance code",g.mode=30;break}g.offset=Ge,g.extra=15&_e,g.mode=24;case 24:if(g.extra){for(R=g.extra;F>>=g.extra,F-=g.extra,g.back+=g.extra}if(g.offset>g.dmax){O.msg="invalid distance too far back",g.mode=30;break}g.mode=25;case 25:if(Y===0)break e;if(ee=Q-Y,g.offset>ee){if((ee=g.offset-ee)>g.whave&&g.sane){O.msg="invalid distance too far back",g.mode=30;break}Se=ee>g.wnext?(ee-=g.wnext,g.wsize-ee):g.wnext-ee,ee>g.length&&(ee=g.length),je=g.window}else je=W,Se=Z-g.offset,ee=g.length;for(YT?(x=Se[je+b[k]],F[ue+b[k]]):(x=96,0),w=1<>Z)+(v-=w)]=M<<24|x<<16|V|0,v!==0;);for(w=1<>=1;if(w!==0?($&=w-1,$+=w):$=0,k++,--Q[O]==0){if(O===N)break;O=f[d+b[k]]}if(W>>7)]}function ue(A,D){A.pending_buf[A.pending++]=255&D,A.pending_buf[A.pending++]=D>>>8&255}function Q(A,D,J){A.bi_valid>_-J?(A.bi_buf|=D<>_-A.bi_valid,A.bi_valid+=J-_):(A.bi_buf|=D<>>=1,J<<=1,0<--D;);return J>>>1}function je(A,D,J){var X,z,te=new Array(b+1),le=0;for(X=1;X<=b;X++)te[X]=le=le+J[X-1]<<1;for(z=0;z<=D;z++){var re=A[2*z+1];re!==0&&(A[2*z]=Se(te[re]++,re))}}function we(A){var D;for(D=0;D>1;1<=J;J--)$e(A,te,J);for(z=de;J=A.heap[1],A.heap[1]=A.heap[A.heap_len--],$e(A,te,1),X=A.heap[1],A.heap[--A.heap_max]=J,A.heap[--A.heap_max]=X,te[2*z]=te[2*J]+te[2*X],A.depth[z]=(A.depth[J]>=A.depth[X]?A.depth[J]:A.depth[X])+1,te[2*J+1]=te[2*X+1]=z,A.heap[1]=z++,$e(A,te,1),2<=A.heap_len;);A.heap[--A.heap_max]=A.heap[1],function(Ue,Tn){var Co,ar,Lo,ft,$c,rh,Pr=Tn.dyn_tree,Z_=Tn.max_code,ZM=Tn.stat_desc.static_tree,YM=Tn.stat_desc.has_stree,QM=Tn.stat_desc.extra_bits,Y_=Tn.stat_desc.extra_base,Mo=Tn.stat_desc.max_length,jc=0;for(ft=0;ft<=b;ft++)Ue.bl_count[ft]=0;for(Pr[2*Ue.heap[Ue.heap_max]+1]=0,Co=Ue.heap_max+1;Co>=7;z>>=1)if(1&Ze&&re.dyn_ltree[2*de]!==0)return o;if(re.dyn_ltree[18]!==0||re.dyn_ltree[20]!==0||re.dyn_ltree[26]!==0)return a;for(de=32;de>>3,(te=A.static_len+3+7>>>3)<=z&&(z=te)):z=te=J+5,J+4<=z&&D!==-1?R(A,D,J,X):A.strategy===4||te===z?(Q(A,2+(X?1:0),3),gt(A,oe,O)):(Q(A,4+(X?1:0),3),function(re,de,Ze,Ue){var Tn;for(Q(re,de-257,5),Q(re,Ze-1,5),Q(re,Ue-4,4),Tn=0;Tn>>8&255,A.pending_buf[A.d_buf+2*A.last_lit+1]=255&D,A.pending_buf[A.l_buf+A.last_lit]=255&J,A.last_lit++,D===0?A.dyn_ltree[2*J]++:(A.matches++,D--,A.dyn_ltree[2*(g[J]+f+1)]++,A.dyn_dtree[2*F(D)]++),A.last_lit===A.lit_bufsize-1},i._tr_align=function(A){Q(A,2,3),ee(A,v,oe),function(D){D.bi_valid===16?(ue(D,D.bi_buf),D.bi_buf=0,D.bi_valid=0):8<=D.bi_valid&&(D.pending_buf[D.pending++]=255&D.bi_buf,D.bi_buf>>=8,D.bi_valid-=8)}(A)}},{"../utils/common":41}],53:[function(n,r,i){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,i){(function(s){(function(o,a){if(!o.setImmediate){var c,l,u,f,d=1,h={},p=!1,m=o.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(o);b=b&&b.setTimeout?b:o,c={}.toString.call(o.process)==="[object process]"?function(S){process.nextTick(function(){w(S)})}:function(){if(o.postMessage&&!o.importScripts){var S=!0,C=o.onmessage;return o.onmessage=function(){S=!1},o.postMessage("","*"),o.onmessage=C,S}}()?(f="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",v,!1):o.attachEvent("onmessage",v),function(S){o.postMessage(f+S,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(S){w(S.data)},function(S){u.port2.postMessage(S)}):m&&"onreadystatechange"in m.createElement("script")?(l=m.documentElement,function(S){var C=m.createElement("script");C.onreadystatechange=function(){w(S),C.onreadystatechange=null,l.removeChild(C),C=null},l.appendChild(C)}):function(S){setTimeout(w,0,S)},b.setImmediate=function(S){typeof S!="function"&&(S=new Function(""+S));for(var C=new Array(arguments.length-1),I=0;I"u"?s===void 0?this:s:self)}).call(this,typeof Bt<"u"?Bt:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(B_);var pM=B_.exports,Qf=Pi(pM);const F_={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(F_);var An=function(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)},ps,No,Li;class mM{constructor(...t){ps.set(this,new Map),No.set(this,new Map),Li.set(this,new Map);for(const n of t)this.define(n)}define(t,n=!1){for(let[r,i]of Object.entries(t)){r=r.toLowerCase(),i=i.map(a=>a.toLowerCase()),An(this,Li,"f").has(r)||An(this,Li,"f").set(r,new Set);const s=An(this,Li,"f").get(r);let o=!0;for(let a of i){const c=a.startsWith("*");if(a=c?a.slice(1):a,s==null||s.add(a),o&&An(this,No,"f").set(r,a),o=!1,c)continue;const l=An(this,ps,"f").get(a);if(l&&l!=r&&!n)throw new Error(`"${r} -> ${a}" conflicts with "${l} -> ${a}". Pass \`force=true\` to override this definition.`);An(this,ps,"f").set(a,r)}}return this}getType(t){if(typeof t!="string")return null;const n=t.replace(/^.*[/\\]/,"").toLowerCase(),r=n.replace(/^.*\./,"").toLowerCase(),i=n.length{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(const t of An(this,Li,"f").values())Object.freeze(t);return this}_getTestState(){return{types:An(this,ps,"f"),extensions:An(this,No,"f")}}}ps=new WeakMap,No=new WeakMap,Li=new WeakMap;var gM=new mM(F_)._freeze();function $_(e,t){switch([...t.slice(0,4)].map(i=>i.toString(16)).join("").toUpperCase()){case"89504E47":return"image/png";case"47494638":return"image/gif";case"25504446":return"application/pdf";case"FFD8FFDB":case"FFD8FFE0":case"FFD8FFE1":return"image/jpeg";case"504B0304":return"application/zip"}return gM.getType(e)??"application/octet-stream"}function yM(e){const t=Eg(e,{}),n=Xn(t),r=Ys(t),i=Bn(We.MAIN);if(!E(i))return;const s=Zs(t),o=Ou(i,s,n);E(o)?Nt("memory",`${i.name} already has a [${r}] named ${n}`):(Tg(i,t),W_(t.id,i.id),Nt("memory",`created [${r}] ${n} in ${i.name}`))}async function _M(e){const t=await e.text();yM(t)}async function bM(e,t){try{Nt("parsezipfile",e.name);const n=await e.arrayBuffer();(await new Qf().loadAsync(n)).forEach((s,o)=>{o.async("uint8array").then(a=>{const c=$_(s,a),l=new File([a],o.name,{type:c});t(l)}).catch(a=>{et("memory","crash",a.message)})})}catch(n){et("memory","crash",n.message)}}async function wM(e,t){try{Nt("parsebinaryfile",e.name);const n=await e.arrayBuffer(),r=e.name.split(".").slice(-1)[0]??"";t(De(r),new Uint8Array(n))}catch(n){et("memory","crash",n.message)}}function eh(e){if(!e||e.type===void 0)return;const t=[{start:e.startOffset,end:e.endOffset??0}];return Object.keys(e).forEach(n=>{if(n!=="parent"){const r=e[n];He(r)?r.forEach(i=>{t.push(eh(i))}):t.push(eh(r))}}),e.range={start:Math.min(...t.filter(n=>n).map(n=>(n==null?void 0:n.start)??0)),end:Math.max(...t.filter(n=>n).map(n=>(n==null?void 0:n.end)??0))},e.range}function vM(e){const t=Pm(`${e} -`);if(t.errors.length>0)return t;ds.input=t.tokens;const n=ds.program();if(ds.errors.length>0)return{tokens:t.tokens,errors:ds.errors.map(i=>({offset:i.token.startOffset,line:i.token.startLine,column:i.token.startColumn,length:i.token.image.length,message:i.message}))};const[r]=oM.go(n);return r?(eh(r),{tokens:t.tokens,cst:n,ast:r}):{tokens:t.tokens,cst:n,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]}}const th=Object.getPrototypeOf(function*(){}).constructor;function EM(e,t){const n=`compile-${e}`;console.time(n);const r=vM(t);if(console.timeEnd(n),r.errors&&r.errors.length>0)return r;if(!r.ast)return{...r,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]};const i=fM(r.ast);if(i.code){Vx&&console.info(i.code);try{return{...r,...i,source:i.code,code:new th("api",i.code)}}catch(s){return{errors:[{message:`unexpected error ${s.message}`,offset:0,line:0,column:0,length:0}],source:"",code:new th("api"," ")}}}return{...r,...i,source:"",code:new th("api"," ")}}function kM(){const e={},t={};function n(i,s){const o=e[s];if(o)return o;const a=EM(i,s);return e[s]=a,a}const r={ids(){return Object.keys(t)},has(i){return E(t[i])},isended(i){const s=t[i];return E(s)?s.isended():!0},halt(i){const s=t[i];return E(s)&&(s.halt(),delete t[i]),!!s},gc(){const i=r.ids();for(let s=0;s[_,w]);p.slice(h-5,h).forEach(([_,w])=>{et("os","build",`$grey${w+1} $grey${_}`)});const[m,b]=p[h]??[];if(Ie(m)&&E(b)){const _=(d.column??1)-1,w=_+d.length,v=_{et("os","build",_)}),!1}}return!!(l!=null&&l.tick(o))},once(i,s,o,a){const c=r.tick(i,s,1,o,a);return r.halt(i)&&c},message(i){const{target:s,path:o}=fh(i.target),a=t[s];if(E(a)){const c={...i,target:o};a.message(c)}}};return r}const Mr=kM();var We=(e=>(e.MAIN="main",e.TITLE="title",e.PLAYER="player",e.CONTENT="content",e.GADGETSTORE="gadgetstore",e.GADGETSYNC="gadgetsync",e))(We||{});const ct={defaultplayer:mb(),software:{main:"",content:""},books:new Map,chips:new Map,loaders:new Map,chipindex:new Map,codepageindex:new Map,binaryfiles:new Map};function SM(e){ct.defaultplayer=e}function AM(){return ct.defaultplayer}function Dc(){return[...ct.books.values()]}function TM(){const[e]=ct.books.values();return e}function ni(e){const t=De(e);return ct.books.get(e)??Dc().find(n=>n.name===t)}function Bc(e,t){E(ni(t))&&(ct.software[e]=t)}function Kt(e){return ni(ct.software[e])}function j_(e){const t=Ag([]);return Ie(e)&&(t.name=e),z_(t),Nt("memory",`created [book] ${t.name}`),t}function xM(e){let t=ni(e);return E(t)||(t=Ag([]),t.name=e),z_(t),Nt("memory",`created [book] ${t.name}`),t}function Bn(e,t){let n=E(t)?xM(t):Kt(e);return E(n)||(E(n)||(n=TM()),E(n)||(n=j_(t)),E(n)&&Nt("memory",`opened [book] ${n.name} for ${e}`)),Bc(e,n.id),n}function Mi(e,t,n){const r=Bn(e);let i=yi(r,t);if(E(i))return i;const s=kg(n);return i=Eg(s==="object"?`@${t} -`:`@${s} ${t} -`,{}),Tg(r,i),W_(i.id,r.id),Dr("memory"),i}function ms(e){const t=Bn("main");return Yi(t,e)}function RM(e){const t=Bn("main");return Nu(t,e)}function IM(e,t){ct.books.clear(),e.forEach(r=>{ct.books.set(r.id,r),r.name==="main"&&(ct.software.main=r.id)});const n=ni(t);if(E(n)&&Bc("main",n.id),!ct.software.main){const r=ct.books.values().next();r.value&&(ct.software.main=r.value.id)}}function z_(e){return ct.books.set(e.id,e),e.id}function OM(e){const t=ni(e);t&&ct.books.delete(t.id)}function W_(e,t){ct.codepageindex.set(e,t)}function NM(e){if(!Ie(e)||!e)return et("memory","login",`failed for playerid ==>${e}<==`,e);const t=Kt("main");if(!E(t))return et("memory","login:main","login failed to find book 'main'",e);const n=ja(t,e);if(E(n))return!0;const r=Zi(t,"title");if(!E(r))return et("memory","login:title","login failed to find board 'title'",e);const i=$a(t,"player");if(!E(i))return et("memory","login:player","login failed to find object type 'player'",e);const s={x:0,y:0},o=i.name??"player",a=Fu(r,s,o,e);return E(a==null?void 0:a.id)?(Cu(t,e,r.id),!0):!1}function G_(e){const t=Kt("main"),n=ja(t,e);Cu(t,e,""),Qs(t,n,es(n,e)),Wg(n,e),Nu(t,e),Nu(t,D_(e))}function CM(e){const t=Kt("main"),n=Og(t);for(let r=0;rPh*5&&(n.tickertime=0,n.tickertext=""),L.isplayer){const u=ms(L.player);u.inputcurrent=0}cw(s).forEach(u=>{L[u]=s[u]})}function MM(){const e=Kt("main");if(!E(e))return;const t=e.timestamp+1,n=Uc.HALT_AT_COUNT;Uc.HALT_AT_COUNT=n*2,ct.loaders.forEach((i,s)=>{Mr.tick(s,ko.LOADER,1,"loader",i),Mr.isended(s)&&(Mr.halt(s),ct.loaders.delete(s))}),Uc.HALT_AT_COUNT=n,e.timestamp=t,L.timestamp=t,Og(e).forEach(i=>{const s=tI(e,i,t);for(let o=0;o{const c=Xs(a);return Object.keys(c).filter(u=>s.includes(De(u))).length===s.length});for(let a=0;aet("memory","crash",i.message));break;case"application/zip":bM(t,i=>K_(e,i)).catch(i=>et("memory","crash",i.message));break;case"application/octet-stream":wM(t,(i,s)=>{DM(e,t,i,s)}).catch(i=>et("memory","crash",i.message));break;default:t.arrayBuffer().then(i=>{const s=$_(t.name,new Uint8Array(i));if(s)n(s);else return et("memory","loadfile",`unsupported file ${t.name}`)}).catch(i=>et("memory","crash",i.message));return}}n((t==null?void 0:t.type)??"")}let q_=0;function BM(){switch(q_++){case 0:return be.BLUE;case 1:return be.GREEN;case 2:return be.CYAN;case 3:return be.RED;case 4:return be.PURPLE;case 5:return be.YELLOW;default:return q_=0,be.WHITE}}function FM(e,t,n,r,i,s){const o=[];let a=t;const c=a===0,l=ze,u=rn,f=c?be.BLACK:be.ONCLEAR,d=hh(e,a++,l,u,f);o.push(d);const h=vb(e,a++,l,u);o.push(h);const p=a++,m=wb(e,p);o.push(m);const b=hh(e,a++,l,u,be.ONCLEAR);o.push(b);const _={...I_(ze,rn,BM(),be.ONCLEAR),...b},w=Eb(e,a++);i&&o.push(w),r.terrain.forEach((T,M)=>{if(T){const x=Ln(n,T);d.char[M]=T.char??(x==null?void 0:x.char)??0,d.color[M]=T.color??(x==null?void 0:x.color)??f,d.bg[M]=T.bg??(x==null?void 0:x.bg)??f,d.color[M]!==be.ONCLEAR&&(s[M]=d.color[M])}});const v=r.objects??{};Object.values(v).forEach(T=>{if(E(T.removed)||E(T.headless))return;const M=T.id??"",x=xg(n,T),V=bb(e,p,M),oe=T.lx??T.x??0,O=T.ly??T.y??0,k=oe+O*ze;if(V.x=T.x??0,V.y=T.y??0,V.char=T.char??(x==null?void 0:x.char)??1,V.color=T.color??(x==null?void 0:x.color)??be.WHITE,V.bg=T.bg??(x==null?void 0:x.bg)??be.ONBORROW,m.sprites.push(V),V.bg===be.ONSHADOW&&(V.bg=be.ONCLEAR,h.alphas[oe+O*l]=.5),V.bg===be.ONBORROW&&(V.bg=s[k]??be.BLACK),V.color!==be.ONCLEAR&&(s[k]=V.color),Ie(T.tickertext)&&ke(T.tickertime)&&T.tickertext.length){const g=ze,N=YL(T.tickertext,g,rn-1),W=(N==null?void 0:N.measuredwidth)??1,B=T.x??0,Z=T.y??0,H=Zze&&(_.x=ze-W),_.x<0&&(_.x=0),ZL(T.tickertext,_)}M===e&&(w.focusx=V.x,w.focusy=V.y,w.focusid=M)});function S(T,M){if(!(T<0||T>=ze||M<0||M>=rn))return h.alphas[T+M*ze]}const C=[[1,1,1,1,1],[1,3,5,3,1],[1,5,12,5,1],[1,3,5,3,1],[1,1,1,1,1]].flat(),I=new Array(h.alphas.length);for(let T=0;TE(oe)?oe*C[O]:void 0).filter(E);I[T]=si(bw(V),0,1)}return h.alphas=I,o}function $M(e){const t=Kt("main"),n=ja(t,e),r=[];if(!E(t)||!E(n))return r;const i=new Array(ze*rn).fill(0),s=Zi(t,n.over??""),o=Zi(t,n.under??""),a=[s,n,o].filter(E);let c=0;for(let l=0;l{const r=new Qf;for(let i=0;i{t(zM(i))}).catch(n)})}async function HM(e){return new Promise((t,n)=>{const r=new Qf;r.loadAsync(jM(e),{base64:!0}).then(async()=>{const i=[],s=[];r.forEach((o,a)=>s.push(a));for(let o=0;o{var t;switch(e.target){case"init":E(e.player)&&(SM(e.player),Fn.reply(e,"ackinit",!0,e.player));break;case"books":Gc("vm:books",async()=>{if(He(e.data)){const[n,r]=e.data,i=await HM(n),s=i.map(o=>o.name);IM(i,r),Me(Fn.name(),"loading",s.join(", ")),Fn.reply(e,"ackbooks",!0,e.player)}});break;case"login":e.player&&NM(e.player)&&(Ui[e.player]=0,Me(Fn.name(),"player login",e.player),Fn.reply(e,"acklogin",!0,e.player));break;case"endgame":Gc("vm:endgame",async()=>{e.player&&(G_(e.player),Ob("vm",e.player),await nh(),Mb("vm"))});break;case"doot":e.player&&(Ui[e.player]=0,ph(Fn.name(),"active",e.player));break;case"input":if(e.player){const n=ms(e.player),[r=Ft.NONE,i=0]=e.data??[Ft.NONE,0];He(n.inputqueue)||(n.inputqueue=[]),r!==Ft.NONE&&n.inputqueue.push([r,i])}break;case"codewatch":if(e.player&&He(e.data)){const[n,r]=e.data;if(!E(gs[r])){const i=mh(n,r);gs[r]=t_(i,s=>{const o=ni(n),a=yi(o,r);E(a)&&(a.code=s,GR(a))})}Ur[n]=Ur[n]??{},Ur[n][r]=Ur[n][r]??new Set,Ur[n][r].add(e.player)}break;case"coderelease":if(e.player&&He(e.data)){const[n,r]=e.data;E(Ur[n])&&E(Ur[n][r])&&(Ur[n][r].delete(e.player),Ur[n][r].size===0&&((t=gs[r])==null||t.call(gs),gs[r]=void 0))}break;case"tick":e.player!=="locked"&&MM();break;case"second":{CM(Ui);const n=Object.keys(Ui);for(let r=0;r=VM&&(delete Ui[i],G_(i),Nt(Fn.name(),"player logout",i),Fn.emit("logout",void 0,i))}++J_>=KM&&(J_=0,Dr(Fn.name()));break}case"flush":Gc("vm:flush",async()=>{Ie(e.data)?await nh(`${e.data} `):await nh()});break;case"cli":E(e.player)&&PM(e.player,e.data);break;case"loadfile":E(e.player)&&K_(e.player,e.data);break;default:LM(e);break}});function qM(){Fn.emit("ready",void 0,AM())}function JM(e){const t=Kt(We.MAIN);if(!E(t))return xc("");const n=Yi(t,We.GADGETSTORE);delete n[e]}iL(e=>{const t=Kt(We.MAIN);if(!E(t))return xc("");const n=Yi(t,We.GADGETSTORE);let r=n[e];return E(r)||(n[e]=r=xc(e)),r});const X_=Po("gadgetserver",["tock"],e=>{const t=Kt(We.MAIN),n=(t==null?void 0:t.activelist)??[],r=Yi(t,We.GADGETSYNC);switch(e.target){case"tock":for(let i=0;ipostMessage(e));onmessage=function(t){XM(t.data)},setTimeout(qM)})(); diff --git a/assets/simspace-_1023Pw3.js b/assets/simspace-_1023Pw3.js new file mode 100644 index 00000000..65412e0c --- /dev/null +++ b/assets/simspace-_1023Pw3.js @@ -0,0 +1,208 @@ +var pM=Object.defineProperty;var mM=(or,Te,Pt)=>Te in or?pM(or,Te,{enumerable:!0,configurable:!0,writable:!0,value:Pt}):or[Te]=Pt;var ye=(or,Te,Pt)=>mM(or,typeof Te!="symbol"?Te+"":Te,Pt);(function(){"use strict";const or=new Set,Te={emit(t,e,n,r){Te.invoke(K_(t,e,n,r))},invoke(t){or.forEach(e=>e.handle(t))},connect(t){or.add(t)},disconnect(t){or.delete(t)}};var Pt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ii(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function N_(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}),n}var Hf={};(function(t){var e=Pt&&Pt.__spreadArray||function(l,u,f){if(f||arguments.length===2)for(var d=0,h=u.length,p;df.length?u:f})}function i(l){return l.reduce(function(u,f){return u.lengthcrypto.getRandomValues(new Uint8Array(t)),U_=(t,e,n)=>{let r=(2<{let o="";for(;;){let a=n(i),c=i;for(;c--;)if(o+=t[a[c]&r]||"",o.length===s)return o}}},Vf=(t,e=21)=>U_(t,e,M_),P_=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t));for(;t--;)e+=L_[n[t]&63];return e};var Kf="abcdefghijklmnopqrstuvwxyz",qf="ABCDEFGHIJKLMNOPQRSTUVWXYZ",Jf="0123456789",D_="346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz",B_="6789BCDFGHJKLMNPQRTWbcdfghjkmnpqrtwz";const F_=Jf,$_=Kf,j_=qf;var z_=F_+$_+j_,Oc={lowercase:Kf,uppercase:qf,numbers:Jf,nolookalikes:D_,nolookalikesSafe:B_,alphanumeric:z_};function ht(){return`sid_${P_(12).replaceAll("-",".")}`}const W_=Vf(Oc.numbers,4),G_=Vf(`${Oc.numbers}${Oc.lowercase}`,16);function H_(){return`pid_${W_()}_${G_()}`}function Xf(t){return(t==null?void 0:t.startsWith("pid_"))??!1}function V_(){return C_({capitalize:!1,adjectiveCount:1})}var be=(t=>(t[t.BLACK=0]="BLACK",t[t.DKBLUE=1]="DKBLUE",t[t.DKGREEN=2]="DKGREEN",t[t.DKCYAN=3]="DKCYAN",t[t.DKRED=4]="DKRED",t[t.DKPURPLE=5]="DKPURPLE",t[t.DKYELLOW=6]="DKYELLOW",t[t.LTGRAY=7]="LTGRAY",t[t.DKGRAY=8]="DKGRAY",t[t.BLUE=9]="BLUE",t[t.GREEN=10]="GREEN",t[t.CYAN=11]="CYAN",t[t.RED=12]="RED",t[t.PURPLE=13]="PURPLE",t[t.YELLOW=14]="YELLOW",t[t.WHITE=15]="WHITE",t[t.ONBLACK=16]="ONBLACK",t[t.ONDKBLUE=17]="ONDKBLUE",t[t.ONDKGREEN=18]="ONDKGREEN",t[t.ONDKCYAN=19]="ONDKCYAN",t[t.ONDKRED=20]="ONDKRED",t[t.ONDKPURPLE=21]="ONDKPURPLE",t[t.ONDKYELLOW=22]="ONDKYELLOW",t[t.ONLTGRAY=23]="ONLTGRAY",t[t.ONDKGRAY=24]="ONDKGRAY",t[t.ONBLUE=25]="ONBLUE",t[t.ONGREEN=26]="ONGREEN",t[t.ONCYAN=27]="ONCYAN",t[t.ONRED=28]="ONRED",t[t.ONPURPLE=29]="ONPURPLE",t[t.ONYELLOW=30]="ONYELLOW",t[t.ONWHITE=31]="ONWHITE",t[t.ONCLEAR=32]="ONCLEAR",t[t.ONSHADOW=33]="ONSHADOW",t[t.ONBORROW=34]="ONBORROW",t))(be||{}),Ye=(t=>(t[t.ISWALK=0]="ISWALK",t[t.ISSOLID=1]="ISSOLID",t[t.ISSWIM=2]="ISSWIM",t[t.ISBULLET=3]="ISBULLET",t))(Ye||{}),Ao=(t=>(t[t.ISTERRAIN=0]="ISTERRAIN",t[t.ISOBJECT=1]="ISOBJECT",t))(Ao||{}),ae=(t=>(t[t.IDLE=0]="IDLE",t[t.NORTH=1]="NORTH",t[t.SOUTH=2]="SOUTH",t[t.WEST=3]="WEST",t[t.EAST=4]="EAST",t[t.BY=5]="BY",t[t.AT=6]="AT",t[t.FLOW=7]="FLOW",t[t.SEEK=8]="SEEK",t[t.RNDNS=9]="RNDNS",t[t.RNDNE=10]="RNDNE",t[t.RND=11]="RND",t[t.CW=12]="CW",t[t.CCW=13]="CCW",t[t.OPP=14]="OPP",t[t.RNDP=15]="RNDP",t))(ae||{}),fe=(t=>(t[t.LOADER=0]="LOADER",t[t.BOARD=1]="BOARD",t[t.OBJECT=2]="OBJECT",t[t.TERRAIN=3]="TERRAIN",t[t.CHARSET=4]="CHARSET",t[t.PALETTE=5]="PALETTE",t[t.CONST=6]="CONST",t[t.RANGE=7]="RANGE",t[t.SELECT=8]="SELECT",t[t.NUMBER=9]="NUMBER",t[t.TEXT=10]="TEXT",t[t.LINK=11]="LINK",t[t.HOTKEY=12]="HOTKEY",t[t.SCROLL=13]="SCROLL",t[t.COPYIT=14]="COPYIT",t))(fe||{});function Pe(t){return t.toLowerCase().trim()}function K_(t,e,n,r){return{id:ht(),target:t,sender:e,data:n,player:r}}function Zf(t){const[e,...n]=t.split(":");return{target:e,path:n.join(":")}}function ls(t,e,n){const r=ht(),i=Pe(t),s=e.map(Pe),o={id(){return r},name(){return t},topics(){return e},emit(a,c,l){Te.emit(a,r,c,l)},reply(a,c,l,u){o.emit(`${a.sender}:${c}`,l,u)},handle(a){const{target:c,path:l}=Zf(a.target),u=Pe(c);s.findIndex(f=>f==="all"||f===u)!==-1&&n(a),(r===c||u==="all"||i===u)&&n({...a,target:l})}};return Te.connect(o),o}/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017-2022 Joachim Wester + * MIT licensed + */var q_=function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),J_=Object.prototype.hasOwnProperty;function Nc(t,e){return J_.call(t,e)}function Cc(t){if(Array.isArray(t)){for(var e=new Array(t.length),n=0;n=48&&r<=57){e++;continue}return!1}return!0}function Zr(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Yf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Mc(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(l[h]===void 0?d=c.slice(0,u).join("/"):u==f-1&&(d=e.path),d!==void 0&&p(e,0,t,d)),u++,Array.isArray(l)){if(h==="-")h=l.length;else{if(n&&!Lc(h))throw new st("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);Lc(h)&&(h=~~h)}if(u>=f){if(n&&e.op==="add"&&h>l.length)throw new st("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);var o=Z_[e.op].call(e,l,h,t);if(o.test===!1)throw new st("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return o}}else if(u>=f){var o=Oi[e.op].call(e,l,h,t);if(o.test===!1)throw new st("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return o}if(l=l[h],n&&u0)throw new st('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new st("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new st("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Mc(t.value))throw new st("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var i=t.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new st("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new st("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var o={op:"_get",path:t.from,value:void 0},a=th([o],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new st("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new st("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function th(t,e,n){try{if(!Array.isArray(t))throw new st("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Uc(Vt(e),Vt(t),n||!0);else{n=n||xo;for(var r=0;r0&&(t.patches=[],t.callback&&t.callback(r)),r}function Bc(t,e,n,r,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=Cc(e),o=Cc(t),a=!1,c=o.length-1;c>=0;c--){var l=o[c],u=t[l];if(Nc(e,l)&&!(e[l]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof u=="object"&&u!=null&&typeof f=="object"&&f!=null&&Array.isArray(u)===Array.isArray(f)?Bc(u,f,n,r+"/"+Zr(l),i):u!==f&&(i&&n.push({op:"test",path:r+"/"+Zr(l),value:Vt(u)}),n.push({op:"replace",path:r+"/"+Zr(l),value:Vt(f)}))}else Array.isArray(t)===Array.isArray(e)?(i&&n.push({op:"test",path:r+"/"+Zr(l),value:Vt(u)}),n.push({op:"remove",path:r+"/"+Zr(l)}),a=!0):(i&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}))}if(!(!a&&s.length==o.length))for(var c=0;c{e.has(s.id)||(e.add(s.id),t(s))});function i(){Te.disconnect(r)}return{forward:n,disconnect:i}}const Fc=66.666,Io=Math.round(1e3/Fc),_b=3;function bb(){return location.href.includes("/join/")}function wb(){return location.href.includes("/locked/")}const $c=ls("clock",[],()=>{});let jc=0,Oo=0,zc=0,rh=performance.now();function ih(){const t=performance.now(),e=t-rh,n=wb()?"locked":"";zc+=e,zc>=Fc&&(zc%=Fc,$c.emit("tick",Oo,n),$c.emit("tock",Oo,n),++jc,++Oo,jc>=Io&&(jc%=Io,$c.emit("second",Oo,n))),rh=t,setTimeout(ih,1)}ih();var sh={exports:{}};/*! Case - v1.6.2 - 2020-03-24 +* Copyright (c) 2020 Nathan Bubna; Licensed MIT, GPL */(function(t){(function(){var e=function(h,p){return p=p||"",h.replace(/(^|-)/g,"$1\\u"+p).replace(/,/g,"\\u"+p)},n=e("20-26,28-2F,3A-40,5B-60,7B-7E,A0-BF,D7,F7","00"),r="a-z"+e("DF-F6,F8-FF","00"),i="A-Z"+e("C0-D6,D8-DE","00"),s="A|An|And|As|At|But|By|En|For|If|In|Of|On|Or|The|To|Vs?\\.?|Via",o=function(h,p,m,b){return h=h||n,p=p||r,m=m||i,b=b||s,{capitalize:new RegExp("(^|["+h+"])(["+p+"])","g"),pascal:new RegExp("(^|["+h+"])+(["+p+m+"])","g"),fill:new RegExp("["+h+"]+(.|$)","g"),sentence:new RegExp('(^\\s*|[\\?\\!\\.]+"?\\s+"?|,\\s+")(['+p+"])","g"),improper:new RegExp("\\b("+b+")\\b","g"),relax:new RegExp("([^"+m+"])(["+m+"]*)(["+m+"])(?=[^"+m+"]|$)","g"),upper:new RegExp("^[^"+p+"]+$"),hole:/[^\s]\s[^\s]/,apostrophe:/'/g,room:new RegExp("["+h+"]")}},a=o(),c={re:a,unicodes:e,regexps:o,types:[],up:String.prototype.toUpperCase,low:String.prototype.toLowerCase,cap:function(h){return c.up.call(h.charAt(0))+h.slice(1)},decap:function(h){return c.low.call(h.charAt(0))+h.slice(1)},deapostrophe:function(h){return h.replace(a.apostrophe,"")},fill:function(h,p,m){return p!=null&&(h=h.replace(a.fill,function(b,_){return _?p+_:""})),m&&(h=c.deapostrophe(h)),h},prep:function(h,p,m,b){if(h=h==null?"":h+"",!b&&a.upper.test(h)&&(h=c.low.call(h)),!p&&!a.hole.test(h)){var _=c.fill(h," ");a.hole.test(_)&&(h=_)}return!m&&!a.room.test(h)&&(h=h.replace(a.relax,c.relax)),h},relax:function(h,p,m,b){return p+" "+(m?m+" ":"")+b}},l={_:c,of:function(h){for(var p=0,m=c.types.length;p0&&b<_.lastIndexOf(" ")?c.low.call(p):p})},sentence:function(h,p,m){return h=l.lower(h).replace(a.sentence,function(b,_,w){return _+c.up.call(w)}),p&&p.forEach(function(b){h=h.replace(new RegExp("\\b"+l.lower(b)+"\\b","g"),c.cap)}),m&&m.forEach(function(b){h=h.replace(new RegExp("(\\b"+l.lower(b)+"\\. +)(\\w)"),function(_,w,v){return w+c.low.call(v)})}),h}};u.squish=u.pascal,l.default=l;for(var f in u)l.type(f,u[f]);var d=typeof d=="function"?d:function(){};d(t.exports?t.exports=l:this.Case=l)}).call(Pt)})(sh);var vb=sh.exports,Eb=Ii(vb);function hs(){return hs=Object.assign||function(t){for(var e=1;e0}function Gc(t){Co++;try{return t()}finally{Co--,Co===0&&xb()}}var Hc=!1;function uh(){return Hc}function fh(t){Hc=!0;try{t()}finally{Hc=!1}}function Tb(t){return function(){return fh(t)}}var Vc=[];function xb(){var t=[].concat(Vc);Vc=[],hh(t)}function hh(t){var e=new Set;t.forEach(function(n){var r;(n.type==="add"||n.type==="delete")&&n.observable[yt].connections.iterate.forEach(function(i){e.add(i)}),(r=n.observable[yt].connections.byKey.get(n.key))==null||r.forEach(function(i){e.add(i)})}),e.forEach(function(n){n.trigger()})}function Lo(t){if(lh()){Vc.push(t);return}hh([t])}function dh(t,e){if(t.type==="iterate")t.observable[yt].connections.iterate.add(e);else{var n=t.observable[yt].connections.byKey.get(t.key);n||(n=new Set,t.observable[yt].connections.byKey.set(t.key,n)),n.add(e)}}function Mo(t,e){if(!uh()){var n=ch();n&&(dh(t,n),n.registerConnection(t)),e&&(dh(t,e),e.registerConnection(t))}}var Kc=Symbol("$skipreactive"),yt=Symbol("$reactive"),cn=Symbol("$reactiveproxy");function ds(t,e){return!!(t&&t[cn]&&t[cn].implicitObserver===e)}function qc(t){return t[Kc]=!0,t}function ph(t){return!!(t&&!ds(t)&&t[yt])}function Jc(t,e,n){if(n===void 0&&(n=!1),t[Kc]||ds(t,e))return t;var r=Rb(t,n);if(!e)return r;var i=r[yt].proxiesWithImplicitObserver.get(e);if(!i){var s={implicitObserver:e};Object.setPrototypeOf(s,mh),i=new Proxy(r[yt].raw,s),r[yt].proxiesWithImplicitObserver.set(e,i)}return i}var ps=Jc;function Rb(t,e){if(e===void 0&&(e=!1),ds(t))return t;if(ph(t))return t[yt].proxy;if(t[yt]||t[cn])throw new Error("unexpected");var n={connections:{iterate:new Set,byKey:new Map},proxy:{},raw:t,proxiesWithImplicitObserver:new Map,shallow:e};Object.defineProperty(t,yt,{enumerable:!1,writable:!0,configurable:!0,value:n});var r=new Proxy(t,mh);return n.proxy=r,r}var mh={has:function(e,n){var r=Reflect.has(e,n);return typeof n=="symbol"||Mo({observable:e,key:n,type:"has"},this.implicitObserver),r},get:function(e,n,r){if(n===cn)return{implicitObserver:this.implicitObserver};var i=Reflect.get(e,n,r);if(typeof n=="symbol")return n.toString()==="Symbol($reactiveproxy)"&&console.error("warning, Symbol($reactiveproxy) passed, but does not match $reactiveproxy. Multiple Reactive libraries loaded?"),i;if(n==="length"&&Array.isArray(e)?Mo({observable:e,type:"iterate"},this.implicitObserver):Mo({observable:e,key:n,type:"get"},this.implicitObserver),ph(i))return Jc(i,this.implicitObserver);if(e[yt].shallow)return i;if(typeof i=="object"&&i!==null&&!ds(i,this.implicitObserver)&&!Object.isFrozen(i)){var s=Reflect.getOwnPropertyDescriptor(e,n);if((!s||!(s.writable===!1&&s.configurable===!1))&&(ah()||this.implicitObserver))return Jc(i,this.implicitObserver)}return i},ownKeys:function(e){return Mo({observable:e,type:"iterate"},this.implicitObserver),Reflect.ownKeys(e)},set:function(e,n,r,i){return Gc(function(){if(typeof n=="symbol")return Reflect.set(e,n,r,i);var s=Object.hasOwnProperty.call(e,n),o=Reflect.get(e,n,i),a=Reflect.set(e,n,r,i);if(!s)Lo({observable:e,key:n,value:r,type:"add"});else if(r!==o)if(n==="length"&&Array.isArray(e)){if(!(onew Map,Xc=t=>{const e=Sn();return t.forEach((n,r)=>{e.set(r,n)}),e},Nr=(t,e,n)=>{let r=t.get(e);return r===void 0&&t.set(e,r=n()),r},Lb=(t,e)=>{const n=[];for(const[r,i]of t)n.push(e(i,r));return n},Mb=(t,e)=>{for(const[n,r]of t)if(e(r,n))return!0;return!1},Ni=()=>new Set,Zc=t=>t[t.length-1],Ub=(t,e)=>{for(let n=0;n{this.off(e,r),n(...i)};this.on(e,r)}off(e,n){const r=this._observers.get(e);r!==void 0&&(r.delete(n),r.size===0&&this._observers.delete(e))}emit(e,n){return Cr((this._observers.get(e)||Sn()).values()).forEach(r=>r(...n))}destroy(){this._observers=Sn()}}const Lr=Math.floor,Uo=Math.abs,yh=(t,e)=>tt>e?t:e,_h=t=>t!==0?t<0:1/t<0,bh=1,wh=2,Yc=4,Qc=8,ms=32,ar=64,tn=128,Po=31,el=63,ti=127,Bb=2147483647,vh=Number.MAX_SAFE_INTEGER,Fb=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Lr(t)===t),$b=t=>t.toLowerCase(),jb=/^\s*/g,zb=t=>t.replace(jb,""),Wb=/([A-Z])/g,Eh=(t,e)=>zb(t.replace(Wb,n=>`${e}${$b(n)}`)),Gb=t=>{const e=unescape(encodeURIComponent(t)),n=e.length,r=new Uint8Array(n);for(let i=0;igs.encode(t):Gb;let ys=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ys&&ys.decode(new Uint8Array).length===1&&(ys=null);class _s{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Mr=()=>new _s,Vb=t=>{let e=t.cpos;for(let n=0;n{const e=new Uint8Array(Vb(t));let n=0;for(let r=0;r{const n=t.cbuf.length;n-t.cpos{const n=t.cbuf.length;t.cpos===n&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(n*2),t.cpos=0),t.cbuf[t.cpos++]=e},tl=St,ve=(t,e)=>{for(;e>ti;)St(t,tn|ti&e),e=Lr(e/128);St(t,ti&e)},nl=(t,e)=>{const n=_h(e);for(n&&(e=-e),St(t,(e>el?tn:0)|(n?ar:0)|el&e),e=Lr(e/64);e>0;)St(t,(e>ti?tn:0)|ti&e),e=Lr(e/128)},rl=new Uint8Array(3e4),qb=rl.length/3,Jb=(t,e)=>{if(e.length{const n=unescape(encodeURIComponent(e)),r=n.length;ve(t,r);for(let i=0;i{const n=t.cbuf.length,r=t.cpos,i=yh(n-r,e.length),s=e.length-i;t.cbuf.set(e.subarray(0,i),r),t.cpos+=i,s>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(ei(n*2,s)),t.cbuf.set(e.subarray(i)),t.cpos=s)},Mt=(t,e)=>{ve(t,e.byteLength),Do(t,e)},il=(t,e)=>{Kb(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},Zb=(t,e)=>il(t,4).setFloat32(0,e,!1),Yb=(t,e)=>il(t,8).setFloat64(0,e,!1),Qb=(t,e)=>il(t,8).setBigInt64(0,e,!1),kh=new DataView(new ArrayBuffer(4)),ew=t=>(kh.setFloat32(0,t),kh.getFloat32(0)===t),bs=(t,e)=>{switch(typeof e){case"string":St(t,119),Ci(t,e);break;case"number":Fb(e)&&Uo(e)<=Bb?(St(t,125),nl(t,e)):ew(e)?(St(t,124),Zb(t,e)):(St(t,123),Yb(t,e));break;case"bigint":St(t,122),Qb(t,e);break;case"object":if(e===null)St(t,126);else if(Pb(e)){St(t,117),ve(t,e.length);for(let n=0;n0&&ve(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Ah=t=>{t.count>0&&(nl(t.encoder,t.count===1?t.s:-t.s),t.count>1&&ve(t.encoder,t.count-2))};class Bo{constructor(){this.encoder=new _s,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Ah(this),this.count=1,this.s=e)}toUint8Array(){return Ah(this),An(this.encoder)}}const Th=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);nl(t.encoder,e),t.count>1&&ve(t.encoder,t.count-2)}};class sl{constructor(){this.encoder=new _s,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Th(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Th(this),An(this.encoder)}}class tw{constructor(){this.sarr=[],this.s="",this.lensE=new Bo}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new _s;return this.sarr.push(this.s),this.s="",Ci(e,this.sarr.join("")),Do(e,this.lensE.toUint8Array()),An(e)}}const Ur=t=>new Error(t),Dn=()=>{throw Ur("Method unimplemented")},Bn=()=>{throw Ur("Unexpected case")},xh=Ur("Unexpected end of array"),Rh=Ur("Integer out of Range");class Fo{constructor(e){this.arr=e,this.pos=0}}const ni=t=>new Fo(t),nw=t=>t.pos!==t.arr.length,rw=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},Dt=t=>rw(t,Ee(t)),Li=t=>t.arr[t.pos++],Ee=t=>{let e=0,n=1;const r=t.arr.length;for(;t.posvh)throw Rh}throw xh},ol=t=>{let e=t.arr[t.pos++],n=e&el,r=64;const i=(e&ar)>0?-1:1;if(!(e&tn))return i*n;const s=t.arr.length;for(;t.posvh)throw Rh}throw xh},Mi=ys?t=>ys.decode(Dt(t)):t=>{let e=Ee(t);if(e===0)return"";{let n=String.fromCodePoint(Li(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(Li(t));else for(;e>0;){const r=e<1e4?e:1e4,i=t.arr.subarray(t.pos,t.pos+r);t.pos+=r,n+=String.fromCodePoint.apply(null,i),e-=r}return decodeURIComponent(escape(n))}},al=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},iw=[t=>{},t=>null,ol,t=>al(t,4).getFloat32(0,!1),t=>al(t,8).getFloat64(0,!1),t=>al(t,8).getBigInt64(0,!1),t=>!1,t=>!0,Mi,t=>{const e=Ee(t),n={};for(let r=0;r{const e=Ee(t),n=[];for(let r=0;riw[127-Li(t)](t);class Ih extends Fo{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),nw(this)?this.count=Ee(this)+1:this.count=-1),this.count--,this.s}}class $o extends Fo{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=ol(this);const e=_h(this.s);this.count=1,e&&(this.s=-this.s,this.count=Ee(this)+2)}return this.count--,this.s}}class cl extends Fo{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=ol(this),n=e&1;this.diff=Lr(e/2),this.count=1,n&&(this.count=Ee(this)+2)}return this.s+=this.diff,this.count--,this.s}}class sw{constructor(e){this.decoder=new $o(e),this.str=Mi(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),n=this.str.slice(this.spos,e);return this.spos=e,n}}const ow=crypto.getRandomValues.bind(crypto),Oh=()=>ow(new Uint32Array(1))[0],aw="10000000-1000-4000-8000"+-1e11,cw=()=>aw.replace(/[018]/g,t=>(t^Oh()&15>>t/4).toString(16)),Nh=t=>new Promise(t);Promise.all.bind(Promise);const Ch=t=>t===void 0?null:t;class lw{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let Lh=new lw,uw=!0;try{typeof localStorage<"u"&&localStorage&&(Lh=localStorage,uw=!1)}catch{}const fw=Lh,hw=Object.assign,dw=Object.keys,pw=(t,e)=>{for(const n in t)e(t[n],n)},Mh=t=>dw(t).length,mw=t=>{for(const e in t)return!1;return!0},gw=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},yw=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),_w=(t,e)=>t===e||Mh(t)===Mh(e)&&gw(t,(n,r)=>(n!==void 0||yw(e,r))&&e[r]===n),bw=Object.freeze,Uh=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&Uh(t[e])}return bw(t)},ll=(t,e,n=0)=>{try{for(;nt,vw=(t,e)=>e.includes(t);var Ph={};const vs=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let Fn;const Ew=()=>{if(Fn===void 0)if(vs){Fn=Sn();const t=process.argv;let e=null;for(let n=0;n{if(t.length!==0){const[e,n]=t.split("=");Fn.set(`--${Eh(e,"-")}`,n),Fn.set(`-${Eh(e,"-")}`,n)}})):Fn=Sn();return Fn},ul=t=>Ew().has(t),jo=t=>Ch(vs?Ph[t.toUpperCase().replaceAll("-","_")]:fw.getItem(t)),Dh=t=>ul("--"+t)||jo(t)!==null;Dh("production");const kw=vs&&vw(Ph.FORCE_COLOR,["true","1","2"])||!ul("--no-colors")&&!Dh("no-color")&&(!vs||process.stdout.isTTY)&&(!vs||ul("--color")||jo("COLORTERM")!==null||(jo("TERM")||"").includes("color")),Sw=t=>new Uint8Array(t),Aw=t=>{const e=Sw(t.byteLength);return e.set(t),e};class Tw{constructor(e,n){this.left=e,this.right=n}}const cr=(t,e)=>new Tw(t,e);typeof DOMParser<"u"&&new DOMParser;const xw=t=>Lb(t,(e,n)=>`${n}:${e};`).join(""),lr=Symbol,Bh=lr(),Fh=lr(),Rw=lr(),Iw=lr(),Ow=lr(),$h=lr(),Nw=lr(),fl=lr(),Cw=lr(),Lw=t=>{var i;t.length===1&&((i=t[0])==null?void 0:i.constructor)===Function&&(t=t[0]());const e=[],n=[];let r=0;for(;r0&&n.push(e.join(""));r{var o;t.length===1&&((o=t[0])==null?void 0:o.constructor)===Function&&(t=t[0]());const e=[],n=[],r=Sn();let i=[],s=0;for(;s0||l.length>0?(e.push("%c"+a),n.push(l)):e.push(a)}else break}}for(s>0&&(i=n,i.unshift(e.join("")));s{console.log(...jh(t)),zh.forEach(e=>e.print(t))},Pw=(...t)=>{console.warn(...jh(t)),t.unshift(fl),zh.forEach(e=>e.print(t))},zh=Ni(),Wh=t=>({[Symbol.iterator](){return this},next:t}),Dw=(t,e)=>Wh(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),hl=(t,e)=>Wh(()=>{const{done:n,value:r}=t.next();return{done:n,value:n?void 0:e(r)}});class dl{constructor(e,n){this.clock=e,this.len=n}}class Es{constructor(){this.clients=new Map}}const Gh=(t,e,n)=>e.clients.forEach((r,i)=>{const s=t.doc.store.clients.get(i);for(let o=0;o{let n=0,r=t.length-1;for(;n<=r;){const i=Lr((n+r)/2),s=t[i],o=s.clock;if(o<=e){if(e{const n=t.clients.get(e.client);return n!==void 0&&Bw(n,e.clock)!==null},pl=t=>{t.clients.forEach(e=>{e.sort((i,s)=>i.clock-s.clock);let n,r;for(n=1,r=1;n=s.clock?i.len=ei(i.len,s.clock+s.len-i.clock):(r{const e=new Es;for(let n=0;n{if(!e.clients.has(i)){const s=r.slice();for(let o=n+1;o{Nr(t.clients,e,()=>[]).push(new dl(n,r))},$w=()=>new Es,jw=t=>{const e=$w();return t.clients.forEach((n,r)=>{const i=[];for(let s=0;s0&&e.clients.set(r,i)}),e},Ui=(t,e)=>{ve(t.restEncoder,e.clients.size),Cr(e.clients.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{t.resetDsCurVal(),ve(t.restEncoder,n);const i=r.length;ve(t.restEncoder,i);for(let s=0;s{const e=new Es,n=Ee(t.restDecoder);for(let r=0;r0){const o=Nr(e.clients,i,()=>[]);for(let a=0;a{const r=new Es,i=Ee(t.restDecoder);for(let s=0;s0){const s=new ri;return ve(s.restEncoder,0),Ui(s,r),s.toUint8Array()}return null},Kh=Oh;class ur extends Db{constructor({guid:e=cw(),collectionid:n=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:a=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=Kh(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new sd,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Nh(l=>{this.on("load",()=>{this.isLoaded=!0,l(this)})});const c=()=>Nh(l=>{const u=f=>{(f===void 0||f===!0)&&(this.off("sync",u),l())};this.on("sync",u)});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;e!==null&&!this.shouldLoad&&Ve(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Cr(this.subdocs).map(e=>e.guid))}transact(e,n=null){return Ve(this,e,n)}get(e,n=ot){const r=Nr(this.share,e,()=>{const s=new n;return s._integrate(this,null),s}),i=r.constructor;if(n!==ot&&i!==n)if(i===ot){const s=new n;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(e,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,$n)}getText(e=""){return this.get(e,xn)}getMap(e=""){return this.get(e,jn)}getXmlElement(e=""){return this.get(e,fr)}getXmlFragment(e=""){return this.get(e,zn)}toJSON(){const e={};return this.share.forEach((n,r)=>{e[r]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,Cr(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new ur({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,Ve(e.parent.doc,r=>{const i=n.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class qh{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Ee(this.restDecoder)}readDsLen(){return Ee(this.restDecoder)}}class Jh extends qh{readLeftID(){return Ne(Ee(this.restDecoder),Ee(this.restDecoder))}readRightID(){return Ne(Ee(this.restDecoder),Ee(this.restDecoder))}readClient(){return Ee(this.restDecoder)}readInfo(){return Li(this.restDecoder)}readString(){return Mi(this.restDecoder)}readParentInfo(){return Ee(this.restDecoder)===1}readTypeRef(){return Ee(this.restDecoder)}readLen(){return Ee(this.restDecoder)}readAny(){return ws(this.restDecoder)}readBuf(){return Aw(Dt(this.restDecoder))}readJSON(){return JSON.parse(Mi(this.restDecoder))}readKey(){return Mi(this.restDecoder)}}class zw{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Ee(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Ee(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Pi extends zw{constructor(e){super(e),this.keys=[],Ee(e),this.keyClockDecoder=new cl(Dt(e)),this.clientDecoder=new $o(Dt(e)),this.leftClockDecoder=new cl(Dt(e)),this.rightClockDecoder=new cl(Dt(e)),this.infoDecoder=new Ih(Dt(e),Li),this.stringDecoder=new sw(Dt(e)),this.parentInfoDecoder=new Ih(Dt(e),Li),this.typeRefDecoder=new $o(Dt(e)),this.lenDecoder=new $o(Dt(e))}readLeftID(){return new Di(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Di(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return ws(this.restDecoder)}readBuf(){return Dt(this.restDecoder)}readJSON(){return ws(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e{r=ei(r,e[0].id.clock);const i=Tn(e,r);ve(t.restEncoder,e.length-i),t.writeClient(n),ve(t.restEncoder,r);const s=e[i];s.write(t,r-s.id.clock);for(let o=i+1;o{const r=new Map;n.forEach((i,s)=>{At(e,s)>i&&r.set(s,i)}),Go(e).forEach((i,s)=>{n.has(s)||r.set(s,0)}),ve(t.restEncoder,r.size),Cr(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{Ww(t,e.clients.get(i),i,s)})},Gw=(t,e)=>{const n=Sn(),r=Ee(t.restDecoder);for(let i=0;i{const r=[];let i=Cr(n.keys()).sort((h,p)=>h-p);if(i.length===0)return null;const s=()=>{if(i.length===0)return null;let h=n.get(i[i.length-1]);for(;h.refs.length===h.i;)if(i.pop(),i.length>0)h=n.get(i[i.length-1]);else return null;return h};let o=s();if(o===null)return null;const a=new sd,c=new Map,l=(h,p)=>{const m=c.get(h);(m==null||m>p)&&c.set(h,p)};let u=o.refs[o.i++];const f=new Map,d=()=>{for(const h of r){const p=h.id.client,m=n.get(p);m?(m.i--,a.clients.set(p,m.refs.slice(m.i)),n.delete(p),m.i=0,m.refs=[]):a.clients.set(p,[h]),i=i.filter(b=>b!==p)}r.length=0};for(;;){if(u.constructor!==ln){const p=Nr(f,u.id.client,()=>At(e,u.id.client))-u.id.clock;if(p<0)r.push(u),l(u.id.client,u.id.clock-1),d();else{const m=u.getMissing(t,e);if(m!==null){r.push(u);const b=n.get(m)||{refs:[],i:0};if(b.refs.length===b.i)l(m,At(e,m)),d();else{u=b.refs[b.i++];continue}}else(p===0||p0)u=r.pop();else if(o!==null&&o.i0){const h=new ri;return gl(h,a,new Map),ve(h.restEncoder,0),{missing:c,update:h.toUint8Array()}}return null},Vw=(t,e)=>gl(t,e.doc.store,e.beforeState),Kw=(t,e,n,r=new Pi(t))=>Ve(e,i=>{i.local=!1;let s=!1;const o=i.doc,a=o.store,c=Gw(r,o),l=Hw(i,a,c),u=a.pendingStructs;if(u){for(const[d,h]of u.missing)if(hh)&&u.missing.set(d,h)}u.update=Vo([u.update,l.update])}}else a.pendingStructs=l;const f=Vh(r,i,a);if(a.pendingDs){const d=new Pi(ni(a.pendingDs));Ee(d.restDecoder);const h=Vh(d,i,a);f&&h?a.pendingDs=Vo([f,h]):a.pendingDs=f||h}else a.pendingDs=f;if(s){const d=a.pendingStructs.update;a.pendingStructs=null,Yh(i.doc,d)}},n,!1),Yh=(t,e,n,r=Pi)=>{const i=ni(e);Kw(i,t,n,new r(i))},qw=(t,e,n)=>Yh(t,e,n,Jh),Jw=(t,e,n=new Map)=>{gl(t,e.store,n),Ui(t,jw(e.store))},Xw=(t,e=new Uint8Array([0]),n=new ri)=>{const r=Qh(e);Jw(n,t,r);const i=[n.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(fv(t.store.pendingStructs.update,e)),i.length>1){if(n.constructor===ks)return lv(i.map((s,o)=>o===0?s:dv(s)));if(n.constructor===ri)return Vo(i)}return i[0]},Zw=(t,e)=>Xw(t,e,new ks),Yw=t=>{const e=new Map,n=Ee(t.restDecoder);for(let r=0;rYw(new qh(ni(t))),ed=(t,e)=>(ve(t.restEncoder,e.size),Cr(e.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{ve(t.restEncoder,n),ve(t.restEncoder,r)}),t),Qw=(t,e)=>ed(t,Go(e.store)),ev=(t,e=new Zh)=>(t instanceof Map?ed(e,t):Qw(e,t),e.toUint8Array()),tv=t=>ev(t,new Xh);class nv{constructor(){this.l=[]}}const td=()=>new nv,nd=(t,e)=>t.l.push(e),rd=(t,e)=>{const n=t.l,r=n.length;t.l=n.filter(i=>e!==i),r===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},id=(t,e,n)=>ll(t.l,[e,n]);class Di{constructor(e,n){this.client=e,this.clock=n}}const Wo=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,Ne=(t,e)=>new Di(t,e),rv=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw Bn()},Bi=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!Hh(e.ds,t.id),yl=(t,e)=>{const n=Nr(t.meta,yl,Ni),r=t.doc.store;n.has(e)||(e.sv.forEach((i,s)=>{i{}),n.add(e))};class sd{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Go=t=>{const e=new Map;return t.clients.forEach((n,r)=>{const i=n[n.length-1];e.set(r,i.id.clock+i.length)}),e},At=(t,e)=>{const n=t.clients.get(e);if(n===void 0)return 0;const r=n[n.length-1];return r.id.clock+r.length},od=(t,e)=>{let n=t.clients.get(e.id.client);if(n===void 0)n=[],t.clients.set(e.id.client,n);else{const r=n[n.length-1];if(r.id.clock+r.length!==e.id.clock)throw Bn()}n.push(e)},Tn=(t,e)=>{let n=0,r=t.length-1,i=t[r],s=i.id.clock;if(s===e)return r;let o=Lr(e/(s+i.length-1)*r);for(;n<=r;){if(i=t[o],s=i.id.clock,s<=e){if(e{const n=t.clients.get(e.client);return n[Tn(n,e.clock)]},bl=(t,e,n)=>{const r=Tn(e,n),i=e[r];return i.id.clock{const n=t.doc.store.clients.get(e.client);return n[bl(t,n,e.clock)]},ad=(t,e,n)=>{const r=e.clients.get(n.client),i=Tn(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==nn&&r.splice(i+1,0,ta(t,s,n.clock-s.id.clock+1)),s},iv=(t,e,n)=>{const r=t.clients.get(e.id.client);r[Tn(r,e.id.clock)]=n},cd=(t,e,n,r,i)=>{if(r===0)return;const s=n+r;let o=bl(t,e,n),a;do a=e[o++],se.deleteSet.clients.size===0&&!Mb(e.afterState,(n,r)=>e.beforeState.get(r)!==n)?!1:(pl(e.deleteSet),Vw(t,e),Ui(t,e.deleteSet),!0),ud=(t,e,n)=>{const r=e._item;(r===null||r.id.clock<(t.beforeState.get(r.id.client)||0)&&!r.deleted)&&Nr(t.changed,e,Ni).add(n)},Ho=(t,e)=>{let n=t[e],r=t[e-1],i=e;for(;i>0;n=r,r=t[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof bt&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}const s=e-i;return s&&t.splice(e+1-s,s),s},ov=(t,e,n)=>{for(const[r,i]of t.clients.entries()){const s=e.clients.get(r);for(let o=i.length-1;o>=0;o--){const a=i[o],c=a.clock+a.len;for(let l=Tn(s,a.clock),u=s[l];l{t.clients.forEach((n,r)=>{const i=e.clients.get(r);for(let s=n.length-1;s>=0;s--){const o=n[s],a=yh(i.length-1,1+Tn(i,o.clock+o.len-1));for(let c=a,l=i[c];c>0&&l.id.clock>=o.clock;l=i[c])c-=1+Ho(i,c)}})},fd=(t,e)=>{if(ea.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(n,c)})),a.push(()=>{n.changedParentTypes.forEach((c,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(c=c.filter(u=>u.target._item===null||!u.target._item.deleted),c.forEach(u=>{u.currentTarget=l,u._path=null}),c.sort((u,f)=>u.path.length-f.path.length),id(l._dEH,c,n))})}),a.push(()=>r.emit("afterTransaction",[n,r])),ll(a,[]),n._needFormattingCleanup&&xv(n)}finally{r.gc&&ov(s,i,r.gcFilter),av(s,i),n.afterState.forEach((u,f)=>{const d=n.beforeState.get(f)||0;if(d!==u){const h=i.clients.get(f),p=ei(Tn(h,d),1);for(let m=h.length-1;m>=p;)m-=1+Ho(h,m)}});for(let u=o.length-1;u>=0;u--){const{client:f,clock:d}=o[u].id,h=i.clients.get(f),p=Tn(h,d);p+11||p>0&&Ho(h,p)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(Uw(fl,Bh,"[yjs] ",Fh,$h,"Changed the client-id because another client seems to be using it."),r.clientID=Kh()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const u=new ks;ld(u,n)&&r.emit("update",[u.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const u=new ri;ld(u,n)&&r.emit("updateV2",[u.toUint8Array(),n.origin,r,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:l}=n;(a.size>0||l.size>0||c.size>0)&&(a.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),l.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:c,added:a,removed:l},r,n]),l.forEach(u=>u.destroy())),t.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,t])):fd(t,e+1)}}},Ve=(t,e,n=null,r=!0)=>{const i=t._transactionCleanups;let s=!1,o=null;t._transaction===null&&(s=!0,t._transaction=new sv(t,n,r),i.push(t._transaction),i.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{o=e(t._transaction)}finally{if(s){const a=t._transaction===i[0];t._transaction=null,a&&fd(i,0)}}return o};function*cv(t){const e=Ee(t.restDecoder);for(let n=0;nVo(t,Jh,ks),uv=(t,e)=>{if(t.constructor===nn){const{client:n,clock:r}=t.id;return new nn(Ne(n,r+e),t.length-e)}else if(t.constructor===ln){const{client:n,clock:r}=t.id;return new ln(Ne(n,r+e),t.length-e)}else{const n=t,{client:r,clock:i}=n.id;return new bt(Ne(r,i+e),null,Ne(r,i+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},Vo=(t,e=Pi,n=ri)=>{if(t.length===1)return t[0];const r=t.map(u=>new e(ni(u)));let i=r.map(u=>new wl(u,!0)),s=null;const o=new n,a=new vl(o);for(;i=i.filter(d=>d.curr!==null),i.sort((d,h)=>{if(d.curr.id.client===h.curr.id.client){const p=d.curr.id.clock-h.curr.id.clock;return p===0?d.curr.constructor===h.curr.constructor?0:d.curr.constructor===ln?1:-1:p}else return h.curr.id.client-d.curr.id.client}),i.length!==0;){const u=i[0],f=u.curr.id.client;if(s!==null){let d=u.curr,h=!1;for(;d!==null&&d.id.clock+d.length<=s.struct.id.clock+s.struct.length&&d.id.client>=s.struct.id.client;)d=u.next(),h=!0;if(d===null||d.id.client!==f||h&&d.id.clock>s.struct.id.clock+s.struct.length)continue;if(f!==s.struct.id.client)Dr(a,s.struct,s.offset),s={struct:d,offset:0},u.next();else if(s.struct.id.clock+s.struct.length0&&(s.struct.constructor===ln?s.struct.length-=p:d=uv(d,p)),s.struct.mergeWith(d)||(Dr(a,s.struct,s.offset),s={struct:d,offset:0},u.next())}}else s={struct:u.curr,offset:0},u.next();for(let d=u.curr;d!==null&&d.id.client===f&&d.id.clock===s.struct.id.clock+s.struct.length&&d.constructor!==ln;d=u.next())Dr(a,s.struct,s.offset),s={struct:d,offset:0}}s!==null&&(Dr(a,s.struct,s.offset),s=null),El(a);const c=r.map(u=>ml(u)),l=Fw(c);return Ui(o,l),o.toUint8Array()},fv=(t,e,n=Pi,r=ri)=>{const i=Qh(e),s=new r,o=new vl(s),a=new n(ni(t)),c=new wl(a,!1);for(;c.curr;){const u=c.curr,f=u.id.client,d=i.get(f)||0;if(c.curr.constructor===ln){c.next();continue}if(u.id.clock+u.length>d)for(Dr(o,u,ei(d-u.id.clock,0)),c.next();c.curr&&c.curr.id.client===f;)Dr(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===f&&c.curr.id.clock+c.curr.length<=d;)c.next()}El(o);const l=ml(a);return Ui(s,l),s.toUint8Array()},hd=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:An(t.encoder.restEncoder)}),t.encoder.restEncoder=Mr(),t.written=0)},Dr=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&hd(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),ve(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},El=t=>{hd(t);const e=t.encoder.restEncoder;ve(e,t.clientStructs.length);for(let n=0;n{const i=new n(ni(t)),s=new wl(i,!1),o=new r,a=new vl(o);for(let l=s.curr;l!==null;l=s.next())Dr(a,e(l),0);El(a);const c=ml(i);return Ui(o,c),o.toUint8Array()},dv=t=>hv(t,ww,Pi,ks),dd="You must not compute changes after the event-handler fired.";class Ko{constructor(e,n){this.target=e,this.currentTarget=e,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=pv(this.currentTarget,this.target))}deletes(e){return Hh(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ur(dd);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(i=>{if(i!==null){const s=n._map.get(i);let o,a;if(this.adds(s)){let c=s.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(s))if(c!==null&&this.deletes(c))o="delete",a=Zc(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",a=Zc(c.content.getContent())):(o="add",a=void 0)}else if(this.deletes(s))o="delete",a=Zc(s.content.getContent());else return;e.set(i,{action:o,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ur(dd);const n=this.target,r=Ni(),i=Ni(),s=[];if(e={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(n).has(null)){let a=null;const c=()=>{a&&s.push(a)};for(let l=n._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=l.length,i.add(l)):this.adds(l)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(l.content.getContent()),r.add(l)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=l.length);a!==null&&a.retain===void 0&&c()}this._changes=e}return e}}const pv=(t,e)=>{const n=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)n.unshift(e._item.parentSub);else{let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;n.unshift(r)}e=e._item.parent}return n},Ut=()=>{Pw("Invalid access: Add Yjs type to a document before reading data.")},pd=80;let kl=0;class mv{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=kl++}}const gv=t=>{t.timestamp=kl++},md=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=kl++},yv=(t,e,n)=>{if(t.length>=pd){const r=t.reduce((i,s)=>i.timestamp{if(t._start===null||e===0||t._searchMarker===null)return null;const n=t._searchMarker.length===0?null:t._searchMarker.reduce((s,o)=>Uo(e-s.index)e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&Uo(n.index-i){for(let r=t.length-1;r>=0;r--){const i=t[r];if(n>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){t.splice(r,1);continue}i.p=s,s.marker=!0}(e0&&e===i.index)&&(i.index=ei(e,i.index+n))}},Jo=(t,e,n)=>{const r=t,i=e.changedParentTypes;for(;Nr(i,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;id(r._eH,n,e)};class ot{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=td(),this._dEH=td(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw Dn()}clone(){throw Dn()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,n){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){nd(this._eH,e)}observeDeep(e){nd(this._dEH,e)}unobserve(e){rd(this._eH,e)}unobserveDeep(e){rd(this._dEH,e)}toJSON(){}}const gd=(t,e,n)=>{t.doc??Ut(),e<0&&(e=t._length+e),n<0&&(n=t._length+n);let r=n-e;const i=[];let s=t._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){const o=s.content.getContent();if(o.length<=e)e-=o.length;else{for(let a=e;a0;a++)i.push(o[a]),r--;e=0}}s=s.right}return i},yd=t=>{t.doc??Ut();const e=[];let n=t._start;for(;n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let i=0;i{let n=0,r=t._start;for(t.doc??Ut();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let s=0;s{const n=[];return As(t,(r,i)=>{n.push(e(r,i,t))}),n},_v=t=>{let e=t._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};n=e.content.getContent(),r=0,e=e.right}const i=n[r++];return n.length<=r&&(n=null),{done:!1,value:i}}}},bd=(t,e)=>{t.doc??Ut();const n=qo(t,e);let r=t._start;for(n!==null&&(r=n.p,e-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e{let i=n;const s=t.doc,o=s.clientID,a=s.store,c=n===null?e._start:n.right;let l=[];const u=()=>{l.length>0&&(i=new bt(Ne(o,At(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new oi(l)),i.integrate(t,0),l=[])};r.forEach(f=>{if(f===null)l.push(f);else switch(f.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(f);break;default:switch(u(),f.constructor){case Uint8Array:case ArrayBuffer:i=new bt(Ne(o,At(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new Ts(new Uint8Array(f))),i.integrate(t,0);break;case ur:i=new bt(Ne(o,At(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new Rs(f)),i.integrate(t,0);break;default:if(f instanceof ot)i=new bt(Ne(o,At(a,o)),i,i&&i.lastId,c,c&&c.id,e,null,new hr(f)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},wd=()=>Ur("Length exceeded!"),vd=(t,e,n,r)=>{if(n>e._length)throw wd();if(n===0)return e._searchMarker&&Ss(e._searchMarker,n,r.length),Xo(t,e,null,r);const i=n,s=qo(e,n);let o=e._start;for(s!==null&&(o=s.p,n-=s.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n{let i=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return Xo(t,e,i,n)},Ed=(t,e,n,r)=>{if(r===0)return;const i=n,s=r,o=qo(e,n);let a=e._start;for(o!==null&&(a=o.p,n-=o.index);a!==null&&n>0;a=a.right)!a.deleted&&a.countable&&(n0&&a!==null;)a.deleted||(r0)throw wd();e._searchMarker&&Ss(e._searchMarker,i,-s+r)},Zo=(t,e,n)=>{const r=e._map.get(n);r!==void 0&&r.delete(t)},Sl=(t,e,n,r)=>{const i=e._map.get(n)||null,s=t.doc,o=s.clientID;let a;if(r==null)a=new oi([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:a=new oi([r]);break;case Uint8Array:a=new Ts(r);break;case ur:a=new Rs(r);break;default:if(r instanceof ot)a=new hr(r);else throw new Error("Unexpected content type")}new bt(Ne(o,At(s.store,o)),i,i&&i.lastId,null,null,e,n,a).integrate(t,0)},Al=(t,e)=>{t.doc??Ut();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},kd=t=>{const e={};return t.doc??Ut(),t._map.forEach((n,r)=>{n.deleted||(e[r]=n.content.getContent()[n.length-1])}),e},Sd=(t,e)=>{t.doc??Ut();const n=t._map.get(e);return n!==void 0&&!n.deleted},wv=(t,e)=>{const n={};return t._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&Bi(s,e)&&(n[i]=s.content.getContent()[s.length-1])}),n},Yo=t=>(t.doc??Ut(),Dw(t._map.entries(),e=>!e[1].deleted));class vv extends Ko{}class $n extends ot{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new $n;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new $n}clone(){const e=new $n;return e.insert(0,this.toArray().map(n=>n instanceof ot?n.clone():n)),e}get length(){return this.doc??Ut(),this._length}_callObserver(e,n){super._callObserver(e,n),Jo(this,e,new vv(this,e))}insert(e,n){this.doc!==null?Ve(this.doc,r=>{vd(r,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?Ve(this.doc,n=>{bv(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?Ve(this.doc,r=>{Ed(r,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return bd(this,e)}toArray(){return yd(this)}slice(e=0,n=this.length){return gd(this,e,n)}toJSON(){return this.map(e=>e instanceof ot?e.toJSON():e)}map(e){return _d(this,e)}forEach(e){As(this,e)}[Symbol.iterator](){return _v(this)}_write(e){e.writeTypeRef(Vv)}}const Ev=t=>new $n;class kv extends Ko{constructor(e,n,r){super(e,n),this.keysChanged=r}}class jn extends ot{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,n){super._integrate(e,n),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new jn}clone(){const e=new jn;return this.forEach((n,r)=>{e.set(r,n instanceof ot?n.clone():n)}),e}_callObserver(e,n){Jo(this,e,new kv(this,e,n))}toJSON(){this.doc??Ut();const e={};return this._map.forEach((n,r)=>{if(!n.deleted){const i=n.content.getContent()[n.length-1];e[r]=i instanceof ot?i.toJSON():i}}),e}get size(){return[...Yo(this)].length}keys(){return hl(Yo(this),e=>e[0])}values(){return hl(Yo(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return hl(Yo(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Ut(),this._map.forEach((n,r)=>{n.deleted||e(n.content.getContent()[n.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?Ve(this.doc,n=>{Zo(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?Ve(this.doc,r=>{Sl(r,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return Al(this,e)}has(e){return Sd(this,e)}clear(){this.doc!==null?Ve(this.doc,e=>{this.forEach(function(n,r,i){Zo(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Kv)}}const Sv=t=>new jn,Br=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&_w(t,e);class Tl{constructor(e,n,r,i){this.left=e,this.right=n,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Bn(),this.right.content.constructor){case _t:this.right.deleted||Fi(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const Ad=(t,e,n)=>{for(;e.right!==null&&n>0;){switch(e.right.content.constructor){case _t:e.right.deleted||Fi(e.currentAttributes,e.right.content);break;default:e.right.deleted||(n{const i=new Map,s=r?qo(e,n):null;if(s){const o=new Tl(s.p.left,s.p,s.index,i);return Ad(t,o,n-s.index)}else{const o=new Tl(null,e._start,0,i);return Ad(t,o,n)}},Td=(t,e,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===_t&&Br(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=t.doc,s=i.clientID;r.forEach((o,a)=>{const c=n.left,l=n.right,u=new bt(Ne(s,At(i.store,s)),c,c&&c.lastId,l,l&&l.id,e,null,new _t(a,o));u.integrate(t,0),n.right=u,n.forward()})},Fi=(t,e)=>{const{key:n,value:r}=e;r===null?t.delete(n):t.set(n,r)},xd=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===_t&&Br(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},Rd=(t,e,n,r)=>{const i=t.doc,s=i.clientID,o=new Map;for(const a in r){const c=r[a],l=n.currentAttributes.get(a)??null;if(!Br(l,c)){o.set(a,l);const{left:u,right:f}=n;n.right=new bt(Ne(s,At(i.store,s)),u,u&&u.lastId,f,f&&f.id,e,null,new _t(a,c)),n.right.integrate(t,0),n.forward()}}return o},xl=(t,e,n,r,i)=>{n.currentAttributes.forEach((d,h)=>{i[h]===void 0&&(i[h]=null)});const s=t.doc,o=s.clientID;xd(n,i);const a=Rd(t,e,n,i),c=r.constructor===String?new Wn(r):r instanceof ot?new hr(r):new si(r);let{left:l,right:u,index:f}=n;e._searchMarker&&Ss(e._searchMarker,n.index,c.getLength()),u=new bt(Ne(o,At(s.store,o)),l,l&&l.lastId,u,u&&u.id,e,null,c),u.integrate(t,0),n.right=u,n.index=f,n.forward(),Td(t,e,n,a)},Id=(t,e,n,r,i)=>{const s=t.doc,o=s.clientID;xd(n,i);const a=Rd(t,e,n,i);e:for(;n.right!==null&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===_t));){if(!n.right.deleted)switch(n.right.content.constructor){case _t:{const{key:c,value:l}=n.right.content,u=i[c];if(u!==void 0){if(Br(u,l))a.delete(c);else{if(r===0)break e;a.set(c,l)}n.right.delete(t)}else n.currentAttributes.set(c,l);break}default:r0){let c="";for(;r>0;r--)c+=` +`;n.right=new bt(Ne(o,At(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Wn(c)),n.right.integrate(t,0),n.forward()}Td(t,e,n,a)},Od=(t,e,n,r,i)=>{let s=e;const o=Sn();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===_t){const l=s.content;o.set(l.key,l)}s=s.right}let a=0,c=!1;for(;e!==s;){if(n===e&&(c=!0),!e.deleted){const l=e.content;switch(l.constructor){case _t:{const{key:u,value:f}=l,d=r.get(u)??null;(o.get(u)!==l||d===f)&&(e.delete(t),a++,!c&&(i.get(u)??null)===f&&d!==f&&(d===null?i.delete(u):i.set(u,d))),!c&&!e.deleted&&Fi(i,l);break}}}e=e.right}return a},Av=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const n=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===_t){const r=e.content.key;n.has(r)?e.delete(t):n.add(r)}e=e.left}},Tv=t=>{let e=0;return Ve(t.doc,n=>{let r=t._start,i=t._start,s=Sn();const o=Xc(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case _t:Fi(o,i.content);break;default:e+=Od(n,r,i,s,o),s=Xc(o),r=i;break}i=i.right}}),e},xv=t=>{const e=new Set,n=t.doc;for(const[r,i]of t.afterState.entries()){const s=t.beforeState.get(r)||0;i!==s&&cd(t,n.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===_t&&o.constructor!==nn&&e.add(o.parent)})}Ve(n,r=>{Gh(t,t.deleteSet,i=>{if(i instanceof nn||!i.parent._hasFormatting||e.has(i.parent))return;const s=i.parent;i.content.constructor===_t?e.add(s):Av(r,i)});for(const i of e)Tv(i)})},Nd=(t,e,n)=>{const r=n,i=Xc(e.currentAttributes),s=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case hr:case si:case Wn:n{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,n=[];Ve(e,r=>{const i=new Map,s=new Map;let o=this.target._start,a=null;const c={};let l="",u=0,f=0;const d=()=>{if(a!==null){let h=null;switch(a){case"delete":f>0&&(h={delete:f}),f=0;break;case"insert":(typeof l=="object"||l.length>0)&&(h={insert:l},i.size>0&&(h.attributes={},i.forEach((p,m)=>{p!==null&&(h.attributes[m]=p)}))),l="";break;case"retain":u>0&&(h={retain:u},mw(c)||(h.attributes=hw({},c))),u=0;break}h&&n.push(h),a=null}};for(;o!==null;){switch(o.content.constructor){case hr:case si:this.adds(o)?this.deletes(o)||(d(),a="insert",l=o.content.getContent()[0],d()):this.deletes(o)?(a!=="delete"&&(d(),a="delete"),f+=1):o.deleted||(a!=="retain"&&(d(),a="retain"),u+=1);break;case Wn:this.adds(o)?this.deletes(o)||(a!=="insert"&&(d(),a="insert"),l+=o.content.str):this.deletes(o)?(a!=="delete"&&(d(),a="delete"),f+=o.length):o.deleted||(a!=="retain"&&(d(),a="retain"),u+=o.length);break;case _t:{const{key:h,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){const m=i.get(h)??null;Br(m,p)?p!==null&&o.delete(r):(a==="retain"&&d(),Br(p,s.get(h)??null)?delete c[h]:c[h]=p)}}else if(this.deletes(o)){s.set(h,p);const m=i.get(h)??null;Br(m,p)||(a==="retain"&&d(),c[h]=m)}else if(!o.deleted){s.set(h,p);const m=c[h];m!==void 0&&(Br(m,p)?m!==null&&o.delete(r):(a==="retain"&&d(),p===null?delete c[h]:c[h]=p))}o.deleted||(a==="insert"&&d(),Fi(i,o.content));break}}o=o.right}for(d();n.length>0;){const h=n[n.length-1];if(h.retain!==void 0&&h.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class xn extends ot{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ut(),this._length}_integrate(e,n){super._integrate(e,n);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new xn}clone(){const e=new xn;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const r=new Rv(this,e,n);Jo(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ut();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Wn&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?Ve(this.doc,r=>{const i=new Tl(null,this._start,0,new Map);for(let s=0;s0)&&xl(r,this,i,a,o.attributes||{})}else o.retain!==void 0?Id(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&Nd(r,i,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,r){this.doc??Ut();const i=[],s=new Map,o=this.doc;let a="",c=this._start;function l(){if(a.length>0){const f={};let d=!1;s.forEach((p,m)=>{d=!0,f[m]=p});const h={insert:a};d&&(h.attributes=f),i.push(h),a=""}}const u=()=>{for(;c!==null;){if(Bi(c,e)||n!==void 0&&Bi(c,n))switch(c.content.constructor){case Wn:{const f=s.get("ychange");e!==void 0&&!Bi(c,e)?(f===void 0||f.user!==c.id.client||f.type!=="removed")&&(l(),s.set("ychange",r?r("removed",c.id):{type:"removed"})):n!==void 0&&!Bi(c,n)?(f===void 0||f.user!==c.id.client||f.type!=="added")&&(l(),s.set("ychange",r?r("added",c.id):{type:"added"})):f!==void 0&&(l(),s.delete("ychange")),a+=c.content.str;break}case hr:case si:{l();const f={insert:c.content.getContent()[0]};if(s.size>0){const d={};f.attributes=d,s.forEach((h,p)=>{d[p]=h})}i.push(f);break}case _t:Bi(c,e)&&(l(),Fi(s,c.content));break}c=c.right}l()};return e||n?Ve(o,f=>{e&&yl(f,e),n&&yl(f,n),u()},"cleanup"):u(),i}insert(e,n,r){if(n.length<=0)return;const i=this.doc;i!==null?Ve(i,s=>{const o=Qo(s,this,e,!r);r||(r={},o.currentAttributes.forEach((a,c)=>{r[c]=a})),xl(s,this,o,n,r)}):this._pending.push(()=>this.insert(e,n,r))}insertEmbed(e,n,r){const i=this.doc;i!==null?Ve(i,s=>{const o=Qo(s,this,e,!r);xl(s,this,o,n,r||{})}):this._pending.push(()=>this.insertEmbed(e,n,r||{}))}delete(e,n){if(n===0)return;const r=this.doc;r!==null?Ve(r,i=>{Nd(i,Qo(i,this,e,!0),n)}):this._pending.push(()=>this.delete(e,n))}format(e,n,r){if(n===0)return;const i=this.doc;i!==null?Ve(i,s=>{const o=Qo(s,this,e,!1);o.right!==null&&Id(s,this,o,n,r)}):this._pending.push(()=>this.format(e,n,r))}removeAttribute(e){this.doc!==null?Ve(this.doc,n=>{Zo(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?Ve(this.doc,r=>{Sl(r,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return Al(this,e)}getAttributes(){return kd(this)}_write(e){e.writeTypeRef(qv)}}const Iv=t=>new xn;class Rl{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ut()}[Symbol.iterator](){return this}next(){let e=this._currentNode,n=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(n)))do if(n=e.content.type,!e.deleted&&(n.constructor===fr||n.constructor===zn)&&n._start!==null)e=n._start;else for(;e!==null;)if(e.right!==null){e=e.right;break}else e.parent===this._root?e=null:e=e.parent._item;while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class zn extends ot{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new zn}clone(){const e=new zn;return e.insert(0,this.toArray().map(n=>n instanceof ot?n.clone():n)),e}get length(){return this.doc??Ut(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Rl(this,e)}querySelector(e){e=e.toUpperCase();const r=new Rl(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),Cr(new Rl(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){Jo(this,e,new Cv(this,n,e))}toString(){return _d(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,n={},r){const i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),As(this,s=>{i.insertBefore(s.toDOM(e,n,r),null)}),i}insert(e,n){this.doc!==null?Ve(this.doc,r=>{vd(r,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)Ve(this.doc,r=>{const i=e&&e instanceof ot?e._item:e;Xo(r,this,i,n)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(s=>s===e)+1;if(i===0&&e!==null)throw Ur("Reference item not found");r.splice(i,0,...n)}}delete(e,n=1){this.doc!==null?Ve(this.doc,r=>{Ed(r,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return yd(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return bd(this,e)}slice(e=0,n=this.length){return gd(this,e,n)}forEach(e){As(this,e)}_write(e){e.writeTypeRef(Xv)}}const Ov=t=>new zn;class fr extends zn{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,n){super._integrate(e,n),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new fr(this.nodeName)}clone(){const e=new fr(this.nodeName),n=this.getAttributes();return pw(n,(r,i)=>{typeof r=="string"&&e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof ot?r.clone():r)),e}toString(){const e=this.getAttributes(),n=[],r=[];for(const a in e)r.push(a);r.sort();const i=r.length;for(let a=0;a0?" "+n.join(" "):"";return`<${s}${o}>${super.toString()}`}removeAttribute(e){this.doc!==null?Ve(this.doc,n=>{Zo(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?Ve(this.doc,r=>{Sl(r,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return Al(this,e)}hasAttribute(e){return Sd(this,e)}getAttributes(e){return e?wv(this,e):kd(this)}toDOM(e=document,n={},r){const i=e.createElement(this.nodeName),s=this.getAttributes();for(const o in s){const a=s[o];typeof a=="string"&&i.setAttribute(o,a)}return As(this,o=>{i.appendChild(o.toDOM(e,n,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(Jv),e.writeKey(this.nodeName)}}const Nv=t=>new fr(t.readKey());class Cv extends Ko{constructor(e,n,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class $i extends jn{constructor(e){super(),this.hookName=e}_copy(){return new $i(this.hookName)}clone(){const e=new $i(this.hookName);return this.forEach((n,r)=>{e.set(r,n)}),e}toDOM(e=document,n={},r){const i=n[this.hookName];let s;return i!==void 0?s=i.createDom(this):s=document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(s,this),s}_write(e){e.writeTypeRef(Zv),e.writeKey(this.hookName)}}const Lv=t=>new $i(t.readKey());class ii extends xn{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new ii}clone(){const e=new ii;return e.applyDelta(this.toDelta()),e}toDOM(e=document,n,r){const i=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const n=[];for(const i in e.attributes){const s=[];for(const o in e.attributes[i])s.push({key:o,value:e.attributes[i][o]});s.sort((o,a)=>o.keyi.nodeName=0;i--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Yv)}}const Mv=t=>new ii;class Il{constructor(e,n){this.id=e,this.length=n}get deleted(){throw Dn()}mergeWith(e){return!1}write(e,n,r){throw Dn()}integrate(e,n){throw Dn()}}const Uv=0;class nn extends Il{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){n>0&&(this.id.clock+=n,this.length-=n),od(e.doc.store,this)}write(e,n){e.writeInfo(Uv),e.writeLen(this.length-n)}getMissing(e,n){return null}}class Ts{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ts(this.content)}splice(e){throw Dn()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const Pv=t=>new Ts(t.readBuf());class xs{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new xs(this.len)}splice(e){const n=new xs(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){zo(e.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(e){}gc(e){}write(e,n){e.writeLen(this.len-n)}getRef(){return 1}}const Dv=t=>new xs(t.readLen()),Cd=(t,e)=>new ur({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Rs{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const n={};this.opts=n,e.gc||(n.gc=!1),e.autoLoad&&(n.autoLoad=!0),e.meta!==null&&(n.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Rs(Cd(this.doc.guid,this.opts))}splice(e){throw Dn()}mergeWith(e){return!1}integrate(e,n){this.doc._item=n,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,n){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const Bv=t=>new Rs(Cd(t.readString(),t.readAny()));class si{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new si(this.embed)}splice(e){throw Dn()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const Fv=t=>new si(t.readJSON());class _t{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new _t(this.key,this.value)}splice(e){throw Dn()}mergeWith(e){return!1}integrate(e,n){const r=n.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,n){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const $v=t=>new _t(t.readKey(),t.readJSON());class ea{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new ea(this.arr)}splice(e){const n=new ea(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const r=this.arr.length;e.writeLen(r-n);for(let i=n;i{const e=t.readLen(),n=[];for(let r=0;r{const e=t.readLen(),n=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const Gv=t=>new Wn(t.readString()),Hv=[Ev,Sv,Iv,Nv,Ov,Lv,Mv],Vv=0,Kv=1,qv=2,Jv=3,Xv=4,Zv=5,Yv=6;class hr{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new hr(this.type._copy())}splice(e){throw Dn()}mergeWith(e){return!1}integrate(e,n){this.type._integrate(e.doc,n)}delete(e){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.delete(e),n=n.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let n=this.type._start;for(;n!==null;)n.gc(e,!0),n=n.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,n){this.type._write(e)}getRef(){return 7}}const Qv=t=>new hr(Hv[t.readTypeRef()](t)),ta=(t,e,n)=>{const{client:r,clock:i}=e.id,s=new bt(Ne(r,i+n),e,Ne(r,i+n-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(n));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=Ne(e.redone.client,e.redone.clock+n)),e.right=s,s.right!==null&&(s.right.left=s),t._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=n,s};class bt extends Il{constructor(e,n,r,i,s,o,a,c){super(e,c.getLength()),this.origin=r,this.left=n,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?wh:0}set marker(e){(this.info&Qc)>0!==e&&(this.info^=Qc)}get marker(){return(this.info&Qc)>0}get keep(){return(this.info&bh)>0}set keep(e){this.keep!==e&&(this.info^=bh)}get countable(){return(this.info&wh)>0}get deleted(){return(this.info&Yc)>0}set deleted(e){this.deleted!==e&&(this.info^=Yc)}markDeleted(){this.info|=Yc}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=At(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=At(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Di&&this.id.client!==this.parent.client&&this.parent.clock>=At(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=ad(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Pr(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===nn||this.right&&this.right.constructor===nn)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===bt&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===bt&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Di){const r=_l(n,this.parent);r.constructor===nn?this.parent=null:this.parent=r.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=ad(e,e.doc.store,Ne(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),Wo(this.origin,i.origin)){if(i.id.client{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),zo(e.deleteSet,this.id.client,this.id.clock,this.length),ud(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw Bn();this.content.gc(e),n?iv(e,this,new nn(this.id,this.length)):this.content=new xs(this.length)}write(e,n){const r=n>0?Ne(this.id.client,this.id.clock+n-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&Po|(r===null?0:tn)|(i===null?0:ar)|(s===null?0:ms);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const a=this.parent;if(a._item!==void 0){const c=a._item;if(c===null){const l=rv(a);e.writeParentInfo(!0),e.writeString(l)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else a.constructor===String?(e.writeParentInfo(!0),e.writeString(a)):a.constructor===Di?(e.writeParentInfo(!1),e.writeLeftID(a)):Bn();s!==null&&e.writeString(s)}this.content.write(e,n)}}const Ld=(t,e)=>eE[e&Po](t),eE=[()=>{Bn()},Dv,jv,Pv,Gv,Fv,$v,Qv,Wv,Bv,()=>{Bn()}],tE=10;class ln extends Il{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){Bn()}write(e,n){e.writeInfo(tE),ve(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const Md=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Ud="__ $YJS$ __";Md[Ud]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438"),Md[Ud]=!0;let Ol,Nl,nE=t=>t();function rE(t,e){if(Nl)return Nl(t,e);nE(t)}function ai(t,e,n){if(Ol)return Ol.apply(null,arguments);throw new Error("observable implementation not provided. Call enableReactiveBindings, enableVueBindings or enableMobxBindings.")}function iE(t){Ol=function(e,n,r){const i=t.createAtom(e);return n&&n(),i},Nl=(e,n)=>t.reaction(e,n,{fireImmediately:!1})}const Pd=new WeakSet;function sE(t){if(Pd.has(t))return t;Pd.add(t);let e;const n=new Map;function r(){if(!e){const f=d=>{(d.changes.added.size||d.changes.deleted.size||d.changes.keys.size||d.changes.delta.length)&&e.reportChanged()};e=ai("map",()=>{t.observe(f)},()=>{t.unobserve(f)})}e.reportObserved(t._implicitObserver)}function i(f){let d=n.get(f);if(!d){const h=p=>{d.reportChanged()};d=ai(f+"",()=>{t.observe(h)},()=>{t.unobserve(h)}),n.set(f,d)}d.reportObserved(t._implicitObserver)}const s=t.get;t.get=function(f){if(typeof f!="number")throw new Error("unexpected");return i(f),Reflect.apply(s,this,arguments)};function o(f){const d=t[f];t[f]=function(){return r(),Reflect.apply(d,this,arguments)}}function a(f){let d=t,h=Object.getOwnPropertyDescriptor(d,f);if(h||(d=Object.getPrototypeOf(d),h=Object.getOwnPropertyDescriptor(d,f)),h||(d=Object.getPrototypeOf(d),h=Object.getOwnPropertyDescriptor(d,f)),!h)throw new Error("property not found");const p=h.get;h.get=function(){return this._disableTracking||r(),Reflect.apply(p,this,arguments)},Object.defineProperty(t,f,h)}function c(f,d){let h=t,p=Object.getOwnPropertyDescriptor(h,f);if(p||(h=Object.getPrototypeOf(h),p=Object.getOwnPropertyDescriptor(h,f)),p||(h=Object.getPrototypeOf(h),p=Object.getOwnPropertyDescriptor(h,f)),!p)throw new Error("property not found");Object.defineProperty(t,d,p)}o("forEach"),o("toJSON"),o("toArray"),o("slice"),o("map"),c("length","lengthUntracked"),a("length");const l=t.push;t.push=function(f){this._disableTracking=!0;const d=l.call(this,f);return this._disableTracking=!1,d};const u=t.slice;return t.slice=function(f,d){this._disableTracking=!0;const h=u.call(this,f,d);return this._disableTracking=!1,h},t}const Dd=new WeakSet;function oE(t){if(Dd.has(t))return t;Dd.add(t);let e;function n(){if(!e){let s=Array.from(t.share.keys());const o=a=>{const c=Array.from(t.share.keys());JSON.stringify(s)!==JSON.stringify(c)&&(s=c,e.reportChanged())};e=ai("map",()=>{t.on("beforeObserverCalls",o)},()=>{t.off("beforeObserverCalls",o)})}e.reportObserved(t._implicitObserver)}const r=t.get;t.get=function(s){if(typeof s!="string")throw new Error("unexpected");const o=Reflect.apply(r,this,arguments);return na(o),o};function i(s){const o=t[s];let a;t[s]=function(){let c,l=arguments;return n(),a&&a.removeObservers(),a=rE(()=>(c=Reflect.apply(o,t,l),c),()=>e.reportChanged()),c}}return i("toJSON"),Object.defineProperty(t,"keys",{get:()=>(n(),Object.keys(t.share))}),t}const Bd=new WeakSet;function aE(t){if(Bd.has(t))return t;Bd.add(t);let e;const n=new Map;function r(){if(!e){const a=c=>{(c.changes.added.size||c.changes.deleted.size||c.changes.keys.size||c.changes.delta.length)&&e.reportChanged()};e=ai("map",()=>{t.observe(a)},()=>{t.unobserve(a)})}e.reportObserved(t._implicitObserver)}function i(a){let c=n.get(a);if(!c){const l=u=>{u.keysChanged.has(a)&&(u.changes.added.size||u.changes.deleted.size||u.changes.keys.size||u.changes.delta.length)&&c.reportChanged()};c=ai(a,()=>{t.observe(l)},()=>{t.unobserve(l)}),n.set(a,c)}c.reportObserved(t._implicitObserver)}const s=t.get;t.get=function(a){if(typeof a!="string")throw new Error("unexpected");return i(a),Reflect.apply(s,this,arguments)};function o(a){const c=t[a];t[a]=function(){return r(),Reflect.apply(c,this,arguments)}}return o("values"),o("entries"),o("keys"),o("forEach"),o("toJSON"),t}const Fd=new WeakSet;function $d(t){if(Fd.has(t))return t;Fd.add(t);let e;const n=i=>{e.reportChanged()};e=ai("text",()=>{t.observe(n)},()=>{t.unobserve(n)});function r(i){const s=t[i];t[i]=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(s,this,arguments)}}return r("toString"),r("toJSON"),t}const jd=new WeakSet;function zd(t){if(jd.has(t))return t;jd.add(t);let e;const n=s=>{(s.changes.added.size||s.changes.deleted.size||s.changes.keys.size||s.changes.delta.length)&&e.reportChanged()};e=ai("xml",()=>{t.observe(n)},()=>{t.unobserve(n)});function r(s){const o=t[s];t[s]=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(o,this,arguments)}}function i(s){let o=t,a=Object.getOwnPropertyDescriptor(o,s);if(a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),a||(o=Object.getPrototypeOf(o),a=Object.getOwnPropertyDescriptor(o,s)),!a)throw new Error("property not found");const c=a.get;a.get=function(){return e.reportObserved(this._implicitObserver),Reflect.apply(c,this,arguments)},Object.defineProperty(t,s,a)}return r("toString"),r("toDOM"),r("toArray"),r("getAttribute"),i("firstChild"),t}function na(t){return t instanceof ii||t instanceof xn?$d(t):t instanceof $n?sE(t):t instanceof jn?aE(t):t instanceof ur||Object.prototype.hasOwnProperty.call(t,"autoLoad")?oE(t):t instanceof zn||t instanceof fr?zd(t):t}function Wd(t){t.share.forEach(e=>{e.constructor!==ot&&na(e)})}function Gd(t,e){for(let r=t.length-1;r>=e;r--){let i=t[r];if(!i.deleted){var n;if(i instanceof nn)continue;(n=i.content)==null||n.getContent().forEach(s=>{s instanceof ot&&na(s)})}}}const Hd=new WeakSet;function cE(t){Hd.has(t)||(Hd.add(t),na(t),t.store.clients.forEach(e=>{e&&Gd(e,0)}),Wd(t),t.on("beforeObserverCalls",e=>{Wd(t),e.afterState.forEach((n,r)=>{const i=e.beforeState.get(r)||0;if(i!==n){const s=e.doc.store.clients.get(r);if(!s)return;const o=Tn(s,i);Gd(s,o)}})}))}class Is{constructor(e){this.value=void 0,this.value=e}}function lE(t){return ArrayBuffer.isView(t)?new Is(t):new Is(Object.freeze(t))}function uE(t){const e=function(){var a;let c=(a=this[cn])==null?void 0:a.implicitObserver;return t._implicitObserver=c,t.slice.bind(t).apply(t,arguments).map(u=>{const f=ra(u,c);return c&&typeof f=="object"?ps(f,c):f})},n=function(a){return a.map(c=>{const l=Cl(c);let u=ci(l)||l;if(u instanceof Is&&(u=u.value),u instanceof ot&&u.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return u})},r=function(){return[].findIndex.apply(e.apply(this),arguments)},i={slice:e,unshift:(...o)=>(t.unshift(n(o)),t.lengthUntracked),push:(...o)=>(t.push(n(o)),t.lengthUntracked),insert:t.insert.bind(t),toJSON:t.toJSON.bind(t),forEach:function(){return[].forEach.apply(e.apply(this),arguments)},every:function(){return[].every.apply(e.apply(this),arguments)},filter:function(){return[].filter.apply(e.apply(this),arguments)},find:function(){return[].find.apply(e.apply(this),arguments)},findIndex:r,some:function(){return[].some.apply(e.apply(this),arguments)},includes:function(){return[].includes.apply(e.apply(this),arguments)},map:function(){return[].map.apply(e.apply(this),arguments)},indexOf:function(){const o=arguments[0];return r.call(this,a=>mE(a,o))},splice:function(){let o=arguments[0]<0?t.length-Math.abs(arguments[0]):arguments[0],a=arguments[1],c=Array.from(Array.from(arguments).slice(2)),l=e.apply(this,[o,Number.isInteger(a)?o+a:void 0]);return t.doc?t.doc.transact(()=>{t.delete(o,a),t.insert(o,n(c))}):(t.delete(o,a),t.insert(o,n(c))),l}},s=[];for(let o in i)s[o]=i[o];return s}function Os(t){if(typeof t=="string"&&t.trim().length){const e=Number(t);if(Number.isInteger(e))return e}return t}function Vd(t,e=new $n){if(e[yt])throw new Error("unexpected");const n=uE(e),r=new Proxy(n,{set:(i,s,o)=>{throw typeof Os(s)!="number"?new Error:new Error("array assignment is not implemented / supported")},get:(i,s,o)=>{const a=Os(s);if(a===ia)return e;if(typeof a=="number"){let u;if(o&&o[cn]){var c;u=(c=o[cn])==null?void 0:c.implicitObserver,e._implicitObserver=u}let f=e.get(a);return f=ra(f,u),f}if(a===Symbol.toStringTag)return"Array";if(a===Symbol.iterator){const u=e.slice();return Reflect.get(u,a)}return a==="length"?e.length:Reflect.get(i,a,o)},deleteProperty:(i,s)=>{const o=Os(s);if(typeof o!="number")throw new Error;return o=0?(e.delete(o),!0):!1},has:(i,s)=>{const o=Os(s);return typeof o!="number"?Reflect.has(i,o):o=0},getOwnPropertyDescriptor(i,s){const o=Os(s);if(o==="length")return{enumerable:!1,configurable:!1,writable:!0};if(typeof o=="number"&&o>=0&&o{const s=[];for(let o=0;o{if(typeof i!="string")throw new Error;const o=Cl(s);let a=ci(o)||o;if(a instanceof Is&&(a=a.value),a instanceof ot&&a.parent)throw new Error("Not supported: reassigning object that already occurs in the tree.");return e.set(i,a),!0},get:(r,i,s)=>{if(i===ia)return e;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[cn]){var a;o=(a=s[cn])==null?void 0:a.implicitObserver,e._implicitObserver=o}let c=e.get(i);return c=ra(c,o),c},deleteProperty:(r,i)=>{if(typeof i!="string")throw new Error;return e.has(i)?(e.delete(i),!0):!1},has:(r,i)=>!!(typeof i=="string"&&e.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&e.has(i))return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(e.keys())});Ns.set(e,n);for(let r in t)n[r]=t[r];return n}function fE(t){return t instanceof ot}const Ns=new WeakMap;function ra(t,e){if(fE(t)){if(t._implicitObserver=e,t instanceof $n||t instanceof jn){if(!Ns.has(t)){const n=Cl(t);Ns.set(t,n)}t=Ns.get(t)}else if(t instanceof fr||t instanceof zn||t instanceof ii||t instanceof $i||t instanceof xn)qc(t),t.__v_skip=!0;else throw new Error("unknown YType");return t}else{if(t===null)return null;if(typeof t=="object")return lE(t)}return t}function Cl(t){if(t==null)return t;if(t=ci(t)||t,t instanceof $n)return Vd([],t);if(t instanceof jn)return Kd({},t);if(typeof t=="string")return t;if(Array.isArray(t))return Vd(t);if(t instanceof fr||t instanceof zn||t instanceof ii||t instanceof $i)return t;if(t instanceof xn)return t;if(typeof t=="object")return t instanceof Is?t:Kd(t);if(typeof t=="number"||typeof t=="boolean")return t;throw new Error("invalid")}function hE(t){for(let[e,n]of Object.entries(t))if(Array.isArray(n)){if(n.length!==0)throw new Error("Root Array initializer must always be empty array")}else if(n&&typeof n=="object"){if(Object.keys(n).length!==0||Object.getPrototypeOf(n)!==Object.prototype)throw new Error("Root Object initializer must always be {}")}else if(n!=="xml"&&n!=="text")throw new Error("unknown Root initializer")}function qd(t,e,n){let r=e[n];if(!r){n!=="__v_raw"&&n!=="__v_isRef"&&n!=="__v_isReadonly"&&console.warn("property not found on root doc",n);return}return r==="xml"?t.getXmlFragment(n):r==="text"?t.getText(n):Array.isArray(r)?t.getArray(n):t.getMap(n)}function dE(t,e){if(t[yt])throw new Error("unexpected");hE(e);const n=new Proxy({},{set:(r,i,s)=>{throw typeof i!="string"?new Error:new Error("cannot set new elements on root doc")},get:(r,i,s)=>{if(i===ia)return t;if(typeof i!="string")return Reflect.get(r,i);let o;if(s&&s[cn]){var a;o=(a=s[cn])==null?void 0:a.implicitObserver,t._implicitObserver=o}if(i==="toJSON"){for(let u of Object.keys(e))qd(t,e,u);return Reflect.get(t,i)}let c=qd(t,e,i);return c=ra(c,o),c},deleteProperty:(r,i)=>{throw new Error("deleteProperty not available for doc")},has:(r,i)=>!!(typeof i=="string"&&t.share.has(i)),getOwnPropertyDescriptor(r,i){if(typeof i=="string"&&t.share.has(i)||i==="toJSON")return{enumerable:!0,configurable:!0}},ownKeys:r=>Array.from(t.share.keys())});return Ns.set(t,n),n}iE(Cb);const ia=Symbol("INTERNAL_SYMBOL");function Jd(t,e){const n=ci(t)||t;if(!n)throw new Error("not a valid synced object");return n instanceof ur?(n.on("update",e),()=>{n.off("update",e)}):(n.observeDeep(e),()=>{n.unobserveDeep(e)})}function pE(t){const e=ci(t);if(!(e instanceof ur))throw new Error("store is not a valid syncedStore that maps to a Y.Doc");return e}function ci(t){if(typeof t!="object"||t===null)return;const e=t[ia];return e&&(qc(e),e.__v_skip=!0),e}function mE(t,e){if(t===e)return!0;if(typeof t=="object"&&typeof e=="object"){const n=ci(t),r=ci(e);return!n||!r?!1:n===r}return!1}function gE(t,e=new ur){return cE(e),dE(e,t)}var xe={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Cs=Symbol.for("react.element"),yE=Symbol.for("react.portal"),_E=Symbol.for("react.fragment"),bE=Symbol.for("react.strict_mode"),wE=Symbol.for("react.profiler"),vE=Symbol.for("react.provider"),EE=Symbol.for("react.context"),kE=Symbol.for("react.forward_ref"),SE=Symbol.for("react.suspense"),AE=Symbol.for("react.memo"),TE=Symbol.for("react.lazy"),Xd=Symbol.iterator;function xE(t){return t===null||typeof t!="object"?null:(t=Xd&&t[Xd]||t["@@iterator"],typeof t=="function"?t:null)}var Zd={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Yd=Object.assign,Qd={};function ji(t,e,n){this.props=t,this.context=e,this.refs=Qd,this.updater=n||Zd}ji.prototype.isReactComponent={},ji.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")},ji.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function ep(){}ep.prototype=ji.prototype;function Ll(t,e,n){this.props=t,this.context=e,this.refs=Qd,this.updater=n||Zd}var Ml=Ll.prototype=new ep;Ml.constructor=Ll,Yd(Ml,ji.prototype),Ml.isPureReactComponent=!0;var tp=Array.isArray,np=Object.prototype.hasOwnProperty,Ul={current:null},rp={key:!0,ref:!0,__self:!0,__source:!0};function ip(t,e,n){var r,i={},s=null,o=null;if(e!=null)for(r in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(s=""+e.key),e)np.call(e,r)&&!rp.hasOwnProperty(r)&&(i[r]=e[r]);var a=arguments.length-2;if(a===1)i.children=n;else if(1{ve(t,Bl);const n=tv(e);Mt(t,n)},lp=(t,e,n)=>{ve(t,ap),Mt(t,Zw(e,n))},LE=(t,e,n)=>lp(e,n,Dt(t)),up=(t,e,n)=>{try{qw(e,Dt(t),n)}catch(r){console.error("Caught error while handling a Yjs update",r)}},ME=(t,e)=>{ve(t,cp),Mt(t,e)},UE=up,PE=(t,e,n,r)=>{const i=Ee(t);switch(i){case Bl:LE(t,e,n);break;case ap:up(t,n,r);break;case cp:UE(t,n,r);break;default:throw new Error("Unknown message type")}return i};function tt(t,e,n,r){const i=r??"";return Te.emit(`error:${e}`,t,n,i),XE(t,n,i)}function DE(t,e,n){Te.emit("gadgetclient:reset",t,e,n)}function BE(t,e,n){Te.emit("gadgetclient:patch",t,e,n)}function FE(t,e){Te.emit("gadgetserver:clearplayer",t,void 0,e)}function $E(t,e){Te.emit("peer:joincode",t,void 0,e)}function jE(t,e){Te.emit("started",t,void 0,e)}function zE(t,e,n,r){Te.emit("register:flush",t,[e,n],r)}function WE(t,e){Te.emit("register:dev",t,void 0,e)}function GE(t,e){Te.emit("register:share",t,void 0,e)}function HE(t,e){Te.emit("register:refresh",t,void 0,e)}function VE(t,e){Te.emit("register:nuke",t,void 0,e)}function KE(t,e,n){Te.emit("synth:tts",t,[e,n])}function qE(t,e,n){Te.emit("synth:play",t,[e,n])}function Fl(t,e,n,r){Te.emit("synth:voice",t,[e,n,r])}function JE(t,e,n,r,i){Te.emit("synth:voicefx",t,[e,n,r,i])}function Nt(t,...e){return Te.emit("tape:info",t,e),!0}function fp(t,...e){return Te.emit("tape:debug",t,e),!0}function XE(t,...e){return Te.emit("tape:error",t,e),!1}function ZE(t,e,n,r,i,s){Te.emit("tape:editor:open",t,[e,n,r,i],s)}function YE(t,e){Te.emit("vm:endgame",t,void 0,e)}function hp(t,e){return`${t}${e}`}function $l(t,e,n){Te.emit("vm:flush",t,e,n)}const dr=gE({shared:[]});function ca(t,e,n){return t.find(r=>r.key===e&&r.type===n)}function AM(t){}function dp(t,e,n){const r=ca(dr.shared,t,e);k(r)||dr.shared.push({key:t,type:e,value:n})}function QE(t,e){dp(t,0,e)}function pp(t,e){const n=new xn(e);dp(t,1,n)}function ek(t,e){const n=ca(dr.shared,t,0);if(k(n)){n.value=e;return}dr.shared.push({key:t,type:0,value:e})}function tk(t,e){const n=new xn(e),r=ca(dr.shared,t,1);if(k(r)){r.value=n;return}dr.shared.push({key:t,type:1,value:n})}function mp(t,e,n){let r;function i(){const o=ca(dr.shared,t,e);k(o)&&(s(),r=Jd(o,()=>n(o.value)))}const s=Jd(dr.shared,i);return i(),()=>r==null?void 0:r()}function nk(t,e){return mp(t,0,e)}function gp(t,e){return mp(t,1,n=>e(n.toJSON()))}function la(t){return An(t)}const Fr=pE(dr),Gn=ls("modem",["second"],t=>{switch(t.target){case"second":break;case"join":if(t.sender!==Gn.id()){Gn.reply(t,"joinack");const e=Mr();CE(e,Fr),Gn.reply(t,"sync",la(e));const n=Mr();lp(n,Fr),Gn.reply(t,"sync",la(n))}break;case"joinack":t.sender,Gn.id();break;case"sync":{if(t.sender!==Gn.id()&&k(t.data))try{const e=ni(t.data),n=Mr();PE(e,n,Fr,Gn)===Bl&&Gn.emit("modem:sync",la(n))}catch(e){tt(Gn.name(),"sync",e.message)}break}}});function yp(t){const e=Mr();ME(e,t),Gn.emit("modem:sync",la(e))}Fr.on("update",yp),Fr.on("destroy",()=>{Fr==null||Fr.off("update",yp)});function ua(t,e){return new Array(t).fill(e)}function _p(t,e,n,r,i=0){const s=n*r;return{id:`tiles:${t}:${e}`,type:1,width:n,height:r,char:ua(s,0),color:ua(s,0),bg:ua(s,i)}}function rk(t,e,n,r=1,i=15){return{id:`sprites:${t}:${e}:${n}`,x:0,y:0,char:r,color:i,bg:be.ONCLEAR}}function ik(t,e){return{id:`sprites:${t}:${e}`,type:2,sprites:[]}}function sk(t,e,n,r,i=0){const s=n*r;return{id:`dither:${t}:${e}`,type:3,width:n,height:r,alphas:ua(s,i)}}function ok(t,e){return{id:`control:${t}:${e}`,type:5,focusx:0,focusy:0,focusid:t,viewscale:2}}var un=(t=>(t[t.START=0]="START",t[t.LEFT=1]="LEFT",t[t.RIGHT=2]="RIGHT",t[t.TOP=3]="TOP",t[t.BOTTOM=4]="BOTTOM",t[t.SCROLL=5]="SCROLL",t))(un||{});const ak={start:0,left:1,right:2,top:3,bottom:4,scroll:5},ck={0:1,1:20,2:20,3:1,4:1,5:40};function bp(t,e){return`${t}:${e}`}const lk=1,uk=16,fk=256;var Ft=(t=>(t[t.NONE=0]="NONE",t[t.ALT=1]="ALT",t[t.CTRL=2]="CTRL",t[t.SHIFT=3]="SHIFT",t[t.MOVE_UP=4]="MOVE_UP",t[t.MOVE_DOWN=5]="MOVE_DOWN",t[t.MOVE_LEFT=6]="MOVE_LEFT",t[t.MOVE_RIGHT=7]="MOVE_RIGHT",t[t.OK_BUTTON=8]="OK_BUTTON",t[t.CANCEL_BUTTON=9]="CANCEL_BUTTON",t[t.MENU_BUTTON=10]="MENU_BUTTON",t[t.SHOOT_UP=11]="SHOOT_UP",t[t.SHOOT_DOWN=12]="SHOOT_DOWN",t[t.SHOOT_LEFT=13]="SHOOT_LEFT",t[t.SHOOT_RIGHT=14]="SHOOT_RIGHT",t))(Ft||{});const $r={};function jl(){return{layers:[],panels:[],reset:!0,focus:"scroll"}}function wp(t){t.text=[],Object.values($r[t.id]??{}).forEach(e=>e==null?void 0:e()),$r[t.id]={}}function vp(t){const e=t.panels.find(n=>n.name===t.focus);if(!e){const n={id:ht(),name:t.focus,edge:un.RIGHT,size:20,text:[]};return t.panels.push(n),t.reset=!1,n}return e}const hk=new Set(["hk","hotkey","rn","range","sl","select","nm","number","tx","text"]),dk=new Set(["rn","range","sl","select","nm","number","tx","text"]),pk=new Set(["tx","text"]),mk={rn:1,range:1,sl:0,select:0,nm:0,number:0,tx:"",text:""},zl={};let Ep=t=>{let e=zl[t];return k(e)||(zl[t]=e=jl()),e};function gk(t){Ep=t}function li(t){return Ep(t)}function yk(t){const e=li(t);e.panels=e.panels.filter(n=>n.edge!==un.SCROLL)}function _k(t,e,n){Object.values($r).forEach(r=>{if(r[e]!==void 0){const i=bp(t.id(),e);ke(n)&&ek(i,n),Se(n)&&tk(i,n)}})}function bk(t){let e="";const n=li(t);return n.panels=n.panels.filter(r=>{if(r.edge===un.SCROLL){const[i]=r.text;return Se(i)&&r.text.length===1&&(e=i),r.text.length>1}return!0}),e}function Wl(t,e,n,r,i){const s=li(t),o=r,a=i??Eb.capital(e),c=s.panels.find(l=>l.name===a);if(c)s.reset=!0,s.focus=a,ke(o)&&(c.size=o);else switch(n){case un.START:{zl[t]=jl();break}case un.LEFT:case un.RIGHT:case un.TOP:case un.BOTTOM:case un.SCROLL:{const l={id:ht(),name:a,edge:n,size:o??ck[n],text:[]};s.panels.push(l),s.focus=a;break}}}function wk(t,e){const n=li(t),r=vp(n);n.reset&&(n.reset=!1,wp(r)),r.text.push(e)}function vk(t,e,n,r,i){const s=li(t),o=vp(s);s.reset&&(s.reset=!1,wp(o));const a=Pe(r),c=[e.id(),n,...hk.has(a)?[a]:["hyperlink",r],...i],l=c[2];if(dk.has(l)){const u=`${c[3]??""}`;$r[o.id]=$r[o.id]??{};const f=e.get(u)??mk[l];if($r[o.id][u]===void 0){const d=bp(e.id(),u);ke(f)&&QE(d,f),Se(f)&&pp(d,f),pk.has(l)?$r[o.id][u]=gp(d,h=>{k(h)&&h!==e.get(u)&&e.set(u,h)}):$r[o.id][u]=nk(d,h=>{k(h)&&h!==e.get(u)&&e.set(u,h)})}}o.text.push(c)}var kp={exports:{}},Gl={exports:{}},Sp;function Ek(){return Sp||(Sp=1,function(t,e){(function(n,r){t.exports=r()})(Pt,function(){function n(m){return!isNaN(parseFloat(m))&&isFinite(m)}function r(m){return m.charAt(0).toUpperCase()+m.substring(1)}function i(m){return function(){return this[m]}}var s=["isConstructor","isEval","isNative","isToplevel"],o=["columnNumber","lineNumber"],a=["fileName","functionName","source"],c=["args"],l=["evalOrigin"],u=s.concat(o,a,c,l);function f(m){if(m)for(var b=0;b-1&&(u=u.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var f=u.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),d=f.match(/ (\(.+\)$)/);f=d?f.replace(d[0],""):f;var h=this.extractLocation(d?d[1]:f),p=d&&f||void 0,m=["eval",""].indexOf(h[0])>-1?void 0:h[0];return new r({functionName:p,fileName:m,lineNumber:h[1],columnNumber:h[2],source:u})},this)},parseFFOrSafari:function(c){var l=c.stack.split(` +`).filter(function(u){return!u.match(o)},this);return l.map(function(u){if(u.indexOf(" > eval")>-1&&(u=u.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),u.indexOf("@")===-1&&u.indexOf(":")===-1)return new r({functionName:u});var f=/((.*".+"[^@]*)?[^@]*)(?:@)/,d=u.match(f),h=d&&d[1]?d[1]:void 0,p=this.extractLocation(u.replace(f,""));return new r({functionName:h,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:u})},this)},parseOpera:function(c){return!c.stacktrace||c.message.indexOf(` +`)>-1&&c.message.split(` +`).length>c.stacktrace.split(` +`).length?this.parseOpera9(c):c.stack?this.parseOpera11(c):this.parseOpera10(c)},parseOpera9:function(c){for(var l=/Line (\d+).*script (?:in )?(\S+)/i,u=c.message.split(` +`),f=[],d=2,h=u.length;d/,"$2").replace(/\([^)]*\)/g,"")||void 0,m;h.match(/\(([^)]*)\)/)&&(m=h.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var b=m===void 0||m==="[arguments not available]"?void 0:m.split(",");return new r({functionName:p,args:b,fileName:d[0],lineNumber:d[1],columnNumber:d[2],source:u})},this)}}})})(kp);var kk=kp.exports,Sk=Ii(kk);function pr(t){const e={},n={get(){return[!1,void 0]},set(){return[!1,void 0]},tick(){},everytick(){},...t,getcommand(r){return e[r]},command(r,i){return e[r]=i,n}};return n}var Ap={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(Pt,function(){return n.importState=function(i){var s=new n;return s.importState(i),s},n;function n(){return function(i){var s=0,o=0,a=0,c=1;i.length==0&&(i=[+new Date]);var l=r();s=l(" "),o=l(" "),a=l(" ");for(var u=0;u>>0,c-=i,c*=i,i=c>>>0,c-=i,i+=c*4294967296}return(i>>>0)*23283064365386963e-26};return s.version="Mash 0.9",s}})})(Ap);var Ak=Ap.exports,Tk=Ii(Ak);function ui(t,e,n){return Math.max(e,Math.min(n,t))}const xk=Tk("089fad0j9awfem09wavefc09uwaef");function Rk(){return xk()}function Ls(t,e){const n=Math.min(t,e),i=Math.max(t,e)-n+1;return n+Math.floor(Rk()*i)}function Hl(t,e,n){typeof t!="number"&&(t=0,e=0,n=1),typeof e!="number"&&(e=t,t=0,n=1),typeof n!="number"&&(n=1);const r=[],i=Math.min(t,e),s=Math.max(t,e);for(let o=i;o<=s;o+=n)r.push(o);return r}function Ik(t){return t[Ls(0,t.length-1)]}function mr(...t){return Ik(t.flat())}function Ok(t){return[...new Set(t)].filter(k)}function Nk(...t){const e=t.flat().filter(k);return e.reduce((n,r)=>n+r,0)/e.length}function gr(t){return k(t)&&k(t.x)&&k(t.y)}function Tt(t,e){switch(e){case ae.NORTH:--t.y;break;case ae.SOUTH:++t.y;break;case ae.WEST:--t.x;break;case ae.EAST:++t.x;break}return t}function zi(t,e){const n=e.x-t.x,r=e.y-t.y;if(n<0)return ae.WEST;if(n>0)return ae.EAST;if(r<0)return ae.NORTH;if(r>0)return ae.SOUTH}const Tp={idle:"IDLE",up:"NORTH",down:"SOUTH",left:"WEST",right:"EAST",by:"BY",at:"AT",flow:"FLOW",seek:"SEEK",rndns:"RNDNS",rndne:"RNDNE",rnd:"RND",cw:"CW",ccw:"CCW",opp:"OPP",rndp:"RNDP",i:"IDLE",u:"NORTH",north:"NORTH",n:"NORTH",d:"SOUTH",south:"SOUTH",s:"SOUTH",l:"WEST",west:"WEST",w:"WEST",r:"EAST",east:"EAST",e:"EAST",edit:"EDIT"};function yr(t){return He(t)&&xp(t[0])}function xp(t){return k(ae[t])&&Se(t)}function Ck(t){const e=ae[t];return k(e)?e:ae.IDLE}function Rp(t){if(Se(t))return Tp[Pe(t)]}function Ip(t){if(yr(t))return t;if(xp(t))return[t];const e=Rp(t);if(k(e))return[e]}function Op(t){const e=N.words[t],n=Ip(e);if(yr(n))return[n,t+1];const[r,i]=Gt(t),s=Ip(r);return yr(s)?[s,i]:[void 0,t]}function Vl(t){const e=[];let[n,r]=Op(t);for(;yr(n);){if(e.push(...n),(n[0]==="AT"||n[0]==="BY")&&n.length<2){const[o,a,c]=ne(N.words,r,[q.NUMBER,q.NUMBER]);e.push(o,a),r=c}const[i,s]=Op(r);n=i,r=s}return e.length?[e,r]:[void 0,t]}function Wi(t){return He(t)&&typeof t[0]=="string"}function Np(t){const e=N.words[t];if(Wi(e))return[e,t+1];const[n,r]=dc(t),[i,s]=Gt(r,!1);return Se(i)?[[i,n],s]:[void 0,t]}function fa(t){if(!Wi(t))return;const[e]=t;return e}function Cp(t){if(!Wi(t))return;const[,e]=t,n=k(e)?ZN(e):void 0;return k(n)?n:void 0}function Lp(t){if(!Wi(t))return;const[,e]=t,n=k(e)?YN(e):void 0;return k(n)?n:void 0}const ze=60,rn=25;var Re=(t=>(t[t.ERROR=0]="ERROR",t[t.LOADER=1]="LOADER",t[t.BOARD=2]="BOARD",t[t.OBJECT=3]="OBJECT",t[t.TERRAIN=4]="TERRAIN",t[t.CHARSET=5]="CHARSET",t[t.PALETTE=6]="PALETTE",t))(Re||{});function Mp(t,e){const n=t??Ye.ISWALK,r=e??Ye.ISWALK;switch(n){case Ye.ISWALK:return r!==Ye.ISWALK;case Ye.ISSWIM:return r!==Ye.ISSWIM;case Ye.ISSOLID:return!0;case Ye.ISBULLET:return r!==Ye.ISWALK&&r!==Ye.ISSWIM}}function Up(t,e,n){const r=t==null?void 0:t.objects[n];if(k(r))return r;if(k(e)){const i=Ms(t,"player"),s={x:e.x??0,y:e.y??0};Dp(s,i)}}function Ms(t,e){var r,i;return[...((i=(r=t==null?void 0:t.named)==null?void 0:r[e])==null?void 0:i.values())??[]].map(s=>typeof s=="string"?t==null?void 0:t.objects[s]:t==null?void 0:t.terrain[s]).filter(k)}function Pp(t,e){const n=fa(e),r=Cp(e),i=Lp(e);return t.filter(s=>!(k(n)&&vf(s)!==n||k(r)&&iC(s)!==r||k(i)&&sC(s)!==i)).filter(k)}function Kl(t,e){return k(t)?e.map(n=>{var r;if(typeof n=="string"){const i=t.objects[n];if(k(i))return i;const s=Ms(t,Pe(n));if(s.length)return s}else if(gr(n)&&n.x>=0&&n.x=0&&n.y0){if(++e>=w1)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function S1(t){return function(){return t}}var ma=function(){try{var t=hi(Object,"defineProperty");return t({},"",{}),t}catch{}}(),A1=ma?function(t,e){return ma(t,"toString",{configurable:!0,enumerable:!1,value:S1(e),writable:!0})}:Gi,T1=k1(A1);function qp(t,e){for(var n=-1,r=t==null?0:t.length;++n-1}var I1=9007199254740991,O1=/^(?:0|[1-9]\d*)$/;function ga(t,e){var n=typeof t;return e=e??I1,!!e&&(n=="number"||n!="symbol"&&O1.test(t))&&t>-1&&t%1==0&&t-1&&t%1==0&&t<=M1}function Vn(t){return t!=null&&eu(t.length)&&!_r(t)}function Yp(t,e,n){if(!hn(n))return!1;var r=typeof e;return(r=="number"?Vn(n)&&ga(e,n.length):r=="string"&&e in n)?Ps(n[e],t):!1}function U1(t){return Ql(function(e,n){var r=-1,i=n.length,s=i>1?n[i-1]:void 0,o=i>2?n[2]:void 0;for(s=t.length>3&&typeof s=="function"?(i--,s):void 0,o&&Yp(n[0],n[1],o)&&(s=i<3?void 0:s,i=1),e=Object(e);++r-1}function VS(t,e){var n=this.__data__,r=wa(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}function br(t){var e=-1,n=t==null?0:t.length;for(this.clear();++ei?0:i+e),n=n>i?i:n,n<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var s=Array(i);++r=r?t:cu(t,e,n)}var lA="\\ud800-\\udfff",uA="\\u0300-\\u036f",fA="\\ufe20-\\ufe2f",hA="\\u20d0-\\u20ff",dA=uA+fA+hA,pA="\\ufe0e\\ufe0f",mA="\\u200d",gA=RegExp("["+mA+lA+dA+pA+"]");function dm(t){return gA.test(t)}function yA(t){return t.split("")}var pm="\\ud800-\\udfff",_A="\\u0300-\\u036f",bA="\\ufe20-\\ufe2f",wA="\\u20d0-\\u20ff",vA=_A+bA+wA,EA="\\ufe0e\\ufe0f",kA="["+pm+"]",lu="["+vA+"]",uu="\\ud83c[\\udffb-\\udfff]",SA="(?:"+lu+"|"+uu+")",mm="[^"+pm+"]",gm="(?:\\ud83c[\\udde6-\\uddff]){2}",ym="[\\ud800-\\udbff][\\udc00-\\udfff]",AA="\\u200d",_m=SA+"?",bm="["+EA+"]?",TA="(?:"+AA+"(?:"+[mm,gm,ym].join("|")+")"+bm+_m+")*",xA=bm+_m+TA,RA="(?:"+[mm+lu+"?",lu,gm,ym,kA].join("|")+")",IA=RegExp(uu+"(?="+uu+")|"+RA+xA,"g");function OA(t){return t.match(IA)||[]}function NA(t){return dm(t)?OA(t):yA(t)}function CA(t){return function(e){e=um(e);var n=dm(e)?NA(e):void 0,r=n?n[0]:e.charAt(0),i=n?cA(n,1).join(""):e.slice(1);return r[t]()+i}}var wm=CA("toUpperCase");function LA(t,e,n,r){var i=-1,s=t==null?0:t.length;for(r&&s&&(n=t[++i]);++ia))return!1;var l=s.get(t),u=s.get(e);if(l&&u)return l==e&&u==t;var f=-1,d=!0,h=n&fx?new Vi:void 0;for(s.set(t,e),s.set(e,t);++f2?e[2]:void 0;for(i&&Yp(e[0],e[1],i)&&(r=1);++n=tR&&(s=gu,o=!1,e=new Vi(e));e:for(;++i-1?i[s?e[o]:o]:void 0}}var aR=Math.max;function cR(t,e,n){var r=t==null?0:t.length;if(!r)return-1;var i=n==null?0:pa(n);return i<0&&(i=aR(r+i,0)),Jp(t,qn(e),i)}var qi=oR(cR);function On(t){return t&&t.length?t[0]:void 0}function lR(t,e){var n=-1,r=Vn(t)?Array(t.length):[];return pi(t,function(i,s,o){r[++n]=e(i,s,o)}),r}function ce(t,e){var n=Me(t)?da:lR;return n(t,qn(e))}function gn(t,e){return au(ce(t,e))}var uR=Object.prototype,fR=uR.hasOwnProperty,Ym=Qx(function(t,e,n){fR.call(t,n)?t[n].push(e):Zl(t,n,[e])}),hR=Object.prototype,dR=hR.hasOwnProperty;function pR(t,e){return t!=null&&dR.call(t,e)}function pe(t,e){return t!=null&&qm(t,e,pR)}var mR="[object String]";function qt(t){return typeof t=="string"||!Me(t)&&Rn(t)&&jr(t)==mR}function gR(t,e){return da(e,function(n){return t[n]})}function dt(t){return t==null?[]:gR(t,dn(t))}var yR=Math.max;function $t(t,e,n,r){t=Vn(t)?t:dt(t),n=n&&!r?pa(n):0;var i=t.length;return n<0&&(n=yR(i+n,0)),qt(t)?n<=i&&t.indexOf(e,n)>-1:!!i&&Xl(t,e,n)>-1}function Qm(t,e,n){var r=t==null?0:t.length;if(!r)return-1;var i=0;return Xl(t,e,i)}var _R="[object Map]",bR="[object Set]",wR=Object.prototype,vR=wR.hasOwnProperty;function qe(t){if(t==null)return!0;if(Vn(t)&&(Me(t)||typeof t=="string"||typeof t.splice=="function"||Bs(t)||nu(t)||_a(t)))return!t.length;var e=pn(t);if(e==_R||e==bR)return!t.size;if(Ds(t))return!cm(t).length;for(var n in t)if(vR.call(t,n))return!1;return!0}var ER="[object RegExp]";function kR(t){return Rn(t)&&jr(t)==ER}var eg=zr&&zr.isRegExp,vr=eg?ba(eg):kR;function Er(t){return t===void 0}var SR="Expected a function";function AR(t){if(typeof t!="function")throw new TypeError(SR);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}function TR(t,e,n,r){if(!hn(t))return t;e=Ea(e,t);for(var i=-1,s=e.length,o=s-1,a=t;a!=null&&++i=CR){var l=NR(t);if(l)return yu(l);o=!1,i=gu,c=new Vi}else c=a;e:for(;++r{n.accept(e)})}}class Xt extends Jn{constructor(e){super([]),this.idx=1,Kt(this,Nn(e,n=>n!==void 0))}set definition(e){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(e){e.visit(this)}}class Ji extends Jn{constructor(e){super(e.definition),this.orgText="",Kt(this,Nn(e,n=>n!==void 0))}}class Zt extends Jn{constructor(e){super(e.definition),this.ignoreAmbiguities=!1,Kt(this,Nn(e,n=>n!==void 0))}}class Yt extends Jn{constructor(e){super(e.definition),this.idx=1,Kt(this,Nn(e,n=>n!==void 0))}}class Xn extends Jn{constructor(e){super(e.definition),this.idx=1,Kt(this,Nn(e,n=>n!==void 0))}}class Zn extends Jn{constructor(e){super(e.definition),this.idx=1,Kt(this,Nn(e,n=>n!==void 0))}}class vt extends Jn{constructor(e){super(e.definition),this.idx=1,Kt(this,Nn(e,n=>n!==void 0))}}class Cn extends Jn{constructor(e){super(e.definition),this.idx=1,Kt(this,Nn(e,n=>n!==void 0))}}class Ln extends Jn{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){super(e.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,Kt(this,Nn(e,n=>n!==void 0))}}class nt{constructor(e){this.idx=1,Kt(this,Nn(e,n=>n!==void 0))}accept(e){e.visit(this)}}function PR(t){return ce(t,Ia)}function Ia(t){function e(n){return ce(n,Ia)}if(t instanceof Xt){const n={type:"NonTerminal",name:t.nonTerminalName,idx:t.idx};return qt(t.label)&&(n.label=t.label),n}else{if(t instanceof Zt)return{type:"Alternative",definition:e(t.definition)};if(t instanceof Yt)return{type:"Option",idx:t.idx,definition:e(t.definition)};if(t instanceof Xn)return{type:"RepetitionMandatory",idx:t.idx,definition:e(t.definition)};if(t instanceof Zn)return{type:"RepetitionMandatoryWithSeparator",idx:t.idx,separator:Ia(new nt({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof Cn)return{type:"RepetitionWithSeparator",idx:t.idx,separator:Ia(new nt({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof vt)return{type:"Repetition",idx:t.idx,definition:e(t.definition)};if(t instanceof Ln)return{type:"Alternation",idx:t.idx,definition:e(t.definition)};if(t instanceof nt){const n={type:"Terminal",name:t.terminalType.name,label:MR(t.terminalType),idx:t.idx};qt(t.label)&&(n.terminalLabel=t.label);const r=t.terminalType.PATTERN;return t.terminalType.PATTERN&&(n.pattern=vr(r)?r.source:r),n}else{if(t instanceof Ji)return{type:"Rule",name:t.name,orgText:t.orgText,definition:e(t.definition)};throw Error("non exhaustive match")}}}class mi{visit(e){const n=e;switch(n.constructor){case Xt:return this.visitNonTerminal(n);case Zt:return this.visitAlternative(n);case Yt:return this.visitOption(n);case Xn:return this.visitRepetitionMandatory(n);case Zn:return this.visitRepetitionMandatoryWithSeparator(n);case Cn:return this.visitRepetitionWithSeparator(n);case vt:return this.visitRepetition(n);case Ln:return this.visitAlternation(n);case nt:return this.visitTerminal(n);case Ji:return this.visitRule(n);default:throw Error("non exhaustive match")}}visitNonTerminal(e){}visitAlternative(e){}visitOption(e){}visitRepetition(e){}visitRepetitionMandatory(e){}visitRepetitionMandatoryWithSeparator(e){}visitRepetitionWithSeparator(e){}visitAlternation(e){}visitTerminal(e){}visitRule(e){}}function DR(t){return t instanceof Zt||t instanceof Yt||t instanceof vt||t instanceof Xn||t instanceof Zn||t instanceof Cn||t instanceof nt||t instanceof Ji}function Oa(t,e=[]){return t instanceof Yt||t instanceof vt||t instanceof Cn?!0:t instanceof Ln?vu(t.definition,r=>Oa(r,e)):t instanceof Xt&&$t(e,t)?!1:t instanceof Jn?(t instanceof Xt&&e.push(t),In(t.definition,r=>Oa(r,e))):!1}function BR(t){return t instanceof Ln}function Yn(t){if(t instanceof Xt)return"SUBRULE";if(t instanceof Yt)return"OPTION";if(t instanceof Ln)return"OR";if(t instanceof Xn)return"AT_LEAST_ONE";if(t instanceof Zn)return"AT_LEAST_ONE_SEP";if(t instanceof Cn)return"MANY_SEP";if(t instanceof vt)return"MANY";if(t instanceof nt)return"CONSUME";throw Error("non exhaustive match")}class Na{walk(e,n=[]){me(e.definition,(r,i)=>{const s=Lt(e.definition,i+1);if(r instanceof Xt)this.walkProdRef(r,s,n);else if(r instanceof nt)this.walkTerminal(r,s,n);else if(r instanceof Zt)this.walkFlat(r,s,n);else if(r instanceof Yt)this.walkOption(r,s,n);else if(r instanceof Xn)this.walkAtLeastOne(r,s,n);else if(r instanceof Zn)this.walkAtLeastOneSep(r,s,n);else if(r instanceof Cn)this.walkManySep(r,s,n);else if(r instanceof vt)this.walkMany(r,s,n);else if(r instanceof Ln)this.walkOr(r,s,n);else throw Error("non exhaustive match")})}walkTerminal(e,n,r){}walkProdRef(e,n,r){}walkFlat(e,n,r){const i=n.concat(r);this.walk(e,i)}walkOption(e,n,r){const i=n.concat(r);this.walk(e,i)}walkAtLeastOne(e,n,r){const i=[new Yt({definition:e.definition})].concat(n,r);this.walk(e,i)}walkAtLeastOneSep(e,n,r){const i=ig(e,n,r);this.walk(e,i)}walkMany(e,n,r){const i=[new Yt({definition:e.definition})].concat(n,r);this.walk(e,i)}walkManySep(e,n,r){const i=ig(e,n,r);this.walk(e,i)}walkOr(e,n,r){const i=n.concat(r);me(e.definition,s=>{const o=new Zt({definition:[s]});this.walk(o,i)})}}function ig(t,e,n){return[new Yt({definition:[new nt({terminalType:t.separator})].concat(t.definition)})].concat(e,n)}function Hs(t){if(t instanceof Xt)return Hs(t.referencedRule);if(t instanceof nt)return jR(t);if(DR(t))return FR(t);if(BR(t))return $R(t);throw Error("non exhaustive match")}function FR(t){let e=[];const n=t.definition;let r=0,i=n.length>r,s,o=!0;for(;i&&o;)s=n[r],o=Oa(s),e=e.concat(Hs(s)),r=r+1,i=n.length>r;return Ra(e)}function $R(t){const e=ce(t.definition,n=>Hs(n));return Ra(sn(e))}function jR(t){return[t.terminalType]}const sg="_~IN~_";class zR extends Na{constructor(e){super(),this.topProd=e,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(e,n,r){}walkProdRef(e,n,r){const i=GR(e.referencedRule,e.idx)+this.topProd.name,s=n.concat(r),o=new Zt({definition:s}),a=Hs(o);this.follows[i]=a}}function WR(t){const e={};return me(t,n=>{const r=new zR(n).startWalking();Kt(e,r)}),e}function GR(t,e){return t.name+e+sg}function ge(t){return t.charCodeAt(0)}function ku(t,e){Array.isArray(t)?t.forEach(function(n){e.push(n)}):e.push(t)}function Vs(t,e){if(t[e]===!0)throw"duplicate flag "+e;t[e],t[e]=!0}function Xi(t){if(t===void 0)throw Error("Internal Error - Should never get here!");return!0}function HR(){throw Error("Internal Error - Should never get here!")}function og(t){return t.type==="Character"}const Ca=[];for(let t=ge("0");t<=ge("9");t++)Ca.push(t);const La=[ge("_")].concat(Ca);for(let t=ge("a");t<=ge("z");t++)La.push(t);for(let t=ge("A");t<=ge("Z");t++)La.push(t);const ag=[ge(" "),ge("\f"),ge(` +`),ge("\r"),ge(" "),ge("\v"),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge(" "),ge("\u2028"),ge("\u2029"),ge(" "),ge(" "),ge(" "),ge("\uFEFF")],VR=/[0-9a-fA-F]/,Ma=/[0-9]/,KR=/[1-9]/;class qR{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(e){this.idx=e.idx,this.input=e.input,this.groupIdx=e.groupIdx}pattern(e){this.idx=0,this.input=e,this.groupIdx=0,this.consumeChar("/");const n=this.disjunction();this.consumeChar("/");const r={type:"Flags",loc:{begin:this.idx,end:e.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":Vs(r,"global");break;case"i":Vs(r,"ignoreCase");break;case"m":Vs(r,"multiLine");break;case"u":Vs(r,"unicode");break;case"y":Vs(r,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:r,value:n,loc:this.loc(0)}}disjunction(){const e=[],n=this.idx;for(e.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),e.push(this.alternative());return{type:"Disjunction",value:e,loc:this.loc(n)}}alternative(){const e=[],n=this.idx;for(;this.isTerm();)e.push(this.term());return{type:"Alternative",value:e,loc:this.loc(n)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){const e=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(e)};case"$":return{type:"EndAnchor",loc:this.loc(e)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(e)};case"B":return{type:"NonWordBoundary",loc:this.loc(e)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let n;switch(this.popChar()){case"=":n="Lookahead";break;case"!":n="NegativeLookahead";break}Xi(n);const r=this.disjunction();return this.consumeChar(")"),{type:n,value:r,loc:this.loc(e)}}return HR()}quantifier(e=!1){let n;const r=this.idx;switch(this.popChar()){case"*":n={atLeast:0,atMost:1/0};break;case"+":n={atLeast:1,atMost:1/0};break;case"?":n={atLeast:0,atMost:1};break;case"{":const i=this.integerIncludingZero();switch(this.popChar()){case"}":n={atLeast:i,atMost:i};break;case",":let s;this.isDigit()?(s=this.integerIncludingZero(),n={atLeast:i,atMost:s}):n={atLeast:i,atMost:1/0},this.consumeChar("}");break}if(e===!0&&n===void 0)return;Xi(n);break}if(!(e===!0&&n===void 0)&&Xi(n))return this.peekChar(0)==="?"?(this.consumeChar("?"),n.greedy=!1):n.greedy=!0,n.type="Quantifier",n.loc=this.loc(r),n}atom(){let e;const n=this.idx;switch(this.peekChar()){case".":e=this.dotAll();break;case"\\":e=this.atomEscape();break;case"[":e=this.characterClass();break;case"(":e=this.group();break}if(e===void 0&&this.isPatternCharacter()&&(e=this.patternCharacter()),Xi(e))return e.loc=this.loc(n),this.isQuantifier()&&(e.quantifier=this.quantifier()),e}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[ge(` +`),ge("\r"),ge("\u2028"),ge("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let e,n=!1;switch(this.popChar()){case"d":e=Ca;break;case"D":e=Ca,n=!0;break;case"s":e=ag;break;case"S":e=ag,n=!0;break;case"w":e=La;break;case"W":e=La,n=!0;break}if(Xi(e))return{type:"Set",value:e,complement:n}}controlEscapeAtom(){let e;switch(this.popChar()){case"f":e=ge("\f");break;case"n":e=ge(` +`);break;case"r":e=ge("\r");break;case"t":e=ge(" ");break;case"v":e=ge("\v");break}if(Xi(e))return{type:"Character",value:e}}controlLetterEscapeAtom(){this.consumeChar("c");const e=this.popChar();if(/[a-zA-Z]/.test(e)===!1)throw Error("Invalid ");return{type:"Character",value:e.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:ge("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){const e=this.popChar();return{type:"Character",value:ge(e)}}classPatternCharacterAtom(){switch(this.peekChar()){case` +`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:const e=this.popChar();return{type:"Character",value:ge(e)}}}characterClass(){const e=[];let n=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),n=!0);this.isClassAtom();){const r=this.classAtom();if(r.type,og(r)&&this.isRangeDash()){this.consumeChar("-");const i=this.classAtom();if(i.type,og(i)){if(i.value=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(e){return{begin:e,end:this.idx}}}class Su{visitChildren(e){for(const n in e){const r=e[n];e.hasOwnProperty(n)&&(r.type!==void 0?this.visit(r):Array.isArray(r)&&r.forEach(i=>{this.visit(i)},this))}}visit(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e);break}this.visitChildren(e)}visitPattern(e){}visitFlags(e){}visitDisjunction(e){}visitAlternative(e){}visitStartAnchor(e){}visitEndAnchor(e){}visitWordBoundary(e){}visitNonWordBoundary(e){}visitLookahead(e){}visitNegativeLookahead(e){}visitCharacter(e){}visitSet(e){}visitGroup(e){}visitGroupBackReference(e){}visitQuantifier(e){}}let Ua={};const JR=new qR;function Pa(t){const e=t.toString();if(Ua.hasOwnProperty(e))return Ua[e];{const n=JR.pattern(e);return Ua[e]=n,n}}function XR(){Ua={}}const cg="Complement Sets are not supported for first char optimization",Da=`Unable to use "first char" lexer optimizations: +`;function ZR(t,e=!1){try{const n=Pa(t);return Au(n.value,{},n.flags.ignoreCase)}catch(n){if(n.message===cg)e&&tg(`${Da} Unable to optimize: < ${t.toString()} > + Complement Sets cannot be automatically optimized. + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let r="";e&&(r=` + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),Eu(`${Da} + Failed parsing: < ${t.toString()} > + Using the @chevrotain/regexp-to-ast library + Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+r)}}return[]}function Au(t,e,n){switch(t.type){case"Disjunction":for(let i=0;i{if(typeof c=="number")Ba(c,e,n);else{const l=c;if(n===!0)for(let u=l.from;u<=l.to;u++)Ba(u,e,n);else{for(let u=l.from;u<=l.to&&u=qs){const u=l.from>=qs?l.from:qs,f=l.to,d=Wr(u),h=Wr(f);for(let p=d;p<=h;p++)e[p]=p}}}});break;case"Group":Au(o.value,e,n);break;default:throw Error("Non Exhaustive Match")}const a=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&Tu(o)===!1||o.type!=="Group"&&a===!1)break}break;default:throw Error("non exhaustive match!")}return dt(e)}function Ba(t,e,n){const r=Wr(t);e[r]=r,n===!0&&YR(t,e)}function YR(t,e){const n=String.fromCharCode(t),r=n.toUpperCase();if(r!==n){const i=Wr(r.charCodeAt(0));e[i]=i}else{const i=n.toLowerCase();if(i!==n){const s=Wr(i.charCodeAt(0));e[s]=s}}}function lg(t,e){return qi(t.value,n=>{if(typeof n=="number")return $t(e,n);{const r=n;return qi(e,i=>r.from<=i&&i<=r.to)!==void 0}})}function Tu(t){const e=t.quantifier;return e&&e.atLeast===0?!0:t.value?Me(t.value)?In(t.value,Tu):Tu(t.value):!1}class QR extends Su{constructor(e){super(),this.targetCharCodes=e,this.found=!1}visitChildren(e){if(this.found!==!0){switch(e.type){case"Lookahead":this.visitLookahead(e);return;case"NegativeLookahead":this.visitNegativeLookahead(e);return}super.visitChildren(e)}}visitCharacter(e){$t(this.targetCharCodes,e.value)&&(this.found=!0)}visitSet(e){e.complement?lg(e,this.targetCharCodes)===void 0&&(this.found=!0):lg(e,this.targetCharCodes)!==void 0&&(this.found=!0)}}function xu(t,e){if(e instanceof RegExp){const n=Pa(e),r=new QR(t);return r.visit(n),r.found}else return qi(e,n=>$t(t,n.charCodeAt(0)))!==void 0}const gi="PATTERN",Ks="defaultMode",Fa="modes";let ug=typeof new RegExp("(?:)").sticky=="boolean";function eI(t,e){e=wu(e,{useSticky:ug,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` +`],tracer:(w,v)=>v()});const n=e.tracer;n("initCharCodeToOptimizedIndexMap",()=>{kI()});let r;n("Reject Lexer.NA",()=>{r=xa(t,w=>w[gi]===Et.NA)});let i=!1,s;n("Transform Patterns",()=>{i=!1,s=ce(r,w=>{const v=w[gi];if(vr(v)){const S=v.source;return S.length===1&&S!=="^"&&S!=="$"&&S!=="."&&!v.ignoreCase?S:S.length===2&&S[0]==="\\"&&!$t(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],S[1])?S[1]:e.useSticky?hg(v):fg(v)}else{if(_r(v))return i=!0,{exec:v};if(typeof v=="object")return i=!0,v;if(typeof v=="string"){if(v.length===1)return v;{const S=v.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),L=new RegExp(S);return e.useSticky?hg(L):fg(L)}}else throw Error("non exhaustive match")}})});let o,a,c,l,u;n("misc mapping",()=>{o=ce(r,w=>w.tokenTypeIdx),a=ce(r,w=>{const v=w.GROUP;if(v!==Et.SKIPPED){if(qt(v))return v;if(Er(v))return!1;throw Error("non exhaustive match")}}),c=ce(r,w=>{const v=w.LONGER_ALT;if(v)return Me(v)?ce(v,L=>Qm(r,L)):[Qm(r,v)]}),l=ce(r,w=>w.PUSH_MODE),u=ce(r,w=>pe(w,"POP_MODE"))});let f;n("Line Terminator Handling",()=>{const w=mg(e.lineTerminatorCharacters);f=ce(r,v=>!1),e.positionTracking!=="onlyOffset"&&(f=ce(r,v=>pe(v,"LINE_BREAKS")?!!v.LINE_BREAKS:pg(v,w)===!1&&xu(w,v.PATTERN)))});let d,h,p,m;n("Misc Mapping #2",()=>{d=ce(r,dg),h=ce(s,wI),p=Jt(r,(w,v)=>{const S=v.GROUP;return qt(S)&&S!==Et.SKIPPED&&(w[S]=[]),w},{}),m=ce(s,(w,v)=>({pattern:s[v],longerAlt:c[v],canLineTerminator:f[v],isCustom:d[v],short:h[v],group:a[v],push:l[v],pop:u[v],tokenTypeIdx:o[v],tokenType:r[v]}))});let b=!0,_=[];return e.safeMode||n("First Char Optimization",()=>{_=Jt(r,(w,v,S)=>{if(typeof v.PATTERN=="string"){const L=v.PATTERN.charCodeAt(0),I=Wr(L);Ru(w,I,m[S])}else if(Me(v.START_CHARS_HINT)){let L;me(v.START_CHARS_HINT,I=>{const T=typeof I=="string"?I.charCodeAt(0):I,M=Wr(T);L!==M&&(L=M,Ru(w,M,m[S]))})}else if(vr(v.PATTERN))if(v.PATTERN.unicode)b=!1,e.ensureOptimizations&&Eu(`${Da} Unable to analyze < ${v.PATTERN.toString()} > pattern. + The regexp unicode flag is not currently supported by the regexp-to-ast library. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{const L=ZR(v.PATTERN,e.ensureOptimizations);qe(L)&&(b=!1),me(L,I=>{Ru(w,I,m[S])})}else e.ensureOptimizations&&Eu(`${Da} TokenType: <${v.name}> is using a custom token pattern without providing parameter. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),b=!1;return w},[])}),{emptyGroups:p,patternIdxToConfig:m,charCodeToPatternIdxToConfig:_,hasCustom:i,canBeOptimized:b}}function tI(t,e){let n=[];const r=rI(t);n=n.concat(r.errors);const i=iI(r.valid),s=i.valid;return n=n.concat(i.errors),n=n.concat(nI(s)),n=n.concat(hI(s)),n=n.concat(dI(s,e)),n=n.concat(pI(s)),n}function nI(t){let e=[];const n=mn(t,r=>vr(r[gi]));return e=e.concat(oI(n)),e=e.concat(lI(n)),e=e.concat(uI(n)),e=e.concat(fI(n)),e=e.concat(aI(n)),e}function rI(t){const e=mn(t,i=>!pe(i,gi)),n=ce(e,i=>({message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:at.MISSING_PATTERN,tokenTypes:[i]})),r=Ta(t,e);return{errors:n,valid:r}}function iI(t){const e=mn(t,i=>{const s=i[gi];return!vr(s)&&!_r(s)&&!pe(s,"exec")&&!qt(s)}),n=ce(e,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:at.INVALID_PATTERN,tokenTypes:[i]})),r=Ta(t,e);return{errors:n,valid:r}}const sI=/[^\\][$]/;function oI(t){class e extends Su{constructor(){super(...arguments),this.found=!1}visitEndAnchor(s){this.found=!0}}const n=mn(t,i=>{const s=i.PATTERN;try{const o=Pa(s),a=new e;return a.visit(o),a.found}catch{return sI.test(s.source)}});return ce(n,i=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain end of input anchor '$' + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:at.EOI_ANCHOR_FOUND,tokenTypes:[i]}))}function aI(t){const e=mn(t,r=>r.PATTERN.test(""));return ce(e,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' must not match an empty string",type:at.EMPTY_MATCH_PATTERN,tokenTypes:[r]}))}const cI=/[^\\[][\^]|^\^/;function lI(t){class e extends Su{constructor(){super(...arguments),this.found=!1}visitStartAnchor(s){this.found=!0}}const n=mn(t,i=>{const s=i.PATTERN;try{const o=Pa(s),a=new e;return a.visit(o),a.found}catch{return cI.test(s.source)}});return ce(n,i=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain start of input anchor '^' + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:at.SOI_ANCHOR_FOUND,tokenTypes:[i]}))}function uI(t){const e=mn(t,r=>{const i=r[gi];return i instanceof RegExp&&(i.multiline||i.global)});return ce(e,r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:at.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[r]}))}function fI(t){const e=[];let n=ce(t,s=>Jt(t,(o,a)=>(s.PATTERN.source===a.PATTERN.source&&!$t(e,a)&&a.PATTERN!==Et.NA&&(e.push(a),o.push(a)),o),[]));n=Ws(n);const r=mn(n,s=>s.length>1);return ce(r,s=>{const o=ce(s,c=>c.name);return{message:`The same RegExp pattern ->${On(s).PATTERN}<-has been used in all of the following Token Types: ${o.join(", ")} <-`,type:at.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}})}function hI(t){const e=mn(t,r=>{if(!pe(r,"GROUP"))return!1;const i=r.GROUP;return i!==Et.SKIPPED&&i!==Et.NA&&!qt(i)});return ce(e,r=>({message:"Token Type: ->"+r.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:at.INVALID_GROUP_TYPE_FOUND,tokenTypes:[r]}))}function dI(t,e){const n=mn(t,i=>i.PUSH_MODE!==void 0&&!$t(e,i.PUSH_MODE));return ce(n,i=>({message:`Token Type: ->${i.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${i.PUSH_MODE}<-which does not exist`,type:at.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}))}function pI(t){const e=[],n=Jt(t,(r,i,s)=>{const o=i.PATTERN;return o===Et.NA||(qt(o)?r.push({str:o,idx:s,tokenType:i}):vr(o)&&gI(o)&&r.push({str:o.source,idx:s,tokenType:i})),r},[]);return me(t,(r,i)=>{me(n,({str:s,idx:o,tokenType:a})=>{if(i${a.name}<- can never be matched. +Because it appears AFTER the Token Type ->${r.name}<-in the lexer's definition. +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;e.push({message:c,type:at.UNREACHABLE_PATTERN,tokenTypes:[r,a]})}})}),e}function mI(t,e){if(vr(e)){const n=e.exec(t);return n!==null&&n.index===0}else{if(_r(e))return e(t,0,[],{});if(pe(e,"exec"))return e.exec(t,0,[],{});if(typeof e=="string")return e===t;throw Error("non exhaustive match")}}function gI(t){return qi([".","\\","[","]","|","^","$","(",")","?","*","+","{"],n=>t.source.indexOf(n)!==-1)===void 0}function fg(t){const e=t.ignoreCase?"i":"";return new RegExp(`^(?:${t.source})`,e)}function hg(t){const e=t.ignoreCase?"iy":"y";return new RegExp(`${t.source}`,e)}function yI(t,e,n){const r=[];return pe(t,Ks)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+Ks+`> property in its definition +`,type:at.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),pe(t,Fa)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+Fa+`> property in its definition +`,type:at.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),pe(t,Fa)&&pe(t,Ks)&&!pe(t.modes,t.defaultMode)&&r.push({message:`A MultiMode Lexer cannot be initialized with a ${Ks}: <${t.defaultMode}>which does not exist +`,type:at.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),pe(t,Fa)&&me(t.modes,(i,s)=>{me(i,(o,a)=>{if(Er(o))r.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${s}> at index: <${a}> +`,type:at.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED});else if(pe(o,"LONGER_ALT")){const c=Me(o.LONGER_ALT)?o.LONGER_ALT:[o.LONGER_ALT];me(c,l=>{!Er(l)&&!$t(i,l)&&r.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${l.name}> on token <${o.name}> outside of mode <${s}> +`,type:at.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),r}function _I(t,e,n){const r=[];let i=!1;const s=Ws(sn(dt(t.modes))),o=xa(s,c=>c[gi]===Et.NA),a=mg(n);return e&&me(o,c=>{const l=pg(c,a);if(l!==!1){const f={message:EI(c,l),type:l.issue,tokenType:c};r.push(f)}else pe(c,"LINE_BREAKS")?c.LINE_BREAKS===!0&&(i=!0):xu(a,c.PATTERN)&&(i=!0)}),e&&!i&&r.push({message:`Warning: No LINE_BREAKS Found. + This Lexer has been defined to track line and column information, + But none of the Token Types can be identified as matching a line terminator. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS + for details.`,type:at.NO_LINE_BREAKS_FLAGS}),r}function bI(t){const e={},n=dn(t);return me(n,r=>{const i=t[r];if(Me(i))e[r]=[];else throw Error("non exhaustive match")}),e}function dg(t){const e=t.PATTERN;if(vr(e))return!1;if(_r(e))return!0;if(pe(e,"exec"))return!0;if(qt(e))return!1;throw Error("non exhaustive match")}function wI(t){return qt(t)&&t.length===1?t.charCodeAt(0):!1}const vI={test:function(t){const e=t.length;for(let n=this.lastIndex;n Token Type + Root cause: ${e.errMsg}. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(e.issue===at.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. + The problem is in the <${t.name}> Token Type + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function mg(t){return ce(t,n=>qt(n)?n.charCodeAt(0):n)}function Ru(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}const qs=256;let $a=[];function Wr(t){return t255?255+~~(t/255):t}}function Js(t,e){const n=t.tokenTypeIdx;return n===e.tokenTypeIdx?!0:e.isParent===!0&&e.categoryMatchesMap[n]===!0}function ja(t,e){return t.tokenTypeIdx===e.tokenTypeIdx}let gg=1;const yg={};function Xs(t){const e=SI(t);AI(e),xI(e),TI(e),me(e,n=>{n.isParent=n.categoryMatches.length>0})}function SI(t){let e=Ct(t),n=t,r=!0;for(;r;){n=Ws(sn(ce(n,s=>s.CATEGORIES)));const i=Ta(n,e);e=e.concat(i),qe(i)?r=!1:n=i}return e}function AI(t){me(t,e=>{bg(e)||(yg[gg]=e,e.tokenTypeIdx=gg++),wg(e)&&!Me(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),wg(e)||(e.CATEGORIES=[]),RI(e)||(e.categoryMatches=[]),II(e)||(e.categoryMatchesMap={})})}function TI(t){me(t,e=>{e.categoryMatches=[],me(e.categoryMatchesMap,(n,r)=>{e.categoryMatches.push(yg[r].tokenTypeIdx)})})}function xI(t){me(t,e=>{_g([],e)})}function _g(t,e){me(t,n=>{e.categoryMatchesMap[n.tokenTypeIdx]=!0}),me(e.CATEGORIES,n=>{const r=t.concat(e);$t(r,n)||_g(r,n)})}function bg(t){return pe(t,"tokenTypeIdx")}function wg(t){return pe(t,"CATEGORIES")}function RI(t){return pe(t,"categoryMatches")}function II(t){return pe(t,"categoryMatchesMap")}function OI(t){return pe(t,"tokenTypeIdx")}const NI={buildUnableToPopLexerModeMessage(t){return`Unable to pop Lexer Mode after encountering Token ->${t.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(t,e,n,r,i){return`unexpected character: ->${t.charAt(e)}<- at offset: ${e}, skipped ${n} characters.`}};var at;(function(t){t[t.MISSING_PATTERN=0]="MISSING_PATTERN",t[t.INVALID_PATTERN=1]="INVALID_PATTERN",t[t.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",t[t.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",t[t.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",t[t.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",t[t.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",t[t.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",t[t.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",t[t.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",t[t.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",t[t.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",t[t.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",t[t.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",t[t.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",t[t.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",t[t.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",t[t.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(at||(at={}));const Zs={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` +`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:NI,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(Zs);class Et{constructor(e,n=Zs){if(this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(i,s)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;const o=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${i}>`);const{time:a,value:c}=ng(s),l=a>10?console.warn:console.log;return this.traceInitIndent time: ${a}ms`),this.traceInitIndent--,c}else return s()},typeof n=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`);this.config=Kt({},Zs,n);const r=this.config.traceInitPerf;r===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof r=="number"&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let i,s=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===Zs.lineTerminatorsPattern)this.config.lineTerminatorsPattern=vI;else if(this.config.lineTerminatorCharacters===Zs.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(n.safeMode&&n.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),Me(e)?i={modes:{defaultMode:Ct(e)},defaultMode:Ks}:(s=!1,i=Ct(e))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(yI(i,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(_I(i,this.trackStartLines,this.config.lineTerminatorCharacters))})),i.modes=i.modes?i.modes:{},me(i.modes,(a,c)=>{i.modes[c]=xa(a,l=>Er(l))});const o=dn(i.modes);if(me(i.modes,(a,c)=>{this.TRACE_INIT(`Mode: <${c}> processing`,()=>{if(this.modes.push(c),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(tI(a,o))}),qe(this.lexerDefinitionErrors)){Xs(a);let l;this.TRACE_INIT("analyzeTokenTypes",()=>{l=eI(a,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:n.positionTracking,ensureOptimizations:n.ensureOptimizations,safeMode:n.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[c]=l.patternIdxToConfig,this.charCodeToPatternIdxToConfig[c]=l.charCodeToPatternIdxToConfig,this.emptyGroups=Kt({},this.emptyGroups,l.emptyGroups),this.hasCustom=l.hasCustom||this.hasCustom,this.canModeBeOptimized[c]=l.canBeOptimized}})}),this.defaultMode=i.defaultMode,!qe(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){const c=ce(this.lexerDefinitionErrors,l=>l.message).join(`----------------------- +`);throw new Error(`Errors detected in definition of Lexer: +`+c)}me(this.lexerDefinitionWarning,a=>{tg(a.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(ug?(this.chopInput=Gi,this.match=this.matchWithTest):(this.updateLastIndex=wt,this.match=this.matchWithExec),s&&(this.handleModes=wt),this.trackStartLines===!1&&(this.computeNewColumn=Gi),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=wt),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{const a=Jt(this.canModeBeOptimized,(c,l,u)=>(l===!1&&c.push(u),c),[]);if(n.ensureOptimizations&&!qe(a))throw Error(`Lexer Modes: < ${a.join(", ")} > cannot be optimized. + Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. + Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{XR()}),this.TRACE_INIT("toFastProperties",()=>{rg(this)})})}tokenize(e,n=this.defaultMode){if(!qe(this.lexerDefinitionErrors)){const i=ce(this.lexerDefinitionErrors,s=>s.message).join(`----------------------- +`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: +`+i)}return this.tokenizeInternal(e,n)}tokenizeInternal(e,n){let r,i,s,o,a,c,l,u,f,d,h,p,m,b,_;const w=e,v=w.length;let S=0,L=0;const I=this.hasCustom?0:Math.floor(e.length/10),T=new Array(I),M=[];let x=this.trackStartLines?1:void 0,V=this.trackStartLines?1:void 0;const oe=bI(this.emptyGroups),O=this.trackStartLines,E=this.config.lineTerminatorsPattern;let g=0,C=[],W=[];const B=[],Z=[];Object.freeze(Z);let H;function Y(){return C}function $(Ae){const je=Wr(Ae),we=W[je];return we===void 0?Z:we}const F=Ae=>{if(B.length===1&&Ae.tokenType.PUSH_MODE===void 0){const je=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(Ae);M.push({offset:Ae.startOffset,line:Ae.startLine,column:Ae.startColumn,length:Ae.image.length,message:je})}else{B.pop();const je=Ki(B);C=this.patternIdxToConfig[je],W=this.charCodeToPatternIdxToConfig[je],g=C.length;const we=this.canModeBeOptimized[je]&&this.config.safeMode===!1;W&&we?H=$:H=Y}};function ue(Ae){B.push(Ae),W=this.charCodeToPatternIdxToConfig[Ae],C=this.patternIdxToConfig[Ae],g=C.length,g=C.length;const je=this.canModeBeOptimized[Ae]&&this.config.safeMode===!1;W&&je?H=$:H=Y}ue.call(this,n);let Q;const ee=this.config.recoveryEnabled;for(;Sc.length){c=o,l=u,Q=gt;break}}}break}}if(c!==null){if(f=c.length,d=Q.group,d!==void 0&&(h=Q.tokenTypeIdx,p=this.createTokenInstance(c,S,h,Q.tokenType,x,V,f),this.handlePayload(p,l),d===!1?L=this.addToken(T,L,p):oe[d].push(p)),e=this.chopInput(e,f),S=S+f,V=this.computeNewColumn(V,f),O===!0&&Q.canLineTerminator===!0){let _e=0,Ge,$e;E.lastIndex=0;do Ge=E.test(c),Ge===!0&&($e=E.lastIndex-1,_e++);while(Ge===!0);_e!==0&&(x=x+_e,V=f-$e,this.updateTokenEndLineColumnLocation(p,d,$e,_e,x,V,f))}this.handleModes(Q,F,ue,p)}else{const _e=S,Ge=x,$e=V;let gt=ee===!1;for(;gt===!1&&S ${Ys(t)} <--`:`token of type --> ${t.name} <--`} but found --> '${e.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:t,ruleName:e}){return"Redundant input, expecting EOF but found: "+t.image},buildNoViableAltMessage({expectedPathsPerAlt:t,actual:e,previous:n,customUserDescription:r,ruleName:i}){const s="Expecting: ",a=` +but found: '`+On(e).image+"'";if(r)return s+r+a;{const c=Jt(t,(d,h)=>d.concat(h),[]),l=ce(c,d=>`[${ce(d,h=>Ys(h)).join(", ")}]`),f=`one of these possible Token sequences: +${ce(l,(d,h)=>` ${h+1}. ${d}`).join(` +`)}`;return s+f+a}},buildEarlyExitMessage({expectedIterationPaths:t,actual:e,customUserDescription:n,ruleName:r}){const i="Expecting: ",o=` +but found: '`+On(e).image+"'";if(n)return i+n+o;{const c=`expecting at least one iteration which starts with one of these possible Token sequences:: + <${ce(t,l=>`[${ce(l,u=>Ys(u)).join(",")}]`).join(" ,")}>`;return i+c+o}}};Object.freeze(Og);const UI={buildRuleNotFoundError(t,e){return"Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+`<- +inside top level rule: ->`+t.name+"<-"}},_i={buildDuplicateFoundError(t,e){function n(u){return u instanceof nt?u.terminalType.name:u instanceof Xt?u.nonTerminalName:""}const r=t.name,i=On(e),s=i.idx,o=Yn(i),a=n(i),c=s>0;let l=`->${o}${c?s:""}<- ${a?`with argument: ->${a}<-`:""} + appears more than once (${e.length} times) in the top level rule: ->${r}<-. + For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES + `;return l=l.replace(/[ \t]+/g," "),l=l.replace(/\s\s+/g,` +`),l},buildNamespaceConflictError(t){return`Namespace conflict found in grammar. +The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${t.name}>. +To resolve this make sure each Terminal and Non-Terminal names are unique +This is easy to accomplish by using the convention that Terminal names start with an uppercase letter +and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(t){const e=ce(t.prefixPath,i=>Ys(i)).join(", "),n=t.alternation.idx===0?"":t.alternation.idx;return`Ambiguous alternatives: <${t.ambiguityIndices.join(" ,")}> due to common lookahead prefix +in inside <${t.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX +For Further details.`},buildAlternationAmbiguityError(t){const e=ce(t.prefixPath,i=>Ys(i)).join(", "),n=t.alternation.idx===0?"":t.alternation.idx;let r=`Ambiguous Alternatives Detected: <${t.ambiguityIndices.join(" ,")}> in inside <${t.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +`;return r=r+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`,r},buildEmptyRepetitionError(t){let e=Yn(t.repetition);return t.repetition.idx!==0&&(e+=t.repetition.idx),`The repetition <${e}> within Rule <${t.topLevelRule.name}> can never consume any tokens. +This could lead to an infinite loop.`},buildTokenNameError(t){return"deprecated"},buildEmptyAlternationError(t){return`Ambiguous empty alternative: <${t.emptyChoiceIdx+1}> in inside <${t.topLevelRule.name}> Rule. +Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(t){return`An Alternation cannot have more than 256 alternatives: + inside <${t.topLevelRule.name}> Rule. + has ${t.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(t){const e=t.topLevelRule.name,n=ce(t.leftRecursionPath,s=>s.name),r=`${e} --> ${n.concat([e]).join(" --> ")}`;return`Left Recursion found in grammar. +rule: <${e}> can be invoked from itself (directly or indirectly) +without consuming any Tokens. The grammar path that causes this is: + ${r} + To fix this refactor your grammar to remove the left recursion. +see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(t){return"deprecated"},buildDuplicateRuleNameError(t){let e;return t.topLevelRule instanceof Ji?e=t.topLevelRule.name:e=t.topLevelRule,`Duplicate definition, rule: ->${e}<- is already defined in the grammar: ->${t.grammarName}<-`}};function PI(t,e){const n=new DI(t,e);return n.resolveRefs(),n.errors}class DI extends mi{constructor(e,n){super(),this.nameToTopRule=e,this.errMsgProvider=n,this.errors=[]}resolveRefs(){me(dt(this.nameToTopRule),e=>{this.currTopLevel=e,e.accept(this)})}visitNonTerminal(e){const n=this.nameToTopRule[e.nonTerminalName];if(n)e.referencedRule=n;else{const r=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:r,type:jt.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}}}class BI extends Na{constructor(e,n){super(),this.topProd=e,this.path=n,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=Ct(this.path.ruleStack).reverse(),this.occurrenceStack=Ct(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(e,n=[]){this.found||super.walk(e,n)}walkProdRef(e,n,r){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){const i=n.concat(r);this.updateExpectedNext(),this.walk(e.referencedRule,i)}}updateExpectedNext(){qe(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}}class FI extends BI{constructor(e,n){super(e,n),this.path=n,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(e,n,r){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){const i=n.concat(r),s=new Zt({definition:i});this.possibleTokTypes=Hs(s),this.found=!0}}}class Wa extends Na{constructor(e,n){super(),this.topRule=e,this.occurrence=n,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}}class $I extends Wa{walkMany(e,n,r){if(e.idx===this.occurrence){const i=On(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof nt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkMany(e,n,r)}}class Ng extends Wa{walkManySep(e,n,r){if(e.idx===this.occurrence){const i=On(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof nt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkManySep(e,n,r)}}class jI extends Wa{walkAtLeastOne(e,n,r){if(e.idx===this.occurrence){const i=On(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof nt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOne(e,n,r)}}class Cg extends Wa{walkAtLeastOneSep(e,n,r){if(e.idx===this.occurrence){const i=On(n.concat(r));this.result.isEndOfRule=i===void 0,i instanceof nt&&(this.result.token=i.terminalType,this.result.occurrence=i.idx)}else super.walkAtLeastOneSep(e,n,r)}}function Iu(t,e,n=[]){n=Ct(n);let r=[],i=0;function s(a){return a.concat(Lt(t,i+1))}function o(a){const c=Iu(s(a),e,n);return r.concat(c)}for(;n.length{qe(c.definition)===!1&&(r=o(c.definition))}),r;if(a instanceof nt)n.push(a.terminalType);else throw Error("non exhaustive match")}i++}return r.push({partialPath:n,suffixDef:Lt(t,i)}),r}function Lg(t,e,n,r){const i="EXIT_NONE_TERMINAL",s=[i],o="EXIT_ALTERNATIVE";let a=!1;const c=e.length,l=c-r-1,u=[],f=[];for(f.push({idx:-1,def:t,ruleStack:[],occurrenceStack:[]});!qe(f);){const d=f.pop();if(d===o){a&&Ki(f).idx<=l&&f.pop();continue}const h=d.def,p=d.idx,m=d.ruleStack,b=d.occurrenceStack;if(qe(h))continue;const _=h[0];if(_===i){const w={idx:p,def:Lt(h),ruleStack:Gs(m),occurrenceStack:Gs(b)};f.push(w)}else if(_ instanceof nt)if(p=0;w--){const v=_.definition[w],S={idx:p,def:v.definition.concat(Lt(h)),ruleStack:m,occurrenceStack:b};f.push(S),f.push(o)}else if(_ instanceof Zt)f.push({idx:p,def:_.definition.concat(Lt(h)),ruleStack:m,occurrenceStack:b});else if(_ instanceof Ji)f.push(zI(_,p,m,b));else throw Error("non exhaustive match")}return u}function zI(t,e,n,r){const i=Ct(n);i.push(t.name);const s=Ct(r);return s.push(1),{idx:e,def:t.definition,ruleStack:i,occurrenceStack:s}}var ct;(function(t){t[t.OPTION=0]="OPTION",t[t.REPETITION=1]="REPETITION",t[t.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",t[t.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",t[t.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",t[t.ALTERNATION=5]="ALTERNATION"})(ct||(ct={}));function Mg(t){if(t instanceof Yt||t==="Option")return ct.OPTION;if(t instanceof vt||t==="Repetition")return ct.REPETITION;if(t instanceof Xn||t==="RepetitionMandatory")return ct.REPETITION_MANDATORY;if(t instanceof Zn||t==="RepetitionMandatoryWithSeparator")return ct.REPETITION_MANDATORY_WITH_SEPARATOR;if(t instanceof Cn||t==="RepetitionWithSeparator")return ct.REPETITION_WITH_SEPARATOR;if(t instanceof Ln||t==="Alternation")return ct.ALTERNATION;throw Error("non exhaustive match")}function WI(t,e,n,r,i,s){const o=Nu(t,e,n),a=Bg(o)?ja:Js;return s(o,r,a,i)}function GI(t,e,n,r,i,s){const o=Cu(t,e,i,n),a=Bg(o)?ja:Js;return s(o[0],a,r)}function HI(t,e,n,r){const i=t.length,s=In(t,o=>In(o,a=>a.length===1));if(e)return function(o){const a=ce(o,c=>c.GATE);for(let c=0;csn(c)),a=Jt(o,(c,l,u)=>(me(l,f=>{pe(c,f.tokenTypeIdx)||(c[f.tokenTypeIdx]=u),me(f.categoryMatches,d=>{pe(c,d)||(c[d]=u)})}),c),{});return function(){const c=this.LA(1);return a[c.tokenTypeIdx]}}else return function(){for(let o=0;os.length===1),i=t.length;if(r&&!n){const s=sn(t);if(s.length===1&&qe(s[0].categoryMatches)){const a=s[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===a}}else{const o=Jt(s,(a,c,l)=>(a[c.tokenTypeIdx]=!0,me(c.categoryMatches,u=>{a[u]=!0}),a),[]);return function(){const a=this.LA(1);return o[a.tokenTypeIdx]===!0}}}else return function(){e:for(let s=0;sIu([o],1)),r=Pg(n.length),i=ce(n,o=>{const a={};return me(o,c=>{const l=Ou(c.partialPath);me(l,u=>{a[u]=!0})}),a});let s=n;for(let o=1;o<=e;o++){const a=s;s=Pg(a.length);for(let c=0;c{const _=Ou(b.partialPath);me(_,w=>{i[c][w]=!0})})}}}}return r}function Nu(t,e,n,r){const i=new Ug(t,ct.ALTERNATION,r);return e.accept(i),Dg(i.result,n)}function Cu(t,e,n,r){const i=new Ug(t,n);e.accept(i);const s=i.result,a=new KI(e,t,n).startWalking(),c=new Zt({definition:s}),l=new Zt({definition:a});return Dg([c,l],r)}function Lu(t,e){e:for(let n=0;n{const i=e[r];return n===i||i.categoryMatchesMap[n.tokenTypeIdx]})}function Bg(t){return In(t,e=>In(e,n=>In(n,r=>qe(r.categoryMatches))))}function XI(t){const e=t.lookaheadStrategy.validate({rules:t.rules,tokenTypes:t.tokenTypes,grammarName:t.grammarName});return ce(e,n=>Object.assign({type:jt.CUSTOM_LOOKAHEAD_VALIDATION},n))}function ZI(t,e,n,r){const i=gn(t,c=>YI(c,n)),s=uO(t,e,n),o=gn(t,c=>oO(c,n)),a=gn(t,c=>tO(c,t,r,n));return i.concat(s,o,a)}function YI(t,e){const n=new eO;t.accept(n);const r=n.allProductions,i=Ym(r,QI),s=Nn(i,a=>a.length>1);return ce(dt(s),a=>{const c=On(a),l=e.buildDuplicateFoundError(t,a),u=Yn(c),f={message:l,type:jt.DUPLICATE_PRODUCTIONS,ruleName:t.name,dslName:u,occurrence:c.idx},d=Fg(c);return d&&(f.parameter=d),f})}function QI(t){return`${Yn(t)}_#_${t.idx}_#_${Fg(t)}`}function Fg(t){return t instanceof nt?t.terminalType.name:t instanceof Xt?t.nonTerminalName:""}class eO extends mi{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(e){this.allProductions.push(e)}visitOption(e){this.allProductions.push(e)}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}visitAlternation(e){this.allProductions.push(e)}visitTerminal(e){this.allProductions.push(e)}}function tO(t,e,n,r){const i=[];if(Jt(e,(o,a)=>a.name===t.name?o+1:o,0)>1){const o=r.buildDuplicateRuleNameError({topLevelRule:t,grammarName:n});i.push({message:o,type:jt.DUPLICATE_RULE_NAME,ruleName:t.name})}return i}function nO(t,e,n){const r=[];let i;return $t(e,t)||(i=`Invalid rule override, rule: ->${t}<- cannot be overridden in the grammar: ->${n}<-as it is not defined in any of the super grammars `,r.push({message:i,type:jt.INVALID_RULE_OVERRIDE,ruleName:t})),r}function $g(t,e,n,r=[]){const i=[],s=Ga(e.definition);if(qe(s))return[];{const o=t.name;$t(s,t)&&i.push({message:n.buildLeftRecursionError({topLevelRule:t,leftRecursionPath:r}),type:jt.LEFT_RECURSION,ruleName:o});const c=Ta(s,r.concat([t])),l=gn(c,u=>{const f=Ct(r);return f.push(u),$g(t,u,n,f)});return i.concat(l)}}function Ga(t){let e=[];if(qe(t))return e;const n=On(t);if(n instanceof Xt)e.push(n.referencedRule);else if(n instanceof Zt||n instanceof Yt||n instanceof Xn||n instanceof Zn||n instanceof Cn||n instanceof vt)e=e.concat(Ga(n.definition));else if(n instanceof Ln)e=sn(ce(n.definition,s=>Ga(s.definition)));else if(!(n instanceof nt))throw Error("non exhaustive match");const r=Oa(n),i=t.length>1;if(r&&i){const s=Lt(t);return e.concat(Ga(s))}else return e}class Mu extends mi{constructor(){super(...arguments),this.alternations=[]}visitAlternation(e){this.alternations.push(e)}}function rO(t,e){const n=new Mu;t.accept(n);const r=n.alternations;return gn(r,s=>{const o=Gs(s.definition);return gn(o,(a,c)=>{const l=Lg([a],[],Js,1);return qe(l)?[{message:e.buildEmptyAlternationError({topLevelRule:t,alternation:s,emptyChoiceIdx:c}),type:jt.NONE_LAST_EMPTY_ALT,ruleName:t.name,occurrence:s.idx,alternative:c+1}]:[]})})}function iO(t,e,n){const r=new Mu;t.accept(r);let i=r.alternations;return i=xa(i,o=>o.ignoreAmbiguities===!0),gn(i,o=>{const a=o.idx,c=o.maxLookahead||e,l=Nu(a,t,c,o),u=cO(l,o,t,n),f=lO(l,o,t,n);return u.concat(f)})}class sO extends mi{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}}function oO(t,e){const n=new Mu;t.accept(n);const r=n.alternations;return gn(r,s=>s.definition.length>255?[{message:e.buildTooManyAlternativesError({topLevelRule:t,alternation:s}),type:jt.TOO_MANY_ALTS,ruleName:t.name,occurrence:s.idx}]:[])}function aO(t,e,n){const r=[];return me(t,i=>{const s=new sO;i.accept(s);const o=s.allProductions;me(o,a=>{const c=Mg(a),l=a.maxLookahead||e,u=a.idx,d=Cu(u,i,c,l)[0];if(qe(sn(d))){const h=n.buildEmptyRepetitionError({topLevelRule:i,repetition:a});r.push({message:h,type:jt.NO_NON_EMPTY_LOOKAHEAD,ruleName:i.name})}})}),r}function cO(t,e,n,r){const i=[],s=Jt(t,(a,c,l)=>(e.definition[l].ignoreAmbiguities===!0||me(c,u=>{const f=[l];me(t,(d,h)=>{l!==h&&Lu(d,u)&&e.definition[h].ignoreAmbiguities!==!0&&f.push(h)}),f.length>1&&!Lu(i,u)&&(i.push(u),a.push({alts:f,path:u}))}),a),[]);return ce(s,a=>{const c=ce(a.alts,u=>u+1);return{message:r.buildAlternationAmbiguityError({topLevelRule:n,alternation:e,ambiguityIndices:c,prefixPath:a.path}),type:jt.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:e.idx,alternatives:a.alts}})}function lO(t,e,n,r){const i=Jt(t,(o,a,c)=>{const l=ce(a,u=>({idx:c,path:u}));return o.concat(l)},[]);return Ws(gn(i,o=>{if(e.definition[o.idx].ignoreAmbiguities===!0)return[];const c=o.idx,l=o.path,u=mn(i,d=>e.definition[d.idx].ignoreAmbiguities!==!0&&d.idx{const h=[d.idx+1,c+1],p=e.idx===0?"":e.idx;return{message:r.buildAlternationPrefixAmbiguityError({topLevelRule:n,alternation:e,ambiguityIndices:h,prefixPath:d.path}),type:jt.AMBIGUOUS_PREFIX_ALTS,ruleName:n.name,occurrence:p,alternatives:h}})}))}function uO(t,e,n){const r=[],i=ce(e,s=>s.name);return me(t,s=>{const o=s.name;if($t(i,o)){const a=n.buildNamespaceConflictError(s);r.push({message:a,type:jt.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:o})}}),r}function fO(t){const e=wu(t,{errMsgProvider:UI}),n={};return me(t.rules,r=>{n[r.name]=r}),PI(n,e.errMsgProvider)}function hO(t){return t=wu(t,{errMsgProvider:_i}),ZI(t.rules,t.tokenTypes,t.errMsgProvider,t.grammarName)}const jg="MismatchedTokenException",zg="NoViableAltException",Wg="EarlyExitException",Gg="NotAllInputParsedException",Hg=[jg,zg,Wg,Gg];Object.freeze(Hg);function Ha(t){return $t(Hg,t.name)}class Va extends Error{constructor(e,n){super(e),this.token=n,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class Vg extends Va{constructor(e,n,r){super(e,n),this.previousToken=r,this.name=jg}}class dO extends Va{constructor(e,n,r){super(e,n),this.previousToken=r,this.name=zg}}class pO extends Va{constructor(e,n){super(e,n),this.name=Gg}}class mO extends Va{constructor(e,n,r){super(e,n),this.previousToken=r,this.name=Wg}}const Uu={},Kg="InRuleRecoveryException";class gO extends Error{constructor(e){super(e),this.name=Kg}}class yO{initRecoverable(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=pe(e,"recoveryEnabled")?e.recoveryEnabled:kr.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=_O)}getTokenToInsert(e){const n=za(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return n.isInsertedInRecovery=!0,n}canTokenTypeBeInsertedInRecovery(e){return!0}canTokenTypeBeDeletedInRecovery(e){return!0}tryInRepetitionRecovery(e,n,r,i){const s=this.findReSyncTokenType(),o=this.exportLexerState(),a=[];let c=!1;const l=this.LA(1);let u=this.LA(1);const f=()=>{const d=this.LA(0),h=this.errorMessageProvider.buildMismatchTokenMessage({expected:i,actual:l,previous:d,ruleName:this.getCurrRuleFullName()}),p=new Vg(h,l,this.LA(0));p.resyncedTokens=Gs(a),this.SAVE_ERROR(p)};for(;!c;)if(this.tokenMatcher(u,i)){f();return}else if(r.call(this)){f(),e.apply(this,n);return}else this.tokenMatcher(u,s)?c=!0:(u=this.SKIP_TOKEN(),this.addToResyncTokens(u,a));this.importLexerState(o)}shouldInRepetitionRecoveryBeTried(e,n,r){return!(r===!1||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,n)))}getFollowsForInRuleRecovery(e,n){const r=this.getCurrentGrammarPath(e,n);return this.getNextPossibleTokenTypes(r)}tryInRuleRecovery(e,n){if(this.canRecoverWithSingleTokenInsertion(e,n))return this.getTokenToInsert(e);if(this.canRecoverWithSingleTokenDeletion(e)){const r=this.SKIP_TOKEN();return this.consumeToken(),r}throw new gO("sad sad panda")}canPerformInRuleRecovery(e,n){return this.canRecoverWithSingleTokenInsertion(e,n)||this.canRecoverWithSingleTokenDeletion(e)}canRecoverWithSingleTokenInsertion(e,n){if(!this.canTokenTypeBeInsertedInRecovery(e)||qe(n))return!1;const r=this.LA(1);return qi(n,s=>this.tokenMatcher(r,s))!==void 0}canRecoverWithSingleTokenDeletion(e){return this.canTokenTypeBeDeletedInRecovery(e)?this.tokenMatcher(this.LA(2),e):!1}isInCurrentRuleReSyncSet(e){const n=this.getCurrFollowKey(),r=this.getFollowSetFromFollowKey(n);return $t(r,e)}findReSyncTokenType(){const e=this.flattenFollowSet();let n=this.LA(1),r=2;for(;;){const i=qi(e,s=>MI(n,s));if(i!==void 0)return i;n=this.LA(r),r++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return Uu;const e=this.getLastExplicitRuleShortName(),n=this.getLastExplicitRuleOccurrenceIndex(),r=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:n,inRule:this.shortRuleNameToFullName(r)}}buildFullFollowKeyStack(){const e=this.RULE_STACK,n=this.RULE_OCCURRENCE_STACK;return ce(e,(r,i)=>i===0?Uu:{ruleName:this.shortRuleNameToFullName(r),idxInCallingRule:n[i],inRule:this.shortRuleNameToFullName(e[i-1])})}flattenFollowSet(){const e=ce(this.buildFullFollowKeyStack(),n=>this.getFollowSetFromFollowKey(n));return sn(e)}getFollowSetFromFollowKey(e){if(e===Uu)return[yi];const n=e.ruleName+e.idxInCallingRule+sg+e.inRule;return this.resyncFollows[n]}addToResyncTokens(e,n){return this.tokenMatcher(e,yi)||n.push(e),n}reSyncTo(e){const n=[];let r=this.LA(1);for(;this.tokenMatcher(r,e)===!1;)r=this.SKIP_TOKEN(),this.addToResyncTokens(r,n);return Gs(n)}attemptInRepetitionRecovery(e,n,r,i,s,o,a){}getCurrentGrammarPath(e,n){const r=this.getHumanReadableRuleStack(),i=Ct(this.RULE_OCCURRENCE_STACK);return{ruleStack:r,occurrenceStack:i,lastTok:e,lastTokOccurrence:n}}getHumanReadableRuleStack(){return ce(this.RULE_STACK,e=>this.shortRuleNameToFullName(e))}}function _O(t,e,n,r,i,s,o){const a=this.getKeyForAutomaticLookahead(r,i);let c=this.firstAfterRepMap[a];if(c===void 0){const d=this.getCurrRuleFullName(),h=this.getGAstProductions()[d];c=new s(h,i).startWalking(),this.firstAfterRepMap[a]=c}let l=c.token,u=c.occurrence;const f=c.isEndOfRule;this.RULE_STACK.length===1&&f&&l===void 0&&(l=yi,u=1),!(l===void 0||u===void 0)&&this.shouldInRepetitionRecoveryBeTried(l,u,o)&&this.tryInRepetitionRecovery(t,e,n,l)}const bO=4,Gr=8,qg=1<$g(n,n,_i))}validateEmptyOrAlternatives(e){return gn(e,n=>rO(n,_i))}validateAmbiguousAlternationAlternatives(e,n){return gn(e,r=>iO(r,n,_i))}validateSomeNonEmptyLookaheadPath(e,n){return aO(e,n,_i)}buildLookaheadForAlternation(e){return WI(e.prodOccurrence,e.rule,e.maxLookahead,e.hasPredicates,e.dynamicTokensEnabled,HI)}buildLookaheadForOptional(e){return GI(e.prodOccurrence,e.rule,e.maxLookahead,e.dynamicTokensEnabled,Mg(e.prodType),VI)}}class vO{initLooksAhead(e){this.dynamicTokensEnabled=pe(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:kr.dynamicTokensEnabled,this.maxLookahead=pe(e,"maxLookahead")?e.maxLookahead:kr.maxLookahead,this.lookaheadStrategy=pe(e,"lookaheadStrategy")?e.lookaheadStrategy:new wO({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(e){me(e,n=>{this.TRACE_INIT(`${n.name} Rule Lookahead`,()=>{const{alternation:r,repetition:i,option:s,repetitionMandatory:o,repetitionMandatoryWithSeparator:a,repetitionWithSeparator:c}=kO(n);me(r,l=>{const u=l.idx===0?"":l.idx;this.TRACE_INIT(`${Yn(l)}${u}`,()=>{const f=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:l.idx,rule:n,maxLookahead:l.maxLookahead||this.maxLookahead,hasPredicates:l.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),d=Fu(this.fullRuleNameToShort[n.name],qg,l.idx);this.setLaFuncCache(d,f)})}),me(i,l=>{this.computeLookaheadFunc(n,l.idx,Pu,"Repetition",l.maxLookahead,Yn(l))}),me(s,l=>{this.computeLookaheadFunc(n,l.idx,Jg,"Option",l.maxLookahead,Yn(l))}),me(o,l=>{this.computeLookaheadFunc(n,l.idx,Du,"RepetitionMandatory",l.maxLookahead,Yn(l))}),me(a,l=>{this.computeLookaheadFunc(n,l.idx,Ka,"RepetitionMandatoryWithSeparator",l.maxLookahead,Yn(l))}),me(c,l=>{this.computeLookaheadFunc(n,l.idx,Bu,"RepetitionWithSeparator",l.maxLookahead,Yn(l))})})})}computeLookaheadFunc(e,n,r,i,s,o){this.TRACE_INIT(`${o}${n===0?"":n}`,()=>{const a=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:n,rule:e,maxLookahead:s||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:i}),c=Fu(this.fullRuleNameToShort[e.name],r,n);this.setLaFuncCache(c,a)})}getKeyForAutomaticLookahead(e,n){const r=this.getLastExplicitRuleShortName();return Fu(r,e,n)}getLaFuncFromCache(e){return this.lookAheadFuncsCache.get(e)}setLaFuncCache(e,n){this.lookAheadFuncsCache.set(e,n)}}class EO extends mi{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(e){this.dslMethods.option.push(e)}visitRepetitionWithSeparator(e){this.dslMethods.repetitionWithSeparator.push(e)}visitRepetitionMandatory(e){this.dslMethods.repetitionMandatory.push(e)}visitRepetitionMandatoryWithSeparator(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)}visitRepetition(e){this.dslMethods.repetition.push(e)}visitAlternation(e){this.dslMethods.alternation.push(e)}}const qa=new EO;function kO(t){qa.reset(),t.accept(qa);const e=qa.dslMethods;return qa.reset(),e}function Xg(t,e){isNaN(t.startOffset)===!0?(t.startOffset=e.startOffset,t.endOffset=e.endOffset):t.endOffseto.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: + ${s.join(` + +`).replace(/\n/g,` + `)}`)}}};return n.prototype=r,n.prototype.constructor=n,n._RULE_NAMES=e,n}function IO(t,e,n){const r=function(){};Yg(r,t+"BaseSemanticsWithDefaults");const i=Object.create(n.prototype);return me(e,s=>{i[s]=xO}),r.prototype=i,r.prototype.constructor=r,r}var $u;(function(t){t[t.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",t[t.MISSING_METHOD=1]="MISSING_METHOD"})($u||($u={}));function OO(t,e){return NO(t,e)}function NO(t,e){const n=mn(e,i=>_r(t[i])===!1),r=ce(n,i=>({msg:`Missing visitor method: <${i}> on ${t.constructor.name} CST Visitor.`,type:$u.MISSING_METHOD,methodName:i}));return Ws(r)}class CO{initTreeBuilder(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=pe(e,"nodeLocationTracking")?e.nodeLocationTracking:kr.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=wt,this.cstFinallyStateUpdate=wt,this.cstPostTerminal=wt,this.cstPostNonTerminal=wt,this.cstPostRule=wt;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Zg,this.setNodeLocationFromNode=Zg,this.cstPostRule=wt,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=wt,this.setNodeLocationFromNode=wt,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Xg,this.setNodeLocationFromNode=Xg,this.cstPostRule=wt,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=wt,this.setNodeLocationFromNode=wt,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=wt,this.setNodeLocationFromNode=wt,this.cstPostRule=wt,this.setInitialNodeLocation=wt;else throw Error(`Invalid config option: "${e.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(e){e.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(e){const n=this.LA(1);e.location={startOffset:n.startOffset,startLine:n.startLine,startColumn:n.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(e){const n={name:e,children:Object.create(null)};this.setInitialNodeLocation(n),this.CST_STACK.push(n)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(e){const n=this.LA(0),r=e.location;r.startOffset<=n.startOffset?(r.endOffset=n.endOffset,r.endLine=n.endLine,r.endColumn=n.endColumn):(r.startOffset=NaN,r.startLine=NaN,r.startColumn=NaN)}cstPostRuleOnlyOffset(e){const n=this.LA(0),r=e.location;r.startOffset<=n.startOffset?r.endOffset=n.endOffset:r.startOffset=NaN}cstPostTerminal(e,n){const r=this.CST_STACK[this.CST_STACK.length-1];SO(r,n,e),this.setNodeLocationFromToken(r.location,n)}cstPostNonTerminal(e,n){const r=this.CST_STACK[this.CST_STACK.length-1];AO(r,n,e),this.setNodeLocationFromNode(r.location,e.location)}getBaseCstVisitorConstructor(){if(Er(this.baseCstVisitorConstructor)){const e=RO(this.className,dn(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(Er(this.baseCstVisitorWithDefaultsConstructor)){const e=IO(this.className,dn(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){const e=this.RULE_STACK;return e[e.length-1]}getPreviousExplicitRuleShortName(){const e=this.RULE_STACK;return e[e.length-2]}getLastExplicitRuleOccurrenceIndex(){const e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]}}class LO{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(e){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):Za}LA(e){const n=this.currIdx+e;return n<0||this.tokVectorLength<=n?Za:this.tokVector[n]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(e){this.currIdx=e}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}}class MO{ACTION(e){return e.call(this)}consume(e,n,r){return this.consumeInternal(n,e,r)}subrule(e,n,r){return this.subruleInternal(n,e,r)}option(e,n){return this.optionInternal(n,e)}or(e,n){return this.orInternal(n,e)}many(e,n){return this.manyInternal(e,n)}atLeastOne(e,n){return this.atLeastOneInternal(e,n)}CONSUME(e,n){return this.consumeInternal(e,0,n)}CONSUME1(e,n){return this.consumeInternal(e,1,n)}CONSUME2(e,n){return this.consumeInternal(e,2,n)}CONSUME3(e,n){return this.consumeInternal(e,3,n)}CONSUME4(e,n){return this.consumeInternal(e,4,n)}CONSUME5(e,n){return this.consumeInternal(e,5,n)}CONSUME6(e,n){return this.consumeInternal(e,6,n)}CONSUME7(e,n){return this.consumeInternal(e,7,n)}CONSUME8(e,n){return this.consumeInternal(e,8,n)}CONSUME9(e,n){return this.consumeInternal(e,9,n)}SUBRULE(e,n){return this.subruleInternal(e,0,n)}SUBRULE1(e,n){return this.subruleInternal(e,1,n)}SUBRULE2(e,n){return this.subruleInternal(e,2,n)}SUBRULE3(e,n){return this.subruleInternal(e,3,n)}SUBRULE4(e,n){return this.subruleInternal(e,4,n)}SUBRULE5(e,n){return this.subruleInternal(e,5,n)}SUBRULE6(e,n){return this.subruleInternal(e,6,n)}SUBRULE7(e,n){return this.subruleInternal(e,7,n)}SUBRULE8(e,n){return this.subruleInternal(e,8,n)}SUBRULE9(e,n){return this.subruleInternal(e,9,n)}OPTION(e){return this.optionInternal(e,0)}OPTION1(e){return this.optionInternal(e,1)}OPTION2(e){return this.optionInternal(e,2)}OPTION3(e){return this.optionInternal(e,3)}OPTION4(e){return this.optionInternal(e,4)}OPTION5(e){return this.optionInternal(e,5)}OPTION6(e){return this.optionInternal(e,6)}OPTION7(e){return this.optionInternal(e,7)}OPTION8(e){return this.optionInternal(e,8)}OPTION9(e){return this.optionInternal(e,9)}OR(e){return this.orInternal(e,0)}OR1(e){return this.orInternal(e,1)}OR2(e){return this.orInternal(e,2)}OR3(e){return this.orInternal(e,3)}OR4(e){return this.orInternal(e,4)}OR5(e){return this.orInternal(e,5)}OR6(e){return this.orInternal(e,6)}OR7(e){return this.orInternal(e,7)}OR8(e){return this.orInternal(e,8)}OR9(e){return this.orInternal(e,9)}MANY(e){this.manyInternal(0,e)}MANY1(e){this.manyInternal(1,e)}MANY2(e){this.manyInternal(2,e)}MANY3(e){this.manyInternal(3,e)}MANY4(e){this.manyInternal(4,e)}MANY5(e){this.manyInternal(5,e)}MANY6(e){this.manyInternal(6,e)}MANY7(e){this.manyInternal(7,e)}MANY8(e){this.manyInternal(8,e)}MANY9(e){this.manyInternal(9,e)}MANY_SEP(e){this.manySepFirstInternal(0,e)}MANY_SEP1(e){this.manySepFirstInternal(1,e)}MANY_SEP2(e){this.manySepFirstInternal(2,e)}MANY_SEP3(e){this.manySepFirstInternal(3,e)}MANY_SEP4(e){this.manySepFirstInternal(4,e)}MANY_SEP5(e){this.manySepFirstInternal(5,e)}MANY_SEP6(e){this.manySepFirstInternal(6,e)}MANY_SEP7(e){this.manySepFirstInternal(7,e)}MANY_SEP8(e){this.manySepFirstInternal(8,e)}MANY_SEP9(e){this.manySepFirstInternal(9,e)}AT_LEAST_ONE(e){this.atLeastOneInternal(0,e)}AT_LEAST_ONE1(e){return this.atLeastOneInternal(1,e)}AT_LEAST_ONE2(e){this.atLeastOneInternal(2,e)}AT_LEAST_ONE3(e){this.atLeastOneInternal(3,e)}AT_LEAST_ONE4(e){this.atLeastOneInternal(4,e)}AT_LEAST_ONE5(e){this.atLeastOneInternal(5,e)}AT_LEAST_ONE6(e){this.atLeastOneInternal(6,e)}AT_LEAST_ONE7(e){this.atLeastOneInternal(7,e)}AT_LEAST_ONE8(e){this.atLeastOneInternal(8,e)}AT_LEAST_ONE9(e){this.atLeastOneInternal(9,e)}AT_LEAST_ONE_SEP(e){this.atLeastOneSepFirstInternal(0,e)}AT_LEAST_ONE_SEP1(e){this.atLeastOneSepFirstInternal(1,e)}AT_LEAST_ONE_SEP2(e){this.atLeastOneSepFirstInternal(2,e)}AT_LEAST_ONE_SEP3(e){this.atLeastOneSepFirstInternal(3,e)}AT_LEAST_ONE_SEP4(e){this.atLeastOneSepFirstInternal(4,e)}AT_LEAST_ONE_SEP5(e){this.atLeastOneSepFirstInternal(5,e)}AT_LEAST_ONE_SEP6(e){this.atLeastOneSepFirstInternal(6,e)}AT_LEAST_ONE_SEP7(e){this.atLeastOneSepFirstInternal(7,e)}AT_LEAST_ONE_SEP8(e){this.atLeastOneSepFirstInternal(8,e)}AT_LEAST_ONE_SEP9(e){this.atLeastOneSepFirstInternal(9,e)}RULE(e,n,r=Ya){if($t(this.definedRulesNames,e)){const o={message:_i.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),type:jt.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(o)}this.definedRulesNames.push(e);const i=this.defineRule(e,n,r);return this[e]=i,i}OVERRIDE_RULE(e,n,r=Ya){const i=nO(e,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(i);const s=this.defineRule(e,n,r);return this[e]=s,s}BACKTRACK(e,n){return function(){this.isBackTrackingStack.push(1);const r=this.saveRecogState();try{return e.apply(this,n),!0}catch(i){if(Ha(i))return!1;throw i}finally{this.reloadRecogState(r),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return PR(dt(this.gastProductionsCache))}}class UO{initRecognizerEngine(e,n){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=ja,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},pe(n,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 + For Further details.`);if(Me(e)){if(qe(e))throw Error(`A Token Vocabulary cannot be empty. + Note that the first argument for the parser constructor + is no longer a Token vector (since v4.0).`);if(typeof e[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 + For Further details.`)}if(Me(e))this.tokensMap=Jt(e,(s,o)=>(s[o.name]=o,s),{});else if(pe(e,"modes")&&In(sn(dt(e.modes)),OI)){const s=sn(dt(e.modes)),o=Ra(s);this.tokensMap=Jt(o,(a,c)=>(a[c.name]=c,a),{})}else if(hn(e))this.tokensMap=Ct(e);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=yi;const r=pe(e,"modes")?sn(dt(e.modes)):dt(e),i=In(r,s=>qe(s.categoryMatches));this.tokenMatcher=i?ja:Js,Xs(dt(this.tokensMap))}defineRule(e,n,r){if(this.selfAnalysisDone)throw Error(`Grammar rule <${e}> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);const i=pe(r,"resyncEnabled")?r.resyncEnabled:Ya.resyncEnabled,s=pe(r,"recoveryValueFunc")?r.recoveryValueFunc:Ya.recoveryValueFunc,o=this.ruleShortNameIdx<o.call(this)&&a.call(this)}}else s=e;if(i.call(this)===!0)return s.call(this)}atLeastOneInternal(e,n){const r=this.getKeyForAutomaticLookahead(Du,e);return this.atLeastOneInternalLogic(e,n,r)}atLeastOneInternalLogic(e,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const o=n.GATE;if(o!==void 0){const a=i;i=()=>o.call(this)&&a.call(this)}}else s=n;if(i.call(this)===!0){let o=this.doSingleRepetition(s);for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s)}else throw this.raiseEarlyExitException(e,ct.REPETITION_MANDATORY,n.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[e,n],i,Du,e,jI)}atLeastOneSepFirstInternal(e,n){const r=this.getKeyForAutomaticLookahead(Ka,e);this.atLeastOneSepFirstInternalLogic(e,n,r)}atLeastOneSepFirstInternalLogic(e,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,a,i,Cg],a,Ka,e,Cg)}else throw this.raiseEarlyExitException(e,ct.REPETITION_MANDATORY_WITH_SEPARATOR,n.ERR_MSG)}manyInternal(e,n){const r=this.getKeyForAutomaticLookahead(Pu,e);return this.manyInternalLogic(e,n,r)}manyInternalLogic(e,n,r){let i=this.getLaFuncFromCache(r),s;if(typeof n!="function"){s=n.DEF;const a=n.GATE;if(a!==void 0){const c=i;i=()=>a.call(this)&&c.call(this)}}else s=n;let o=!0;for(;i.call(this)===!0&&o===!0;)o=this.doSingleRepetition(s);this.attemptInRepetitionRecovery(this.manyInternal,[e,n],i,Pu,e,$I,o)}manySepFirstInternal(e,n){const r=this.getKeyForAutomaticLookahead(Bu,e);this.manySepFirstInternalLogic(e,n,r)}manySepFirstInternalLogic(e,n,r){const i=n.DEF,s=n.SEP;if(this.getLaFuncFromCache(r).call(this)===!0){i.call(this);const a=()=>this.tokenMatcher(this.LA(1),s);for(;this.tokenMatcher(this.LA(1),s)===!0;)this.CONSUME(s),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,s,a,i,Ng],a,Bu,e,Ng)}}repetitionSepSecondInternal(e,n,r,i,s){for(;r();)this.CONSUME(n),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,n,r,i,s],r,Ka,e,s)}doSingleRepetition(e){const n=this.getLexerPosition();return e.call(this),this.getLexerPosition()>n}orInternal(e,n){const r=this.getKeyForAutomaticLookahead(qg,n),i=Me(e)?e:e.DEF,o=this.getLaFuncFromCache(r).call(this,i);if(o!==void 0)return i[o].ALT.call(this);this.raiseNoAltException(n,e.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){const e=this.LA(1),n=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new pO(n,e))}}subruleInternal(e,n,r){let i;try{const s=r!==void 0?r.ARGS:void 0;return this.subruleIdx=n,i=e.apply(this,s),this.cstPostNonTerminal(i,r!==void 0&&r.LABEL!==void 0?r.LABEL:e.ruleName),i}catch(s){throw this.subruleInternalError(s,r,e.ruleName)}}subruleInternalError(e,n,r){throw Ha(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,n!==void 0&&n.LABEL!==void 0?n.LABEL:r),delete e.partialCstResult),e}consumeInternal(e,n,r){let i;try{const s=this.LA(1);this.tokenMatcher(s,e)===!0?(this.consumeToken(),i=s):this.consumeInternalError(e,s,r)}catch(s){i=this.consumeInternalRecovery(e,n,s)}return this.cstPostTerminal(r!==void 0&&r.LABEL!==void 0?r.LABEL:e.name,i),i}consumeInternalError(e,n,r){let i;const s=this.LA(0);throw r!==void 0&&r.ERR_MSG?i=r.ERR_MSG:i=this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:n,previous:s,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new Vg(i,n,s))}consumeInternalRecovery(e,n,r){if(this.recoveryEnabled&&r.name==="MismatchedTokenException"&&!this.isBackTracking()){const i=this.getFollowsForInRuleRecovery(e,n);try{return this.tryInRuleRecovery(e,i)}catch(s){throw s.name===Kg?r:s}}else throw r}saveRecogState(){const e=this.errors,n=Ct(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:n,CST_STACK:this.CST_STACK}}reloadRecogState(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK}ruleInvocationStateUpdate(e,n,r){this.RULE_OCCURRENCE_STACK.push(r),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(n)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){const e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]}shortRuleNameToFullName(e){return this.shortRuleNameToFull[e]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),yi)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}}class PO{initErrorHandler(e){this._errors=[],this.errorMessageProvider=pe(e,"errorMessageProvider")?e.errorMessageProvider:kr.errorMessageProvider}SAVE_ERROR(e){if(Ha(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:Ct(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return Ct(this._errors)}set errors(e){this._errors=e}raiseEarlyExitException(e,n,r){const i=this.getCurrRuleFullName(),s=this.getGAstProductions()[i],a=Cu(e,s,n,this.maxLookahead)[0],c=[];for(let u=1;u<=this.maxLookahead;u++)c.push(this.LA(u));const l=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:c,previous:this.LA(0),customUserDescription:r,ruleName:i});throw this.SAVE_ERROR(new mO(l,this.LA(1),this.LA(0)))}raiseNoAltException(e,n){const r=this.getCurrRuleFullName(),i=this.getGAstProductions()[r],s=Nu(e,i,this.maxLookahead),o=[];for(let l=1;l<=this.maxLookahead;l++)o.push(this.LA(l));const a=this.LA(0),c=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:s,actual:o,previous:a,customUserDescription:n,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new dO(c,this.LA(1),a))}}class DO{initContentAssist(){}computeContentAssist(e,n){const r=this.gastProductionsCache[e];if(Er(r))throw Error(`Rule ->${e}<- does not exist in this grammar.`);return Lg([r],n,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(e){const n=On(e.ruleStack),i=this.getGAstProductions()[n];return new FI(i,e).startWalking()}}const Ja={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(Ja);const Qg=!0,e0=Math.pow(2,Gr)-1,t0=on({name:"RECORDING_PHASE_TOKEN",pattern:Et.NA});Xs([t0]);const n0=za(t0,`This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(n0);const BO={name:`This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}};class FO{initGastRecorder(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let e=0;e<10;e++){const n=e>0?e:"";this[`CONSUME${n}`]=function(r,i){return this.consumeInternalRecord(r,e,i)},this[`SUBRULE${n}`]=function(r,i){return this.subruleInternalRecord(r,e,i)},this[`OPTION${n}`]=function(r){return this.optionInternalRecord(r,e)},this[`OR${n}`]=function(r){return this.orInternalRecord(r,e)},this[`MANY${n}`]=function(r){this.manyInternalRecord(e,r)},this[`MANY_SEP${n}`]=function(r){this.manySepFirstInternalRecord(e,r)},this[`AT_LEAST_ONE${n}`]=function(r){this.atLeastOneInternalRecord(e,r)},this[`AT_LEAST_ONE_SEP${n}`]=function(r){this.atLeastOneSepFirstInternalRecord(e,r)}}this.consume=function(e,n,r){return this.consumeInternalRecord(n,e,r)},this.subrule=function(e,n,r){return this.subruleInternalRecord(n,e,r)},this.option=function(e,n){return this.optionInternalRecord(n,e)},this.or=function(e,n){return this.orInternalRecord(n,e)},this.many=function(e,n){this.manyInternalRecord(e,n)},this.atLeastOne=function(e,n){this.atLeastOneInternalRecord(e,n)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{const e=this;for(let n=0;n<10;n++){const r=n>0?n:"";delete e[`CONSUME${r}`],delete e[`SUBRULE${r}`],delete e[`OPTION${r}`],delete e[`OR${r}`],delete e[`MANY${r}`],delete e[`MANY_SEP${r}`],delete e[`AT_LEAST_ONE${r}`],delete e[`AT_LEAST_ONE_SEP${r}`]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA})}ACTION_RECORD(e){}BACKTRACK_RECORD(e,n){return()=>!0}LA_RECORD(e){return Za}topLevelRuleRecord(e,n){try{const r=new Ji({definition:[],name:e});return r.name=e,this.recordingProdStack.push(r),n.call(this),this.recordingProdStack.pop(),r}catch(r){if(r.KNOWN_RECORDER_ERROR!==!0)try{r.message=r.message+` + This error was thrown during the "grammar recording phase" For more info see: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw r}throw r}}optionInternalRecord(e,n){return Qs.call(this,Yt,e,n)}atLeastOneInternalRecord(e,n){Qs.call(this,Xn,n,e)}atLeastOneSepFirstInternalRecord(e,n){Qs.call(this,Zn,n,e,Qg)}manyInternalRecord(e,n){Qs.call(this,vt,n,e)}manySepFirstInternalRecord(e,n){Qs.call(this,Cn,n,e,Qg)}orInternalRecord(e,n){return $O.call(this,e,n)}subruleInternalRecord(e,n,r){if(Xa(n),!e||pe(e,"ruleName")===!1){const a=new Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw a.KNOWN_RECORDER_ERROR=!0,a}const i=Ki(this.recordingProdStack),s=e.ruleName,o=new Xt({idx:n,nonTerminalName:s,label:r==null?void 0:r.LABEL,referencedRule:void 0});return i.definition.push(o),this.outputCst?BO:Ja}consumeInternalRecord(e,n,r){if(Xa(n),!bg(e)){const o=new Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw o.KNOWN_RECORDER_ERROR=!0,o}const i=Ki(this.recordingProdStack),s=new nt({idx:n,terminalType:e,label:r==null?void 0:r.LABEL});return i.definition.push(s),n0}}function Qs(t,e,n,r=!1){Xa(n);const i=Ki(this.recordingProdStack),s=_r(e)?e:e.DEF,o=new t({definition:[],idx:n});return r&&(o.separator=e.SEP),pe(e,"MAX_LOOKAHEAD")&&(o.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(o),s.call(this),i.definition.push(o),this.recordingProdStack.pop(),Ja}function $O(t,e){Xa(e);const n=Ki(this.recordingProdStack),r=Me(t)===!1,i=r===!1?t:t.DEF,s=new Ln({definition:[],idx:e,ignoreAmbiguities:r&&t.IGNORE_AMBIGUITIES===!0});pe(t,"MAX_LOOKAHEAD")&&(s.maxLookahead=t.MAX_LOOKAHEAD);const o=vu(i,a=>_r(a.GATE));return s.hasPredicates=o,n.definition.push(s),me(i,a=>{const c=new Zt({definition:[]});s.definition.push(c),pe(a,"IGNORE_AMBIGUITIES")?c.ignoreAmbiguities=a.IGNORE_AMBIGUITIES:pe(a,"GATE")&&(c.ignoreAmbiguities=!0),this.recordingProdStack.push(c),a.ALT.call(this),this.recordingProdStack.pop()}),Ja}function r0(t){return t===0?"":`${t}`}function Xa(t){if(t<0||t>e0){const e=new Error(`Invalid DSL Method idx value: <${t}> + Idx value must be a none negative value smaller than ${e0+1}`);throw e.KNOWN_RECORDER_ERROR=!0,e}}class jO{initPerformanceTracer(e){if(pe(e,"traceInitPerf")){const n=e.traceInitPerf,r=typeof n=="number";this.traceInitMaxIdent=r?n:1/0,this.traceInitPerf=r?n>0:n}else this.traceInitMaxIdent=0,this.traceInitPerf=kr.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(e,n){if(this.traceInitPerf===!0){this.traceInitIndent++;const r=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${e}>`);const{time:i,value:s}=ng(n),o=i>10?console.warn:console.log;return this.traceInitIndent time: ${i}ms`),this.traceInitIndent--,s}else return n()}}function zO(t,e){e.forEach(n=>{const r=n.prototype;Object.getOwnPropertyNames(r).forEach(i=>{if(i==="constructor")return;const s=Object.getOwnPropertyDescriptor(r,i);s&&(s.get||s.set)?Object.defineProperty(t.prototype,i,s):t.prototype[i]=n.prototype[i]})})}const Za=za(yi,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(Za);const kr=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:Og,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),Ya=Object.freeze({recoveryValueFunc:()=>{},resyncEnabled:!0});var jt;(function(t){t[t.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",t[t.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",t[t.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",t[t.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",t[t.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",t[t.LEFT_RECURSION=5]="LEFT_RECURSION",t[t.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",t[t.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",t[t.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",t[t.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",t[t.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",t[t.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",t[t.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",t[t.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(jt||(jt={}));class eo{static performSelfAnalysis(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let e;this.selfAnalysisDone=!0;const n=this.className;this.TRACE_INIT("toFastProps",()=>{rg(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),me(this.definedRulesNames,i=>{const o=this[i].originalGrammarAction;let a;this.TRACE_INIT(`${i} Rule`,()=>{a=this.topLevelRuleRecord(i,o)}),this.gastProductionsCache[i]=a})}finally{this.disableRecording()}});let r=[];if(this.TRACE_INIT("Grammar Resolving",()=>{r=fO({rules:dt(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(r)}),this.TRACE_INIT("Grammar Validations",()=>{if(qe(r)&&this.skipValidations===!1){const i=hO({rules:dt(this.gastProductionsCache),tokenTypes:dt(this.tokensMap),errMsgProvider:_i,grammarName:n}),s=XI({lookaheadStrategy:this.lookaheadStrategy,rules:dt(this.gastProductionsCache),tokenTypes:dt(this.tokensMap),grammarName:n});this.definitionErrors=this.definitionErrors.concat(i,s)}}),qe(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{const i=WR(dt(this.gastProductionsCache));this.resyncFollows=i}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var i,s;(s=(i=this.lookaheadStrategy).initialize)===null||s===void 0||s.call(i,{rules:dt(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(dt(this.gastProductionsCache))})),!eo.DEFER_DEFINITION_ERRORS_HANDLING&&!qe(this.definitionErrors))throw e=ce(this.definitionErrors,i=>i.message),new Error(`Parser Definition Errors detected: + ${e.join(` +------------------------------- +`)}`)})}constructor(e,n){this.definitionErrors=[],this.selfAnalysisDone=!1;const r=this;if(r.initErrorHandler(n),r.initLexerAdapter(),r.initLooksAhead(n),r.initRecognizerEngine(e,n),r.initRecoverable(n),r.initTreeBuilder(n),r.initContentAssist(),r.initGastRecorder(n),r.initPerformanceTracer(n),pe(n,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. + Please use the flag on the relevant DSL method instead. + See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES + For further details.`);this.skipValidations=pe(n,"skipValidations")?n.skipValidations:kr.skipValidations}}eo.DEFER_DEFINITION_ERRORS_HANDLING=!1,zO(eo,[yO,vO,CO,LO,UO,MO,PO,DO,FO,jO]);class WO extends eo{constructor(e,n=kr){const r=Ct(n);r.outputCst=!0,super(e,r)}}function GO(t){const e=new HO,n=dt(t);return ce(n,r=>e.visitRule(r))}class HO extends mi{visitRule(e){const n=this.visitEach(e.definition),r=Ym(n,s=>s.propertyName),i=ce(r,(s,o)=>{const a=!vu(s,l=>!l.canBeNull);let c=s[0].type;return s.length>1&&(c=ce(s,l=>l.type)),{name:o,type:c,optional:a}});return{name:e.name,properties:i}}visitAlternative(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitOption(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitRepetition(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitRepetitionMandatory(e){return this.visitEach(e.definition)}visitRepetitionMandatoryWithSeparator(e){return this.visitEach(e.definition).concat({propertyName:e.separator.name,canBeNull:!0,type:Qa(e.separator)})}visitRepetitionWithSeparator(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0}).concat({propertyName:e.separator.name,canBeNull:!0,type:Qa(e.separator)})}visitAlternation(e){return this.visitEachAndOverrideWith(e.definition,{canBeNull:!0})}visitTerminal(e){return[{propertyName:e.label||e.terminalType.name,canBeNull:!1,type:Qa(e)}]}visitNonTerminal(e){return[{propertyName:e.label||e.nonTerminalName,canBeNull:!1,type:Qa(e)}]}visitEachAndOverrideWith(e,n){return ce(this.visitEach(e),r=>Kt({},r,n))}visitEach(e){return sn(ce(e,n=>this.visit(n)))}}function Qa(t){return t instanceof Xt?{kind:"rule",name:t.referencedRule.name}:{kind:"token"}}function VO(t,e){let n=[];return n=n.concat('import type { CstNode, ICstVisitor, IToken } from "chevrotain";'),n=n.concat(sn(ce(t,r=>KO(r)))),e.includeVisitorInterface&&(n=n.concat(ZO(e.visitorInterfaceName,t))),n.join(` + +`)+` +`}function KO(t){const e=qO(t),n=JO(t);return[e,n]}function qO(t){const e=s0(t.name),n=ju(t.name);return`export interface ${e} extends CstNode { + name: "${t.name}"; + children: ${n}; +}`}function JO(t){return`export type ${ju(t.name)} = { + ${ce(t.properties,n=>XO(n)).join(` + `)} +};`}function XO(t){const e=QO(t.type);return`${t.name}${t.optional?"?":""}: ${e}[];`}function ZO(t,e){return`export interface ${t} extends ICstVisitor { + ${ce(e,n=>YO(n)).join(` + `)} +}`}function YO(t){const e=ju(t.name);return`${t.name}(children: ${e}, param?: IN): OUT;`}function QO(t){if(Me(t)){const e=Ra(ce(t,r=>i0(r)));return"("+Jt(e,(r,i)=>r+" | "+i)+")"}else return i0(t)}function i0(t){return t.kind==="token"?"IToken":s0(t.name)}function s0(t){return wm(t)+"CstNode"}function ju(t){return wm(t)+"CstChildren"}const eN={includeVisitorInterface:!0,visitorInterfaceName:"ICstNodeVisitor"};function tN(t,e){const n=Object.assign(Object.assign({},eN),e),r=GO(t);return VO(r,n)}const Qn=!!JSON.parse("false"),nN=!!JSON.parse("false");JSON.parse("false");const rN=!!JSON.parse("false");JSON.parse("false"),JSON.parse("false");const zu=Hl(32,126).map(t=>String.fromCharCode(t));function Ie(t){return on({...t,name:`token_${t.name}`})}function yn(t,e=!1){return Ie(e?{name:t,pattern:new RegExp(t.toLowerCase(),"i"),longer_alt:zt,group:Et.SKIPPED}:{name:t,pattern:new RegExp(t.toLowerCase(),"i"),longer_alt:zt})}const to=Ie({name:"newline",line_breaks:!0,start_chars_hint:[` +`,"\r"],pattern:/\n|\r\n?/}),iN=Ie({name:"whitespace",pattern:/ +/,group:Et.SKIPPED}),sN=Ie({name:"whitespace",pattern:/\s+/,line_breaks:!0,group:Et.SKIPPED}),Wu=Ie({name:"stat",pattern:/@.*/,start_chars_hint:["@"]}),Zi=Ie({name:"command",pattern:/#/,start_chars_hint:["#"]});let o0=!1;function oN(t,e,n){if(!o0)return null;const[r]=n.slice(-1);if(r&&r.tokenType!==to)return null;let i=e;for(;t[i]===" ";)i++;if("@#/?':!".includes(t[i]))return null;let s=e+1;for(;s"@#/?':!".includes(t)===!1)}),c0=Ie({name:"comment",pattern:/'.*/,start_chars_hint:["'"]}),l0=Ie({name:"label",pattern:/:[^;:\n]*/,start_chars_hint:[":"]}),u0=Ie({name:"hyperlink",pattern:/!/,start_chars_hint:["!"]}),f0=Ie({name:"hyperlinktext",pattern:/;[^;\n]*/,start_chars_hint:[";"]}),zt=Ie({name:"stringliteral",pattern:/[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/,start_chars_hint:zu}),h0=Ie({name:"stringliteraldouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),d0=Ie({name:"numberliteral",pattern:/-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?/}),p0=Ie({name:"iseq",pattern:/=|is|eq|equal/,longer_alt:zt}),m0=Ie({name:"isnoteq",pattern:/!=|not ?eq|not ?equal/,longer_alt:zt}),g0=Ie({name:"islessthan",pattern:/<|below/,longer_alt:zt}),y0=Ie({name:"isgreaterthan",pattern:/>|above/,longer_alt:zt}),_0=Ie({name:"islessthanorequal",pattern:/<=|below ?or ?eq|below ?or ?equal/,longer_alt:zt}),b0=Ie({name:"isgreaterthanorequal",pattern:/>=|above ?or ?eq|above ?or ?equal/,longer_alt:zt}),Gu=Ie({name:"or",pattern:/or/i,longer_alt:zt}),Hu=Ie({name:"not",pattern:/not/i,longer_alt:zt}),Vu=Ie({name:"and",pattern:/and/i,longer_alt:zt}),Ku=Ie({name:"plus",pattern:/\+/}),qu=Ie({name:"minus",pattern:/-/}),w0=Ie({name:"power",pattern:/\*\*/}),v0=Ie({name:"multiply",pattern:/\*/}),Ju=Ie({name:"divide",pattern:/\//}),E0=Ie({name:"moddivide",pattern:/%/}),k0=Ie({name:"floordivide",pattern:/%%/}),S0=Ie({name:"query",pattern:/\?/}),A0=Ie({name:"lparen",pattern:/\(/,push_mode:"ignore_newlines"}),T0=Ie({name:"rparen",pattern:/\)/,pop_mode:!0}),x0=Ie({name:"command_play",pattern:/(play|bgplay) .*/,start_chars_hint:zu,longer_alt:zt}),R0=yn("debugger"),Xu=yn("if"),ec=yn("do"),aN=yn("to",!0),Zu=yn("done"),cN=yn("then",!0),Yu=yn("else"),I0=yn("while"),O0=yn("repeat"),N0=yn("waitfor"),C0=Ie({name:"foreach",pattern:/foreach|for/,longer_alt:zt}),L0=yn("break"),M0=yn("continue");function U0(t){return[...t,d0,p0,m0,_0,g0,b0,y0,Gu,Hu,Vu,Ku,qu,w0,v0,Ju,k0,E0,S0,A0,T0,h0,zt]}const P0=U0([a0,Wu,x0,Zi,c0,l0,u0,f0,to,iN,L0,M0,R0,Zu,ec,Yu,C0,Xu,O0,cN,aN,N0,I0]),lN=new Et({defaultMode:"use_newlines",modes:{use_newlines:P0,ignore_newlines:U0([sN])}},{skipValidations:!Qn,ensureOptimizations:Qn});function D0(t){o0=!0;const e=lN.tokenize(t||` +`),[n]=(He(e.tokens)?e.tokens:[]).slice(-1);return n&&n.tokenType.name!=="Newline"&&e.tokens.push(za(to,` +`,n.startOffset,n.endOffset??NaN,n.startLine??NaN,n.endLine??NaN,n.startColumn??NaN,n.endColumn??NaN)),e}function B0(t,e=!0){const[n,...r]=t;switch(Pe(n)){default:return e?{type:fe.OBJECT,values:t}:{type:fe.CONST,values:t};case"loader":return{type:fe.LOADER,values:r};case"board":return{type:fe.BOARD,values:r};case"object":return{type:fe.OBJECT,values:r};case"terrain":return{type:fe.TERRAIN,values:r};case"charset":return{type:fe.CHARSET,values:r};case"palette":return{type:fe.PALETTE,values:r};case"rn":case"range":return{type:fe.RANGE,values:r};case"sl":case"select":return{type:fe.SELECT,values:r};case"nm":case"number":return{type:fe.NUMBER,values:r};case"tx":case"text":return{type:fe.TEXT,values:r};case"ln":case"link":return{type:fe.LINK,values:r};case"hk":case"hotkey":return{type:fe.HOTKEY,values:r};case"scroll":return{type:fe.SCROLL,values:r};case"copyit":return{type:fe.COPYIT,values:r}}}function _n(t){switch(t){case fe.LOADER:return"loader";case fe.BOARD:return"board";case fe.OBJECT:return"object";case fe.TERRAIN:return"terrain";case fe.CHARSET:return"charset";case fe.PALETTE:return"palette";case fe.CONST:return"const";case fe.RANGE:return"range";case fe.SELECT:return"select";case fe.NUMBER:return"number";case fe.TEXT:return"text";case fe.LINK:return"link";case fe.HOTKEY:return"hotkey";case fe.SCROLL:return"scroll";case fe.COPYIT:return"copyit"}}var Qu;try{Qu=new TextDecoder}catch{}var ie,bn,U=0,Je={},Ce,Hr,wn=0,er=0,xt,Sr,Qt=[],Oe,F0={useRecords:!1,mapsAsObjects:!0};class $0{}const j0=new $0;j0.name="MessagePack 0xC1";var Vr=!1,z0=2,W0;try{new Function("")}catch{z0=1/0}class no{constructor(e){e&&(e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.sequential&&e.trusted!==!1&&(e.trusted=!0,!e.structures&&e.useRecords!=!1&&(e.structures=[],e.maxSharedStructures||(e.maxSharedStructures=0))),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType="number")),Object.assign(this,e)}unpack(e,n){if(ie)return ny(()=>(sf(),this?this.unpack(e,n):no.prototype.unpack.call(F0,e,n)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof n=="object"?(bn=n.end||e.length,U=n.start||0):(U=0,bn=n>-1?n:e.length),er=0,Hr=null,xt=null,ie=e;try{Oe=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw ie=null,e instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof no){if(Je=this,this.structures)return Ce=this.structures,tc(n);(!Ce||Ce.length>0)&&(Ce=[])}else Je=F0,(!Ce||Ce.length>0)&&(Ce=[]);return tc(n)}unpackMultiple(e,n){let r,i=0;try{Vr=!0;let s=e.length,o=this?this.unpack(e,s):nc.unpack(e,s);if(n){if(n(o,i,U)===!1)return;for(;Ur.slice(0)));for(let r=0,i=e.length;r=32&&(s.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in n||[])if(r>=0){let i=e[r],s=n[r];s&&(i&&((e.restoreStructures||(e.restoreStructures=[]))[r]=i),e[r]=s)}return this.structures=e}decode(e,n){return this.unpack(e,n)}}function tc(t){try{if(!Je.trusted&&!Vr){let n=Ce.sharedLength||0;n=32&&W0?(e=W0(ie,U,bn,Je),ie=null,!(t&&t.lazy)&&e&&(e=e.toJSON()),U=bn):e=lt(),xt&&(U=xt.postBundlePosition,xt=null),Vr&&(Ce.restoreStructures=null),U==bn)Ce&&Ce.restoreStructures&&G0(),Ce=null,ie=null,Sr&&(Sr=null);else{if(U>bn)throw new Error("Unexpected end of MessagePack data");if(!Vr){let n;try{n=JSON.stringify(e,(r,i)=>typeof i=="bigint"?`${i}n`:i).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return e}catch(e){throw Ce&&Ce.restoreStructures&&G0(),sf(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||U>bn)&&(e.incomplete=!0),e}}function G0(){for(let t in Ce.restoreStructures)Ce[t]=Ce.restoreStructures[t];Ce.restoreStructures=null}function lt(){let t=ie[U++];if(t<160)if(t<128){if(t<64)return t;{let e=Ce[t&63]||Je.getStructures&&V0()[t&63];return e?(e.read||(e.read=ef(e,t&63)),e.read()):t}}else if(t<144)if(t-=128,Je.mapsAsObjects){let e={};for(let n=0;n=U)return Hr.slice(U-wn,(U+=e)-wn);if(er==0&&bn<140){let n=e<16?nf(e):J0(e);if(n!=null)return n}return tf(e)}else{let e;switch(t){case 192:return null;case 193:return xt?(e=lt(),e>0?xt[1].slice(xt.position1,xt.position1+=e):xt[0].slice(xt.position0,xt.position0-=e)):j0;case 194:return!1;case 195:return!0;case 196:if(e=ie[U++],e===void 0)throw new Error("Unexpected end of buffer");return rf(e);case 197:return e=Oe.getUint16(U),U+=2,rf(e);case 198:return e=Oe.getUint32(U),U+=4,rf(e);case 199:return bi(ie[U++]);case 200:return e=Oe.getUint16(U),U+=2,bi(e);case 201:return e=Oe.getUint32(U),U+=4,bi(e);case 202:if(e=Oe.getFloat32(U),Je.useFloat32>2){let n=of[(ie[U]&127)<<1|ie[U+1]>>7];return U+=4,(n*e+(e>0?.5:-.5)>>0)/n}return U+=4,e;case 203:return e=Oe.getFloat64(U),U+=8,e;case 204:return ie[U++];case 205:return e=Oe.getUint16(U),U+=2,e;case 206:return e=Oe.getUint32(U),U+=4,e;case 207:return Je.int64AsType==="number"?(e=Oe.getUint32(U)*4294967296,e+=Oe.getUint32(U+4)):Je.int64AsType==="string"?e=Oe.getBigUint64(U).toString():Je.int64AsType==="auto"?(e=Oe.getBigUint64(U),e<=BigInt(2)<=BigInt(-2)<=U?Hr.slice(U-wn,(U+=e)-wn):fN(e);case 218:return e=Oe.getUint16(U),U+=2,er>=U?Hr.slice(U-wn,(U+=e)-wn):hN(e);case 219:return e=Oe.getUint32(U),U+=4,er>=U?Hr.slice(U-wn,(U+=e)-wn):dN(e);case 220:return e=Oe.getUint16(U),U+=2,K0(e);case 221:return e=Oe.getUint32(U),U+=4,K0(e);case 222:return e=Oe.getUint16(U),U+=2,q0(e);case 223:return e=Oe.getUint32(U),U+=4,q0(e);default:if(t>=224)return t-256;if(t===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+t)}}}const uN=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function ef(t,e){function n(){if(n.count++>z0){let i=t.read=new Function("r","return function(){return "+(Je.freezeData?"Object.freeze":"")+"({"+t.map(s=>s==="__proto__"?"__proto_:r()":uN.test(s)?s+":r()":"["+JSON.stringify(s)+"]:r()").join(",")+"})}")(lt);return t.highByte===0&&(t.read=H0(e,t.read)),i()}let r={};for(let i=0,s=t.length;ifunction(){let n=ie[U++];if(n===0)return e();let r=t<32?-(t+(n<<5)):t+(n<<5),i=Ce[r]||V0()[r];if(!i)throw new Error("Record id is not defined for "+r);return i.read||(i.read=ef(i,t)),i.read()};function V0(){let t=ny(()=>(ie=null,Je.getStructures()));return Ce=Je._mergeStructures(t,Ce)}var tf=ro,fN=ro,hN=ro,dN=ro;function ro(t){let e;if(t<16&&(e=nf(t)))return e;if(t>64&&Qu)return Qu.decode(ie.subarray(U,U+=t));const n=U+t,r=[];for(e="";U65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c)}else r.push(i);r.length>=4096&&(e+=Rt.apply(String,r),r.length=0)}return r.length>0&&(e+=Rt.apply(String,r)),e}function K0(t){let e=new Array(t);for(let n=0;n0){U=e;return}n[r]=i}return Rt.apply(String,n)}function nf(t){if(t<4)if(t<2){if(t===0)return"";{let e=ie[U++];if((e&128)>1){U-=1;return}return Rt(e)}}else{let e=ie[U++],n=ie[U++];if((e&128)>0||(n&128)>0){U-=2;return}if(t<3)return Rt(e,n);let r=ie[U++];if((r&128)>0){U-=3;return}return Rt(e,n,r)}else{let e=ie[U++],n=ie[U++],r=ie[U++],i=ie[U++];if((e&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){U-=4;return}if(t<6){if(t===4)return Rt(e,n,r,i);{let s=ie[U++];if((s&128)>0){U-=5;return}return Rt(e,n,r,i,s)}}else if(t<8){let s=ie[U++],o=ie[U++];if((s&128)>0||(o&128)>0){U-=6;return}if(t<7)return Rt(e,n,r,i,s,o);let a=ie[U++];if((a&128)>0){U-=7;return}return Rt(e,n,r,i,s,o,a)}else{let s=ie[U++],o=ie[U++],a=ie[U++],c=ie[U++];if((s&128)>0||(o&128)>0||(a&128)>0||(c&128)>0){U-=8;return}if(t<10){if(t===8)return Rt(e,n,r,i,s,o,a,c);{let l=ie[U++];if((l&128)>0){U-=9;return}return Rt(e,n,r,i,s,o,a,c,l)}}else if(t<12){let l=ie[U++],u=ie[U++];if((l&128)>0||(u&128)>0){U-=10;return}if(t<11)return Rt(e,n,r,i,s,o,a,c,l,u);let f=ie[U++];if((f&128)>0){U-=11;return}return Rt(e,n,r,i,s,o,a,c,l,u,f)}else{let l=ie[U++],u=ie[U++],f=ie[U++],d=ie[U++];if((l&128)>0||(u&128)>0||(f&128)>0||(d&128)>0){U-=12;return}if(t<14){if(t===12)return Rt(e,n,r,i,s,o,a,c,l,u,f,d);{let h=ie[U++];if((h&128)>0){U-=13;return}return Rt(e,n,r,i,s,o,a,c,l,u,f,d,h)}}else{let h=ie[U++],p=ie[U++];if((h&128)>0||(p&128)>0){U-=14;return}if(t<15)return Rt(e,n,r,i,s,o,a,c,l,u,f,d,h,p);let m=ie[U++];if((m&128)>0){U-=15;return}return Rt(e,n,r,i,s,o,a,c,l,u,f,d,h,p,m)}}}}}function X0(){let t=ie[U++],e;if(t<192)e=t-160;else switch(t){case 217:e=ie[U++];break;case 218:e=Oe.getUint16(U),U+=2;break;case 219:e=Oe.getUint32(U),U+=4;break;default:throw new Error("Expected string")}return ro(e)}function rf(t){return Je.copyBuffers?Uint8Array.prototype.slice.call(ie,U,U+=t):ie.subarray(U,U+=t)}function bi(t){let e=ie[U++];if(Qt[e]){let n;return Qt[e](ie.subarray(U,n=U+=t),r=>{U=r;try{return lt()}finally{U=n}})}else throw new Error("Unknown extension type "+e)}var Z0=new Array(4096);function Y0(){let t=ie[U++];if(t>=160&&t<192){if(t=t-160,er>=U)return Hr.slice(U-wn,(U+=t)-wn);if(!(er==0&&bn<180))return tf(t)}else return U--,Q0(lt());let e=(t<<5^(t>1?Oe.getUint16(U):t>0?ie[U]:0))&4095,n=Z0[e],r=U,i=U+t-3,s,o=0;if(n&&n.bytes==t){for(;r{let n=lt().map(Q0),r=t;e!==void 0&&(t=t<32?-((e<<5)+t):(e<<5)+t,n.highByte=e);let i=Ce[t];return i&&(i.isShared||Vr)&&((Ce.restoreStructures||(Ce.restoreStructures=[]))[t]=i),Ce[t]=n,n.read=ef(n,r),n.read()};Qt[0]=()=>{},Qt[0].noBuffer=!0,Qt[66]=t=>{let e=t.length,n=BigInt(t[0]&128?t[0]-256:t[0]);for(let r=1;r{let t=lt();return(pN[t[0]]||Error)(t[1],{cause:t[2]})},Qt[105]=t=>{if(Je.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=Oe.getUint32(U-4);Sr||(Sr=new Map);let n=ie[U],r;n>=144&&n<160||n==220||n==221?r=[]:r={};let i={target:r};Sr.set(e,i);let s=lt();return i.used?Object.assign(r,s):(i.target=s,s)},Qt[112]=t=>{if(Je.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=Oe.getUint32(U-4),n=Sr.get(e);return n.used=!0,n.target},Qt[115]=()=>new Set(lt());const ty=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(t=>t+"Array");let mN=typeof globalThis=="object"?globalThis:window;Qt[116]=t=>{let e=t[0],n=ty[e];if(!n){if(e===16){let r=new ArrayBuffer(t.length-1);return new Uint8Array(r).set(t.subarray(1)),r}throw new Error("Could not find typed array for code "+e)}return new mN[n](Uint8Array.prototype.slice.call(t,1).buffer)},Qt[120]=()=>{let t=lt();return new RegExp(t[0],t[1])};const gN=[];Qt[98]=t=>{let e=(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3],n=U;return U+=e-t.length,xt=gN,xt=[X0(),X0()],xt.position0=0,xt.position1=0,xt.postBundlePosition=U,U=n,lt()},Qt[255]=t=>t.length==4?new Date((t[0]*16777216+(t[1]<<16)+(t[2]<<8)+t[3])*1e3):t.length==8?new Date(((t[0]<<22)+(t[1]<<14)+(t[2]<<6)+(t[3]>>2))/1e6+((t[3]&3)*4294967296+t[4]*16777216+(t[5]<<16)+(t[6]<<8)+t[7])*1e3):t.length==12?new Date(((t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3])/1e6+((t[4]&128?-281474976710656:0)+t[6]*1099511627776+t[7]*4294967296+t[8]*16777216+(t[9]<<16)+(t[10]<<8)+t[11])*1e3):new Date("invalid");function ny(t){let e=bn,n=U,r=wn,i=er,s=Hr,o=Sr,a=xt,c=new Uint8Array(ie.slice(0,bn)),l=Ce,u=Ce.slice(0,Ce.length),f=Je,d=Vr,h=t();return bn=e,U=n,wn=r,er=i,Hr=s,Sr=o,xt=a,ie=c,Vr=d,Ce=l,Ce.splice(0,Ce.length,...u),Je=f,Oe=new DataView(ie.buffer,ie.byteOffset,ie.byteLength),h}function sf(){ie=null,Sr=null,Ce=null}const of=new Array(147);for(let t=0;t<256;t++)of[t]=+("1e"+Math.floor(45.15-t*.30103));var nc=new no({useRecords:!1});const yN=nc.unpack;nc.unpackMultiple,nc.unpack;let _N=new Float32Array(1);new Uint8Array(_N.buffer,0,4);let rc;try{rc=new TextEncoder}catch{}let af,ry;const ic=typeof Buffer<"u",sc=ic?function(t){return Buffer.allocUnsafeSlow(t)}:Uint8Array,iy=ic?Buffer:Uint8Array,sy=ic?4294967296:2144337920;let j,io,Xe,P=0,Wt,rt=null,bN;const wN=21760,vN=/[\u0080-\uFFFF]/,Yi=Symbol("record-id");class EN extends no{constructor(e){super(e),this.offset=0;let n,r,i,s,o=iy.prototype.utf8Write?function(E,g){return j.utf8Write(E,g,j.byteLength-g)}:rc&&rc.encodeInto?function(E,g){return rc.encodeInto(E,j.subarray(g)).written}:!1,a=this;e||(e={});let c=e&&e.sequential,l=e.structures||e.saveStructures,u=e.maxSharedStructures;if(u==null&&(u=l?32:0),u>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let f=e.maxOwnStructures;f==null&&(f=l?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let d=u>32||f+u>64,h=u+64,p=u+f+64;if(p>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let m=[],b=0,_=0;this.pack=this.encode=function(E,g){if(j||(j=new sc(8192),Xe=j.dataView||(j.dataView=new DataView(j.buffer,0,8192)),P=0),Wt=j.length-10,Wt-P<2048?(j=new sc(j.length),Xe=j.dataView||(j.dataView=new DataView(j.buffer,0,j.length)),Wt=j.length-10,P=0):P=P+7&2147483640,n=P,g&IN&&(P+=g&255),s=a.structuredClone?new Map:null,a.bundleStrings&&typeof E!="string"?(rt=[],rt.size=1/0):rt=null,i=a.structures,i){i.uninitialized&&(i=a._mergeStructures(a.getStructures()));let W=i.sharedLength||0;if(W>u)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+i.sharedLength);if(!i.transitions){i.transitions=Object.create(null);for(let B=0;B$.offset>F.offset?1:-1),Z=B.length,H=-1;for(;W&&Z>0;){let $=B[--Z].offset+n;$W.position+n?H>=0&&(H+=6):(H>=0&&(Xe.setUint32(W.position+n,Xe.getUint32(W.position+n)+H),H=-1),W=W.previous,Z++)}H>=0&&W&&Xe.setUint32(W.position+n,Xe.getUint32(W.position+n)+H),P+=B.length*6,P>Wt&&x(P),a.offset=P;let Y=SN(j.subarray(n,P),B);return s=null,Y}return a.offset=P,g&xN?(j.start=n,j.end=P,j):j.subarray(n,P)}catch(W){throw C=W,W}finally{if(i&&(w(),r&&a.saveStructures)){let W=i.sharedLength||0,B=j.subarray(n,P),Z=AN(i,a);if(!C)return a.saveStructures(Z,Z.isCompatible)===!1?a.pack(E,g):(a.lastNamedStructuresLength=W,j.length>1073741824&&(j=null),B)}j.length>1073741824&&(j=null),g&RN&&(P=n)}};const w=()=>{_<10&&_++;let E=i.sharedLength||0;if(i.length>E&&!c&&(i.length=E),b>1e4)i.transitions=null,_=0,b=0,m.length>0&&(m=[]);else if(m.length>0&&!c){for(let g=0,C=m.length;g{var g=E.length;g<16?j[P++]=144|g:g<65536?(j[P++]=220,j[P++]=g>>8,j[P++]=g&255):(j[P++]=221,Xe.setUint32(P,g),P+=4);for(let C=0;C{P>Wt&&(j=x(P));var g=typeof E,C;if(g==="string"){let W=E.length;if(rt&&W>=4&&W<4096){if((rt.size+=W)>wN){let Y,$=(rt[0]?rt[0].length*3+rt[1].length:0)+10;P+$>Wt&&(j=x(P+$));let F;rt.position?(F=rt,j[P]=200,P+=3,j[P++]=98,Y=P-n,P+=4,cy(n,S,0),Xe.setUint16(Y+n-3,P-n-Y)):(j[P++]=214,j[P++]=98,Y=P-n,P+=4),rt=["",""],rt.previous=F,rt.size=0,rt.position=Y}let H=vN.test(E);rt[H?0:1]+=E,j[P++]=193,S(H?-W:W);return}let B;W<32?B=1:W<256?B=2:W<65536?B=3:B=5;let Z=W*3;if(P+Z>Wt&&(j=x(P+Z)),W<64||!o){let H,Y,$,F=P+B;for(H=0;H>6|192,j[F++]=Y&63|128):(Y&64512)===55296&&(($=E.charCodeAt(H+1))&64512)===56320?(Y=65536+((Y&1023)<<10)+($&1023),H++,j[F++]=Y>>18|240,j[F++]=Y>>12&63|128,j[F++]=Y>>6&63|128,j[F++]=Y&63|128):(j[F++]=Y>>12|224,j[F++]=Y>>6&63|128,j[F++]=Y&63|128);C=F-P-B}else C=o(E,P+B);C<32?j[P++]=160|C:C<256?(B<2&&j.copyWithin(P+2,P+1,P+1+C),j[P++]=217,j[P++]=C):C<65536?(B<3&&j.copyWithin(P+3,P+2,P+2+C),j[P++]=218,j[P++]=C>>8,j[P++]=C&255):(B<5&&j.copyWithin(P+5,P+3,P+3+C),j[P++]=219,Xe.setUint32(P,C),P+=4),P+=C}else if(g==="number")if(E>>>0===E)E<32||E<128&&this.useRecords===!1||E<64&&!this.randomAccessStructure?j[P++]=E:E<256?(j[P++]=204,j[P++]=E):E<65536?(j[P++]=205,j[P++]=E>>8,j[P++]=E&255):(j[P++]=206,Xe.setUint32(P,E),P+=4);else if(E>>0===E)E>=-32?j[P++]=256+E:E>=-128?(j[P++]=208,j[P++]=E+256):E>=-32768?(j[P++]=209,Xe.setInt16(P,E),P+=2):(j[P++]=210,Xe.setInt32(P,E),P+=4);else{let W;if((W=this.useFloat32)>0&&E<4294967296&&E>=-2147483648){j[P++]=202,Xe.setFloat32(P,E);let B;if(W<4||(B=E*of[(j[P]&127)<<1|j[P+1]>>7])>>0===B){P+=4;return}else P--}j[P++]=203,Xe.setFloat64(P,E),P+=8}else if(g==="object"||g==="function")if(!E)j[P++]=192;else{if(s){let B=s.get(E);if(B){if(!B.id){let Z=s.idsToInsert||(s.idsToInsert=[]);B.id=Z.push(B)}j[P++]=214,j[P++]=112,Xe.setUint32(P,B.id),P+=4;return}else s.set(E,{offset:P-n})}let W=E.constructor;if(W===Object)M(E);else if(W===Array)v(E);else if(W===Map)if(this.mapAsEmptyObject)j[P++]=128;else{C=E.size,C<16?j[P++]=128|C:C<65536?(j[P++]=222,j[P++]=C>>8,j[P++]=C&255):(j[P++]=223,Xe.setUint32(P,C),P+=4);for(let[B,Z]of E)S(B),S(Z)}else{for(let B=0,Z=af.length;B(j=$,$=null,P+=ee,P>Wt&&x(P),{target:j,targetView:Xe,position:P-ee}),S)}finally{$&&(j=$,Xe=F,P=ue,Wt=j.length-10)}Q&&(Q.length+P>Wt&&x(Q.length+P),P=kN(Q,j,P,Y.type));return}}if(Array.isArray(E))v(E);else{if(E.toJSON){const B=E.toJSON();if(B!==E)return S(B)}if(g==="function")return S(this.writeFunction&&this.writeFunction(E));M(E)}}}else if(g==="boolean")j[P++]=E?195:194;else if(g==="bigint"){if(E=-(BigInt(1)<0)j[P++]=207,Xe.setBigUint64(P,E);else if(this.largeBigIntToFloat)j[P++]=203,Xe.setFloat64(P,Number(E));else{if(this.largeBigIntToString)return S(E.toString());if(this.useBigIntExtension&&E-(BigInt(2)**BigInt(1023))){j[P++]=199,P++,j[P++]=66;let W=[],B;do{let Z=E&BigInt(255);B=(Z&BigInt(128))===(E>=BigInt(8)}while(!((E===BigInt(0)||E===BigInt(-1))&&B));j[P-2]=W.length;for(let Z=W.length;Z>0;)j[P++]=Number(W[--Z]);return}else throw new RangeError(E+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}P+=8}else if(g==="undefined")this.encodeUndefinedAsNil?j[P++]=192:(j[P++]=212,j[P++]=0,j[P++]=0);else throw new Error("Unknown type: "+g)},L=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?E=>{let g;if(this.skipValues){g=[];for(let B in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(B))&&!this.skipValues.includes(E[B])&&g.push(B)}else g=Object.keys(E);let C=g.length;C<16?j[P++]=128|C:C<65536?(j[P++]=222,j[P++]=C>>8,j[P++]=C&255):(j[P++]=223,Xe.setUint32(P,C),P+=4);let W;if(this.coercibleKeyAsNumber)for(let B=0;B{j[P++]=222;let g=P-n;P+=2;let C=0;for(let W in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(W))&&(S(W),S(E[W]),C++);if(C>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');j[g+++n]=C>>8,j[g+n]=C&255},I=this.useRecords===!1?L:e.progressiveRecords&&!d?E=>{let g,C=i.transitions||(i.transitions=Object.create(null)),W=P++-n,B;for(let Z in E)if(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(Z)){if(g=C[Z],g)C=g;else{let H=Object.keys(E),Y=C;C=i.transitions;let $=0;for(let F=0,ue=H.length;F{let g,C=i.transitions||(i.transitions=Object.create(null)),W=0;for(let Z in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(Z))&&(g=C[Z],g||(g=C[Z]=Object.create(null),W++),C=g);let B=C[Yi];B?B>=96&&d?(j[P++]=((B-=96)&31)+96,j[P++]=B>>5):j[P++]=B:V(C,C.__keys__||Object.keys(E),W);for(let Z in E)(typeof E.hasOwnProperty!="function"||E.hasOwnProperty(Z))&&S(E[Z])},T=typeof this.useRecords=="function"&&this.useRecords,M=T?E=>{T(E)?I(E):L(E)}:I,x=E=>{let g;if(E>16777216){if(E-n>sy)throw new Error("Packed buffer would be larger than maximum buffer size");g=Math.min(sy,Math.round(Math.max((E-n)*(E>67108864?1.25:2),4194304)/4096)*4096)}else g=(Math.max(E-n<<2,j.length-1)>>12)+1<<12;let C=new sc(g);return Xe=C.dataView||(C.dataView=new DataView(C.buffer,0,g)),E=Math.min(E,j.length),j.copy?j.copy(C,0,n,E):C.set(j.slice(n,E)),P-=n,n=0,Wt=C.length-10,j=C},V=(E,g,C)=>{let W=i.nextId;W||(W=64),W=p&&(W=h),i.nextId=W+1);let B=g.highByte=W>=96&&d?W-96>>5:-1;E[Yi]=W,E.__keys__=g,i[W-64]=g,W=0?(j[P++]=(W&31)+96,j[P++]=B):j[P++]=W):(B>=0?(j[P++]=213,j[P++]=114,j[P++]=(W&31)+96,j[P++]=B):(j[P++]=212,j[P++]=114,j[P++]=W),C&&(b+=_*C),m.length>=f&&(m.shift()[Yi]=0),m.push(E),S(g))},oe=(E,g,C,W)=>{let B=j,Z=P,H=Wt,Y=n;j=io,P=0,n=0,j||(io=j=new sc(8192)),Wt=j.length-10,V(E,g,W),io=j;let $=P;if(j=B,P=Z,Wt=H,n=Y,$>1){let F=P+$-1;F>Wt&&x(F);let ue=C+n;j.copyWithin(ue+$,ue+1,P),j.set(io.slice(0,$),ue),P=F}else j[C+n]=io[0]},O=E=>{let g=bN(E,j,n,P,i,x,(C,W,B)=>{if(B)return r=!0;P=W;let Z=j;return S(C),w(),Z!==j?{position:P,targetView:Xe,target:j}:P},this);if(g===0)return M(E);P=g}}useBuffer(e){j=e,j.dataView||(j.dataView=new DataView(j.buffer,j.byteOffset,j.byteLength)),P=0}set position(e){P=e}get position(){return P}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}}ry=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,$0],af=[{pack(t,e,n){let r=t.getTime()/1e3;if((this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:i,targetView:s,position:o}=e(6);i[o++]=214,i[o++]=255,s.setUint32(o,r)}else if(r>0&&r<4294967296){let{target:i,targetView:s,position:o}=e(10);i[o++]=215,i[o++]=255,s.setUint32(o,t.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),s.setUint32(o+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),n(this.onInvalidDate());let{target:i,targetView:s,position:o}=e(3);i[o++]=212,i[o++]=255,i[o++]=255}else{let{target:i,targetView:s,position:o}=e(15);i[o++]=199,i[o++]=12,i[o++]=255,s.setUint32(o,t.getMilliseconds()*1e6),s.setBigInt64(o+4,BigInt(Math.floor(r)))}}},{pack(t,e,n){if(this.setAsEmptyObject)return e(0),n({});let r=Array.from(t),{target:i,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(i[s++]=212,i[s++]=115,i[s++]=0),n(r)}},{pack(t,e,n){let{target:r,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),n([t.name,t.message,t.cause])}},{pack(t,e,n){let{target:r,position:i}=e(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),n([t.source,t.flags])}},{pack(t,e){this.moreTypes?oy(t,16,e):ay(ic?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let n=t.constructor;n!==iy&&this.moreTypes?oy(t,ty.indexOf(n.name),e):ay(t,e)}},{pack(t,e){let{target:n,position:r}=e(1);n[r]=193}}];function oy(t,e,n,r){let i=t.byteLength;if(i+1<256){var{target:s,position:o}=n(4+i);s[o++]=199,s[o++]=i+1}else if(i+1<65536){var{target:s,position:o}=n(5+i);s[o++]=200,s[o++]=i+1>>8,s[o++]=i+1&255}else{var{target:s,position:o,targetView:a}=n(7+i);s[o++]=201,a.setUint32(o,i+1),o+=4}s[o++]=116,s[o++]=e,t.buffer||(t=new Uint8Array(t)),s.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),o)}function ay(t,e){let n=t.byteLength;var r,i;if(n<256){var{target:r,position:i}=e(n+2);r[i++]=196,r[i++]=n}else if(n<65536){var{target:r,position:i}=e(n+3);r[i++]=197,r[i++]=n>>8,r[i++]=n&255}else{var{target:r,position:i,targetView:s}=e(n+5);r[i++]=198,s.setUint32(i,n),i+=4}r.set(t,i)}function kN(t,e,n,r){let i=t.length;switch(i){case 1:e[n++]=212;break;case 2:e[n++]=213;break;case 4:e[n++]=214;break;case 8:e[n++]=215;break;case 16:e[n++]=216;break;default:i<256?(e[n++]=199,e[n++]=i):i<65536?(e[n++]=200,e[n++]=i>>8,e[n++]=i&255):(e[n++]=201,e[n++]=i>>24,e[n++]=i>>16&255,e[n++]=i>>8&255,e[n++]=i&255)}return e[n++]=r,e.set(t,n),n+=i,n}function SN(t,e){let n,r=e.length*6,i=t.length-r;for(;n=e.pop();){let s=n.offset,o=n.id;t.copyWithin(s+r,s,i),r-=6;let a=s+r;t[a++]=214,t[a++]=105,t[a++]=o>>24,t[a++]=o>>16&255,t[a++]=o>>8&255,t[a++]=o&255,i=s}return t}function cy(t,e,n){if(rt.length>0){Xe.setUint32(rt.position+t,P+n-rt.position-t),rt.stringsPosition=P-t;let r=rt;rt=null,e(r[0]),e(r[1])}}function AN(t,e){return t.isCompatible=n=>{let r=!n||(e.lastNamedStructuresLength||0)===n.length;return r||e._mergeStructures(n),r},t}let ly=new EN({useRecords:!1});const TN=ly.pack;ly.pack;const xN=512,RN=1024,IN=2048;function wi(){return null}function so(t,e,n={}){if(!k(t))return;const r=[],i=Object.keys(t);for(let s=0;s(t[t.kind=0]="kind",t[t.id=1]="id",t[t.x=2]="x",t[t.y=3]="y",t[t.lx=4]="lx",t[t.ly=5]="ly",t[t.code=6]="code",t[t.name=7]="name",t[t.char=8]="char",t[t.color=9]="color",t[t.bg=10]="bg",t[t.player=11]="player",t[t.bucket=12]="bucket",t[t.pushable=13]="pushable",t[t.collision=14]="collision",t[t.destructible=15]="destructible",t[t.tickertext=16]="tickertext",t[t.tickertime=17]="tickertime",t[t.p1=18]="p1",t[t.p2=19]="p2",t[t.p3=20]="p3",t[t.cycle=21]="cycle",t[t.stepx=22]="stepx",t[t.stepy=23]="stepy",t[t.sender=24]="sender",t[t.arg=25]="arg",t[t.headless=26]="headless",t[t.removed=27]="removed",t))(cf||{});function oc(t){return so(t,cf,{category:wi,kinddata:wi})}function ac(t){return oo(t,cf)}var lf=(t=>(t[t.width=0]="width",t[t.height=1]="height",t[t.bits=2]="bits",t))(lf||{});function fy(t){return so(t,lf)}function hy(t){return oo(t,lf)}function dy(t,e){return{id:ht(),code:t,...e}}var uf=(t=>(t[t.id=0]="id",t[t.code=1]="code",t[t.board=2]="board",t[t.object=3]="object",t[t.terrain=4]="terrain",t[t.charset=5]="charset",t[t.palette=6]="palette",t[t.eighttrack=7]="eighttrack",t))(uf||{});function CN(t){return so(t,uf,{board:nC,object:oc,terrain:oc,charset:fy,palette:fy,stats:wi})}function LN(t){return oo(t,uf,{board:rC,object:ac,terrain:ac,charset:hy,palette:hy})}function MN(t){const e={...ao(t)};return Object.keys(e).forEach(n=>{switch(n){case"type":case"name":delete e[n];break}}),e}function UN(t){return k(t)?(t.stats=void 0,ao(t)):{}}function ao(t){var r;if(!k(t))return{};if(k((r=t.stats)==null?void 0:r.type))return t.stats;t.stats={};const e=D0(t.code);let n=!0;for(let i=0;i(t[t.id=0]="id",t[t.name=1]="name",t[t.timestamp=2]="timestamp",t[t.activelist=3]="activelist",t[t.pages=4]="pages",t[t.flags=5]="flags",t))(hf||{});function PN(t){return so(t,hf,{pages:e=>e.map(CN)})}function DN(t){return oo(t,hf,{pages:e=>e.map(LN)})}function vi(t,e){if(!k(t))return;const n=Pe(e);return t.pages.find(i=>i.id===e||n===tr(i))}function df(t,e,n){if(!k(t))return;const r=Pe(n);return t.pages.find(s=>co(s)===e&&(s.id===n||r===tr(s)))}function BN(t,e){return k(t)?t.pages.filter(n=>co(n)===e):[]}function yy(t,e){if(!k(t)||!k(e))return!1;const n=vi(t,e.id);return k(n)?!1:(t.pages.push(e),!0)}function FN(t,e){const n=vi(t,e);if(k(t)&&k(n)){const r=Pe(e);return t.pages=t.pages.filter(i=>i.id!==e&&r!==tr(i)),n}}function Mn(t,e){if(k(e)&&k(e.kind))return k(e.kinddata)||(e.kinddata=k(e.id)?cc(t,e.kind):by(t,e.kind)),e.kinddata}function _y(t,e){const n=Mn(t,e);return{char:(e==null?void 0:e.char)??(n==null?void 0:n.char)??1,color:(e==null?void 0:e.color)??(n==null?void 0:n.color)??be.WHITE,bg:(e==null?void 0:e.bg)??(n==null?void 0:n.bg)??be.ONBORROW}}function cc(t,e){const n=e??"",r=df(t,Re.OBJECT,n);if(k(r)){const i=ff(r);return{...fs(i),name:n,code:r.code}}}function by(t,e){const n=e??"",r=df(t,Re.TERRAIN,n);if(k(r)){const i=ff(r);return{...fs(i),name:n,code:r.code}}}function Qi(t,e){const n=vi(t,e);return ff(n)}function es(t,e){return t?(t.flags[e]=t.flags[e]??{},t.flags[e]):{}}function pf(t,e){t&&delete t.flags[e]}function wy(t,e,n){const r=es(t,e);return r==null?void 0:r[n]}function $N(t,e,n,r){const i=es(t,e);return i&&(i[n]=r),r}function lc(t,e){const n=wy(t,e,"board");return Qi(t,Se(n)?n:"")}function mf(t,e,n){if(!k(t))return;$N(t,e,"board",n);const r=Qi(t,n);k(r)?t.activelist.includes(e)||t.activelist.push(e):t.activelist=t.activelist.filter(i=>i!==e)}function jN(t){const n=((t==null?void 0:t.activelist)??[]).map(r=>{const i=wy(t,r,"board");return Se(i)?i:""});return Ok(n)}function vy(t){return jN(t).map(n=>Qi(t,n)).filter(k)}function zN(t,e,n,r){const i=ns(e,(n==null?void 0:n.id)??"");if(!k(t)||!k(e)||!k(i)||!k(i.x)||!k(i.y)||!k(e.lookup)||r.x<0||r.x>=ze||r.y<0||r.y>=rn||i.x-r.x===0&&i.y-r.y===0)return!0;const s=r.x+r.y*ze,o=Mn(t,i),a=i.collision??(o==null?void 0:o.collision),c=ns(e,e.lookup[s]??"");if(k(c))return!0;const l=e.terrain[s];if(k(l)){const u=Mn(t,l),f=l.collision??(u==null?void 0:u.collision);if(Mp(a,f))return!0}return!1}function WN(t,e,n,r){const i=ns(e,(n==null?void 0:n.id)??"");if(!k(t)||!k(e)||!k(i)||!k(i.x)||!k(i.y)||!k(e.lookup)||r.x<0||r.x>=ze||r.y<0||r.y>=rn)return{kind:"edge",collision:Ye.ISSOLID,x:r.x,y:r.y};if(i.x-r.x===0&&i.y-r.y===0)return;const s=i.x+i.y*ze,o=r.x+r.y*ze,a=Mn(t,i),c=i.collision??(a==null?void 0:a.collision),l=ns(e,e.lookup[o]??"");if(k(l))return{...l};const u=e.terrain[o];if(k(u)){const f=Mn(t,u),d=u.collision??(f==null?void 0:f.collision);if(Mp(c,d))return{...u,x:r.x,y:r.y}}i.x=r.x,i.y=r.y,k(i.removed)||(e.lookup[s]=void 0,e.lookup[o]=i.id??"")}function ts(t,e){const n=Mn(t,e);return k(e==null?void 0:e.id)&&k(e.x)&&k(e.y)?Pe(e.name??(n==null?void 0:n.name)??"object"):Pe((e==null?void 0:e.name)??(n==null?void 0:n.name)??"terrain")}function gf(t,e,n,r){if(!k(t)||!k(e)||!k(e.named)||!k(n))return;const i=ts(t,n);e.named[i]||(e.named[i]=new Set),e.named[i].add((n==null?void 0:n.id)??r??"")}function GN(t,e,n){if(!(!k(t)||!k(e)||!k(e.lookup)||!k(n==null?void 0:n.id))&&!k(n.removed)){const r=n.x??0,i=n.y??0;e.lookup[r+i*ze]=n.id}}function uc(t,e){if(!k(t)||!k(e)||k(e.lookup)&&k(e.named))return;const n=new Array(ze*rn).fill(void 0),r={},i=Object.values(e.objects);for(let a=0;a=ze&&(s=0,++o)}e.lookup=n,e.named=r}function yf(t,e,n){return ts(t,e)!=="player"&&k(e)?(e.removed=n,!0):!1}function uo(t,e,n){var r;if(k(t)&&k(e)&&k(n==null?void 0:n.id)){if(k(e.lookup)&&k(n.x)&&k(n.y)){const s=n.x+n.y*ze;e.lookup[s]===n.id&&e.lookup.splice(s,1)}const i=ts(t,n);k((r=e.named)==null?void 0:r[i])&&k(n.id)&&e.named[i].delete(n.id)}}function HN(t,e,n){const r=[];if(!k(t)||!k(e))return r;const i=Object.values(e.objects);for(let s=0;sIo*5&&(r.push(o.id),My(e,o.id))}return r}function VN(t,e,n){const r=[];if(!k(t)||!k(e))return r;e.lookup=void 0,uc(t,e);const i=Object.values(e.objects);for(let o=0;obe.WHITE&&tbe[e]).find(e=>k(e)&&ebe[e]).find(e=>k(e)&&e>=be.ONBLACK)}function Ny(t){if(vn(t))return t;if(Iy(t))return[t];const e=Oy(t);if(k(e))return[e]}function Cy(t){const e=N.words[t],n=Ny(e);if(vn(n))return[n,t+1];const[r,i]=Gt(t),s=Ny(r);return vn(s)?[s,i]:[void 0,t]}function dc(t){const e=[];let n=t;const[r,i]=Cy(t);if(vn(r)&&(e.push(...r),n=i),vn(e)&&!Ry(e)){const[s,o]=Cy(i);Ry(s)&&(n=o)}return e.length?[e,n]:[void 0,t]}function QN(t){const e={};return t.every(n=>{const r=be[n];k(r)&&(r{})}function tC(t=mb){const e={terrain:eC(),objects:{},id:""};return t(e)}var wf=(t=>(t[t.terrain=0]="terrain",t[t.objects=1]="objects",t[t.isdark=2]="isdark",t[t.over=3]="over",t[t.under=4]="under",t[t.exitnorth=5]="exitnorth",t[t.exitsouth=6]="exitsouth",t[t.exitwest=7]="exitwest",t[t.exiteast=8]="exiteast",t[t.timelimit=9]="timelimit",t[t.restartonzap=10]="restartonzap",t[t.maxplayershots=11]="maxplayershots",t))(wf||{});function nC(t){return so(t,wf,{terrain:e=>e.map(oc),objects:e=>Object.values(e).map(oc),id:wi,named:wi,lookup:wi,codepage:wi})}function rC(t){return oo(t,wf,{terrain:e=>e.map(ac),objects:e=>{const n={};for(let r=0;r=ze||e.y<0||e.y>=rn)return;const n={...e},r=e.x+e.y*ze;return t.terrain[r]=n,e}function aC(t,e){if(!k(t)||!k(e))return;const n={...e,id:e.id??ht()};return t.objects[n.id]=n,n}function Ly(t,e,n){return oC(t,{...e,kind:n})}function Ef(t,e,n,r){return aC(t,{...e,id:r??void 0,kind:n})}function ns(t,e){if(t)return t.objects[e]}function kf(t,e,n,r,i){if(!k(t)||!k(e))return{x:0,y:0};const s={x:e.x??0,y:e.y??0},o={x:e.lx??s.x,y:e.ly??s.y},a=zi(o,s),c=ze-1,l=rn-1;for(let u=0;u(t[t.CATEGORY=0]="CATEGORY",t[t.COLLISION=1]="COLLISION",t[t.COLOR=2]="COLOR",t[t.KIND=3]="KIND",t[t.DIR=4]="DIR",t[t.NUMBER=5]="NUMBER",t[t.STRING=6]="STRING",t[t.NUMBER_OR_STRING=7]="NUMBER_OR_STRING",t[t.MAYBE_CATEGORY=8]="MAYBE_CATEGORY",t[t.MAYBE_COLLISION=9]="MAYBE_COLLISION",t[t.MAYBE_COLOR=10]="MAYBE_COLOR",t[t.MAYBE_KIND=11]="MAYBE_KIND",t[t.MAYBE_DIR=12]="MAYBE_DIR",t[t.MAYBE_NUMBER=13]="MAYBE_NUMBER",t[t.MAYBE_STRING=14]="MAYBE_STRING",t[t.MAYBE_NUMBER_OR_STRING=15]="MAYBE_NUMBER_OR_STRING",t[t.ANY=16]="ANY",t))(q||{});function It(t,e){throw new Error(`Invalid arg, expected: ${t} but got ${JSON.stringify(e)}`)}function ne(t,e,n){var o,a,c,l;const r=N.words;N.words=t;const i=[];let s=e;for(let u=0;u(Uy(1,t,e),0)).command("synth",(t,e)=>{for(let n=1;n<=8;++n)nr(n,e);return 0}).command("synth1",(t,e)=>(nr(1,e),0)).command("synth2",(t,e)=>(nr(2,e),0)).command("synth3",(t,e)=>(nr(3,e),0)).command("synth4",(t,e)=>(nr(4,e),0)).command("synth5",(t,e)=>(nr(5,e),0)).command("synth6",(t,e)=>(nr(6,e),0)).command("synth7",(t,e)=>(nr(7,e),0)).command("synth8",(t,e)=>(nr(8,e),0)).command("bgplay",(t,e)=>(Uy(0,t,e),0)).command("bgsynth",(t,e)=>(nr(0,e),0)).command("tts",(t,e)=>{const[n,r]=ne(e,0,[q.STRING,q.MAYBE_STRING]);return KE("audio",r??"",n),0});function mc(t,e,n,r){const i=Se(e)?e:e.id,s=Se(e)?void 0:{x:e.x??0,y:e.y??0},o=Se(n)?n:n.id,a=i??s;k(o)&&k(a)&&t.send(o,r,a)}function fC(t,e,n,r){k(n==null?void 0:n.id)?(n.headless=!0,uo(t,e,n)):Ly(e,r,"empty")}function Py(t,e,n,r,i){const s=WN(e,n,r,i);if(k(s)){mc(t,s,t.id(),"thud"),r.kind===We.PLAYER?mc(t,t.id(),s,"touch"):r.collision===Ye.ISBULLET?mc(t,t.id(),s,"shot"):mc(t,t.id(),s,"bump");const o=Mn(e,s);return(s.destructible??(o==null?void 0:o.destructible))&&fC(e,n,s,i),!1}return!0}function Dy(t,e,n){if(!gr(N.element))return 0;const[r,i]=ne(e,0,[q.DIR,q.MAYBE_KIND]),s=i??["bullet"],o=KN(N.book,N.board,s,{x:N.element.x,y:N.element.y});if(k(o)){o.arg=n,o.collision=Ye.ISBULLET,o.stepx=r.x-N.element.x,o.stepy=r.y-N.element.y;const a=Mn(N.book,o),c=o.code??(a==null?void 0:a.code)??"";w_(N.book,N.board,o,c,1),o.x===N.element.x&&o.y===N.element.y?o.headless=!0:t.bucket(o.id)}return t.yield(),0}const hC=pr().command("change",(t,e)=>{if(!k(N.book)||!k(N.board))return 0;const[n,r]=ne(e,0,[q.KIND,q.KIND]);uc(N.book,N.board);const i=fa(n)??"",s=Ms(N.board,i),o=Pp(s,n),a=fa(r),c=Cp(r),l=Lp(r);return o.forEach(u=>{if(ts(N.book,u)===a)k(c)&&(u.color=c),k(l)&&(u.bg=l);else{if(k(u.id)&&(uo(N.book,N.board,u),!yf(N.book,u,N.timestamp)))return;gr(u)&&_f(N.book,N.board,r,u)}}),0}).command("put",(t,e)=>{if(!k(N.book)||!k(N.board))return 0;const[n,r]=ne(e,0,[q.DIR,q.KIND]);return uc(N.book,N.board),_f(N.book,N.board,r,n),0}).command("shootwith",(t,e)=>{const[n,r]=ne(e,0,[q.ANY]);return Dy(t,e.slice(r),n)}).command("shoot",Dy).command("throwstar",()=>0),dC=navigator.userAgent.includes("Mac")?"cmd":"ctrl",qr="$dkpurple",pC="$196",mC="$205";function an(t,e){return`$${t}${e}$blue`}function By(t,e){return`$${t}${e}$ondkblue`}function et(t,e){Nt(t,e)}function gC(t,e){const n=pC.repeat(e);et(t,`${qr}${n}`)}function Sf(t,e){const n=mC.repeat(e);et(t,`${qr}${n}`)}function fo(t,e){et(t,`${qr} ${" ".repeat(e.length)} `),gC(t,e.length+2),et(t,`${qr} $white${e} `),Sf(t,e.length+2)}function Ar(t,e){et(t,`${qr} ${" ".repeat(e.length)} `),et(t,`${qr} $gray${e} `),Sf(t,e.length+2)}function De(t,e,n){et(t,`${qr} $white${e} $blue${n}`)}function Fe(t,e){et(t,`${qr}$blue${e}`)}function rs(t=""){$l("cli",t,N.player)}const yC=pr().command("send",(t,e)=>{const[n,r]=ne(e,0,[q.STRING,q.ANY]);switch(n){case"helpmenu":fo("cli","H E L P"),De("cli","#help controls","zss controls and inputs"),et("cli","!helpcontrols;read help controls"),et("cli",""),De("cli","#help text","text formatting"),et("cli","!helptext;read help text"),et("cli",""),De("cli","#help developer","developer commands"),et("cli","!helpdeveloper;read help developer"),et("cli",""),De("cli","#help player","player settings"),et("cli","!helpplayer;read help player"),Ar("cli","keyboard input"),De("cli","?","open console"),De("cli","esc","close console"),De("cli","tab","move console"),De("cli","up / down arrow keys","navigate console items"),De("cli","left / right arrow keys","change console items"),De("cli","enter","interact with console items"),De("cli","alt + arrow keys","skip words and console lines"),De("cli",`${dC} + up / down arrow keys`,"input history");break;case"helpcontrols":fo("cli","zss controls and inputs"),Ar("cli","keyboard input"),De("cli","arrow keys","move"),De("cli","shift + arrow keys","shoot"),De("cli","enter","ok / accept"),De("cli","escape","cancel / close"),De("cli","tab","menu / action"),Ar("cli","mouse input"),Fe("cli","todo ???"),Ar("cli","controller input"),De("cli","left stick","move"),De("cli","right stick","aim"),De("cli","a","ok / accept"),De("cli","b","cancel / close"),De("cli","y","menu / action"),De("cli","x","shoot"),De("cli","triggers","shoot");break;case"helptext":fo("cli","text formatting"),Ar("cli","typography"),Fe("cli","plain text"),Fe("cli","$centering text"),Fe("cli",'"\\"@quoted strings for special chars\\""'),Fe("cli","$$0-255 for ascii chars $159$176$240"),Fe("cli",`use color names like ${an("red","$$red")} to change foreground color`),Fe("cli",`use color names like ${By("ongreen","$$ongreen")} to change background color`),Fe("cli",`use clear ${By("onclear","to change background to")} transparent`),Ar("cli","hyperlinks"),Fe("cli",`${an("white",'"!hotkey"')} message shortcut;${an("gray","Label")}`),Fe("cli",`${an("white",'"!range"')} flag [labelmin] [labelmax];${an("gray","Input Label")}`),Fe("cli",`${an("white",'"!select"')} flag ...list of values;${an("gray","Input Label")}`),Fe("cli",`${an("white",'"!number"')} flag [minvalue] [maxvalue];${an("gray","Input Label")}`),Fe("cli",`${an("white",'"!text"')} flag;${an("gray","Input Label")}`),Fe("cli",`${an("white",'"!copyit"')} flag;${an("gray","Input Label")}`);break;case"helpdeveloper":fo("cli","developer commands"),De("cli","#books","list books in memory"),De("cli","#pages","list pages in opened book"),De("cli","@[pagetype:]page name","create & edit a new codepage in the currently opened book"),De("cli","#trash","list books and pages from open book you can delete"),De("cli","#save","flush state to register");break;case"helpplayer":fo("cli","player settings"),Fe("cli","todo");break;default:Nt("$2",`${n} ${r??""}`);break}return 0}).command("stat",(t,e)=>{let n;const[r,...i]=e.map(Ot),s=i.join(" ");switch(Pe(r)){case _n(fe.LOADER):n=xi(We.CONTENT,s,Re.LOADER);break;default:n=xi(We.CONTENT,[r,...i].join(" "),Re.OBJECT);break;case _n(fe.BOARD):n=xi(We.CONTENT,s,Re.BOARD);break;case _n(fe.OBJECT):n=xi(We.CONTENT,s,Re.OBJECT);break;case _n(fe.TERRAIN):n=xi(We.CONTENT,s,Re.TERRAIN);break;case _n(fe.CHARSET):n=xi(We.CONTENT,s,Re.CHARSET);break;case _n(fe.PALETTE):n=xi(We.CONTENT,s,Re.PALETTE);break}return k(n)&&t.command("pageopen",n.id),0}).command("text",(t,e)=>{const n=e.map(Ot).join(" ");return Nt("$2",n),0}).command("hyperlink",(t,e)=>{const[n,...r]=e,i=Ot(n),s=r.map(Ot).join(" ");return Nt("$2",`!${s};${i}`),0}).command("dev",()=>(rs(),WE("cli",N.player),0)).command("share",()=>(rs(),GE("cli",N.player),0)).command("bookcreate",(t,e)=>{const[n]=ne(e,0,[q.MAYBE_STRING]),r=g_(n);return k(r)&&t.command("bookopen",r.id),0}).command("bookopen",(t,e)=>{const[n]=ne(e,0,[q.STRING]),r=Xr(n);return k(r)?(Fe("cli",`opened [book] ${r.name}`),Tc(We.MAIN,r.id),t.command("pages")):tt("cli","bookopen",`book ${n} not found`,N.player),0}).command("booktrash",(t,e)=>{const[n]=ne(e,0,[q.STRING]),r=Ht(We.MAIN),i=Xr(n);return k(i)&&(r===i&&Tc(We.MAIN,""),GL(n),Fe("cli",`trashed [book] ${i.name}`),rs(),t.command("pages")),0}).command("pageopen",(t,e)=>{const[n]=ne(e,0,[q.STRING]),r=Un(We.MAIN);if(!k(r))return 0;const i=vi(r,n);if(k(i)){const s=tr(i),o=lo(i);Fe("cli",`opened [${o}] ${s}`),pp(hp(r.id,i.id),i.code);const a=lo(i);ZE("cli",r.id,i.id,a,`${s} - ${r.name}`,N.player)}else tt("cli","pageopen",`page ${n} not found`,N.player);return 0}).command("pagetrash",(t,e)=>{const[n]=ne(e,0,[q.STRING]),r=Un(We.MAIN),i=FN(r,n);if(k(n)){const s=tr(i),o=lo(i);Fe("cli",`trashed [${o}] ${s}`),rs(),t.command("pages")}return 0}).command("help",(t,e)=>{const n=e.map(Ot).join(" ")||"menu";return t.command(`help${n}`),0}).command("books",()=>{Ar("cli","books");const t=Ht(We.MAIN);De("cli","main",`${(t==null?void 0:t.name)??"empty"} $GREEN${(t==null?void 0:t.id)??""}`);const e=Ht(We.CONTENT);De("cli","content",`${(e==null?void 0:e.name)??"empty"} ${(e==null?void 0:e.id)??""}`),Sf("cli",7);const n=Ac();return n.length?n.forEach(r=>{et("cli",`!bookopen ${r.id};${r.name}`)}):Fe("cli","no books found"),et("cli","!bookcreate;create a new book"),0}).command("pages",()=>{Ar("cli","pages");const t=Un(We.MAIN);return k(t)&&(De("cli","main",`${t.name} $GREEN${t.id}`),t.pages.length?t.pages.forEach(e=>{const n=tr(e),r=lo(e);et("cli",`!pageopen ${e.id};[${r}] ${n}`)}):(et("cli",""),Fe("cli","no pages found"),Fe("cli","use @ to create a page"),Fe("cli","@board name of board"),Fe("cli","@object name of object"),Fe("cli","@terrain name of terrain"),Fe("cli","You can omit the type and it will default to object"),Fe("cli","@object name of object"),Fe("cli","@name of object"))),0}).command("trash",()=>{Ar("cli","$REDTRASH"),Fe("cli","books");const t=Ac();t.length&&(t.forEach(n=>{et("cli",`!booktrash ${n.id};$REDTRASH ${n.name}`)}),et("cli",""));const e=Ht(We.MAIN);return k(e)&&(Fe("cli",`pages in open ${e.name} book`),e.pages.forEach(n=>{const r=tr(n);et("cli",`!pagetrash ${n.id};$REDTRASH ${r}`)}),et("cli","")),0}).command("save",()=>(rs(),0)).command("savewith",(t,e)=>{const[n]=ne(e,0,[q.STRING]);return rs(n),0}).command("nuke",()=>(VE("cli",N.player),0)).command("joincode",()=>($E("cli",N.player),0));function _C(t){const e=Ey[t];if(k(e))return e;const n=Ty[t];if(k(n))return n;const r=hc[t];if(k(r))return r;const i=Tp[t];if(k(i))return i}const bC=pr({get(t,e){const n=_C(e);return k(n)?[!0,n]:[!1,void 0]}}),wC=new Set(["inputmove","inputalt","inputctrl","inputshift","inputok","inputcancel","inputmenu"]),Fy=new Set(["player","pushable","collision","destructible","p1","p2","p3","cycle","stepx","stepy","sender","arg"]),vC=["NORTH","SOUTH","WEST","EAST"];function EC(t){const e=as(t);if(ke(e.inputcurrent)||(e.inputcurrent=0),He(e.inputqueue)||(e.inputqueue=[]),e.inputcurrent>0)return e;const[n]=e.inputqueue,[r=Ft.NONE,i=0]=n??[Ft.NONE,0];switch(e.inputmove=[],e.inputok=0,e.inputcancel=0,e.inputmenu=0,e.inputalt=i&lk?1:0,e.inputctrl=i&uk?1:0,e.inputshift=i&fk?1:0,r){case Ft.MOVE_UP:case Ft.MOVE_DOWN:case Ft.MOVE_LEFT:case Ft.MOVE_RIGHT:e.inputmove=[vC[r-Ft.MOVE_UP]];break;case Ft.OK_BUTTON:e.inputok=1;break;case Ft.CANCEL_BUTTON:e.inputcancel=1;break;case Ft.MENU_BUTTON:e.inputmenu=1;break}return e.inputcurrent=r,e.inputqueue=e.inputqueue.filter(s=>{const[o]=s;return o!==Ft.NONE&&o!==r}),e}const kC=pr({get(t,e){var s,o;if(N.isplayer&&wC.has(e)){const a=EC(((s=N.element)==null?void 0:s.id)??"")[e];return[k(a),a]}const n=(o=N.element)==null?void 0:o[e];if(k(n)||Fy.has(e))return[!0,n];const i=as(N.player)[e];return[k(i),i]},set(t,e,n){var s;const r=(s=N.element)==null?void 0:s[e];if(k(r)||Fy.has(e))return k(N.element)&&(N.element[e]=n),[!0,n];const i=as(N.player);return i[e]=n,[!0,n]},everytick(t){var e,n;k((e=N.element)==null?void 0:e.x)&&k(N.element.y)&&k(N.element.stepx)&&k(N.element.stepy)&&Py(t,N.book,N.board,N.element,{x:N.element.x+N.element.stepx,y:N.element.y+N.element.stepy})===!1&&(N.element.stepx=0,N.element.stepy=0),(n=N.element)!=null&&n.headless&&t.command("die")}}).command("become",(t,e)=>{var i,s;const n={x:((i=N.element)==null?void 0:i.x)??0,y:((s=N.element)==null?void 0:s.y)??0},[r]=ne(e,0,[q.KIND]);return uc(N.book,N.board),uo(N.book,N.board,N.element),yf(N.book,N.element,N.timestamp)&&_f(N.book,N.board,r,n),t.endofprogram(),0}).command("bind",()=>0).command("char",(t,e)=>{const[n]=ne(e,0,[q.NUMBER]);return k(N.element)&&(N.element.char=n),0}).command("color",(t,e)=>{const[n]=ne(e,0,[q.COLOR]);return k(N.element)&&k(n)&&pc(N.element,n),0}).command("go",(t,e)=>{if(k(N.element)){const[n]=ne(e,0,[q.DIR]);if(Py(t,N.book,N.board,N.element,n),t.yield(),N.element.x===n.x&&N.element.y===n.y)return 0}return 1}).command("try",(t,e)=>{const[,n]=ne(e,0,[q.DIR]);return t.command("go",...e)&&n{if(!k(N.element))return 0;const[n]=ne(e,0,[q.DIR]),r=N.element.x??0,i=N.element.y??0;return N.element.stepx=n.x-r,N.element.stepy=n.y-i,0}),SC=pr().command("clear",(t,e)=>(e.forEach(n=>t.set(Ot(n),0)),0)).command("set",(t,e)=>{const[n,r]=ne(e,0,[q.STRING,q.ANY]);return t.set(n,r),0}).command("take",(t,e)=>{const[n,r,i]=ne(e,0,[q.STRING,q.MAYBE_NUMBER]),s=t.get(n),o=r??1;if(!ke(s))return 1;const a=s-o;return a<0?(i{const[n,r,i]=ne(e,0,[q.STRING,q.MAYBE_NUMBER]),s=t.get(n),o=ke(s)?s:0,a=r??1;if(!ke(a))return 0;const c=s===void 0?1:0;return c&&i{var u,f;const[n,r]=ne(e,0,[q.STRING,q.ANY]),[i,s]=n.split(":"),o=k(s)?i:"self",a=s??i;function c(d){d.forEach(h=>{k(h.id)&&t.send(h.id,a,r)})}const l=Pe(o);switch(l){case"all":for(const d of Object.keys(((u=N.board)==null?void 0:u.objects)??{}))t.send(d,a,r);break;case"self":t.message({id:ht(),sender:t.id(),target:a,data:r});break;case"others":for(const d of Object.keys(((f=N.board)==null?void 0:f.objects)??{}))d!==t.id()&&t.send(d,a,r);break;default:{c(Kl(N.board,[o]));const d=t.get(l);He(d)?c(Kl(N.board,d)):c(Kl(N.board,[d]));break}}return 0}).command("stat",(t,e)=>{const n=B0(e.map(Ot));switch(n.type){case fe.OBJECT:k(N.element)&&(N.element.name=n.values.join(" "));break}return 0}).command("text",(t,e)=>{const n=e.map(Ot).join("");return wk(N.player,n),0}).command("hyperlink",(t,e)=>{const[n,r,...i]=e,s=Ot(n),o=Ot(r);return vk(N.player,t,s,o,i),0}).command("gadget",(t,e)=>{const[n]=ne(e,0,[q.STRING]),r=ak[Pe(n)];if(r===un.SCROLL){const[i,s]=ne(e,1,[q.MAYBE_STRING,q.MAYBE_NUMBER]);Wl(N.player,n,r,s,i)}else if(k(r)){const[i,s]=ne(e,1,[q.MAYBE_NUMBER,q.MAYBE_STRING]);Wl(N.player,n,r,i,s)}return 0}),TC=pr().command("idle",t=>(t.yield(),0)).command("end",t=>(t.endofprogram(),0)).command("endwith",(t,e)=>{const[n]=ne(e,0,[q.ANY]);return t.set("arg",n),t.command("end")}).command("lock",t=>(t.lock(t.id()),0)).command("restore",(t,e)=>(t.restore(Ot(e[0])),0)).command("unlock",t=>(t.unlock(),0)).command("zap",(t,e)=>(t.zap(Ot(e[0])),0)).command("cycle",(t,e)=>{if(k(N.element)){const[n]=ne(e,0,[q.NUMBER]);N.element.cycle=ui(Math.round(n),1,255)}return 0}).command("die",t=>{var e;return(e=N.element)!=null&&e.headless&&uo(N.book,N.board,N.element),yf(N.book,N.element,N.timestamp),t.endofprogram(),0}).command("endgame",()=>(YE("element",N.player),0)).command("run",(t,e)=>{const[n]=ne(e,0,[q.STRING]);return xc(n),0}).command("runwith",(t,e)=>{const[n,r]=ne(e,0,[q.ANY,q.STRING]);return t.set("arg",n),xc(r),0});function $y(t,e){if(!k(t))return;const n=Pe(e),r=n.endsWith("le");switch(n){case"float32":case"float32le":{const i=t.dataview.getFloat32(t.cursor,r);return t.cursor+=4,i}case"float64":case"float64le":{const i=t.dataview.getFloat64(t.cursor,r);return t.cursor+=8,i}case"int8":case"int8le":{const i=t.dataview.getInt8(t.cursor);return t.cursor+=1,i}case"int16":case"int16le":{const i=t.dataview.getInt16(t.cursor,r);return t.cursor+=2,i}case"int32":case"int32le":{const i=t.dataview.getInt32(t.cursor,r);return t.cursor+=4,i}case"int64":case"int64le":{const i=t.dataview.getBigInt64(t.cursor,r);return t.cursor+=8,i}case"uint8":case"uint8le":{const i=t.dataview.getUint8(t.cursor);return t.cursor+=1,i}case"uint16":case"uint16le":{const i=t.dataview.getUint16(t.cursor,r);return t.cursor+=2,i}case"uint32":case"uint32le":{const i=t.dataview.getUint32(t.cursor,r);return t.cursor+=4,i}case"uint64":case"uint64le":{const i=t.dataview.getBigUint64(t.cursor,r);return t.cursor+=8,i}}}const xC=(t,e)=>{const n=v_(t.id());if(!k(n))return 0;const[r]=ne(e,0,[q.STRING]),i=Pe(r);switch(i){case"seek":{const[s]=ne(e,1,[q.NUMBER]);n.cursor=s;break}case"float32":case"float32le":case"float64":case"float64le":case"int8":case"int8le":case"int16":case"int16le":case"int32":case"int32le":case"int64":case"int64le":case"uint8":case"uint8le":case"uint16":case"uint16le":case"uint32":case"uint32le":case"uint64":case"uint64le":{const[s]=ne(e,1,[q.STRING]);t.set(s,$y(n,i));break}case"text":{const[s,o]=ne(e,1,[q.STRING,q.STRING]),a=$y(n,s);if(ke(a)&&Se(o)){const c=new Uint8Array(n.bytes.buffer,n.cursor,a),u=new TextDecoder("utf-8").decode(c);t.set(o,u),n.cursor+=a}break}}return 0},RC=pr({get(t,e){const n=v_(t.id());if(k(n))switch(Pe(e)){case"filename":return[k(n.filename),n.filename];case"cursor":return[k(n.cursor),n.cursor]}return[!1,void 0]}}).command("send",(t,e)=>{const[n,r]=ne(e,0,[q.STRING,q.ANY]);return t.message({id:ht(),sender:t.id(),target:n,data:r}),0}).command("stat",()=>0).command("text",(t,e)=>{const n=e.map(Ot).join(" ");return Nt("$2",n),0}).command("hyperlink",(t,e)=>{const[n,...r]=e,i=Ot(n),s=r.map(Ot).join(" ");return Nt("$2",`!${s};${i}`),0}).command("load",(t,e)=>{const n=e.map(Ot).join(" "),r=t.get(n)??n;return Un(We.CONTENT,r),0}).command("reload",(t,e)=>{const n=e.map(Ot).join(" "),r=t.get(n)??n,i=Un(We.CONTENT,r);return i.pages=[],0}).command("bin",xC);var ho=(t=>(t[t.ERROR=0]="ERROR",t[t.CLI=1]="CLI",t[t.LOADER=2]="LOADER",t[t.CODE_PAGE=3]="CODE_PAGE",t))(ho||{});const IC={audio:uC,board:hC,cli:yC,const:bC,element:kC,flags:SC,gadget:AC,lifecycle:TC,loader:RC},Af=["const","flags","audio","board","lifecycle","element"],OC={0:[],1:["cli",...Af],2:["loader",...Af],3:["gadget",...Af]},NC={0:new Map,1:new Map,2:new Map,3:new Map};function po(t){return(OC[t]??[]).map(n=>IC[n]).filter(k)}function CC(t,e){const n=NC[t];if(!n.has(e)){let r;const i=po(t);for(let s=0;s>>=Vy,i>0&&(r|=BC),n+=PC.encode(r);while(i>0);return n};var mo={};(function(t){function e(I,T,M){if(T in I)return I[T];if(arguments.length===3)return M;throw new Error('"'+T+'" is a required argument.')}t.getArg=e;const n=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(I){const T=I.match(n);return T?{scheme:T[1],auth:T[2],host:T[3],port:T[4],path:T[5]}:null}t.urlParse=i;function s(I){let T="";return I.scheme&&(T+=I.scheme+":"),T+="//",I.auth&&(T+=I.auth+"@"),I.host&&(T+=I.host),I.port&&(T+=":"+I.port),I.path&&(T+=I.path),T}t.urlGenerate=s;const o=32;function a(I){const T=[];return function(M){for(let V=0;Vo&&T.pop(),x}}const c=a(function(T){let M=T;const x=i(T);if(x){if(!x.path)return T;M=x.path}const V=t.isAbsolute(M),oe=[];let O=0,E=0;for(;;)if(O=E,E=M.indexOf("/",O),E===-1){oe.push(M.slice(O));break}else for(oe.push(M.slice(O,E));E=0;E--){const C=oe[E];C==="."?oe.splice(E,1):C===".."?g++:g>0&&(C===""?(oe.splice(E+1,g),g=0):(oe.splice(E,2),g--))}return M=oe.join("/"),M===""&&(M=V?"/":"."),x?(x.path=M,s(x)):M});t.normalize=c;function l(I,T){I===""&&(I="."),T===""&&(T=".");const M=i(T),x=i(I);if(x&&(I=x.path||"/"),M&&!M.scheme)return x&&(M.scheme=x.scheme),s(M);if(M||T.match(r))return T;if(x&&!x.host&&!x.path)return x.host=T,s(x);const V=T.charAt(0)==="/"?T:c(I.replace(/\/+$/,"")+"/"+T);return x?(x.path=V,s(x)):V}t.join=l,t.isAbsolute=function(I){return I.charAt(0)==="/"||n.test(I)};function u(I,T){I===""&&(I="."),I=I.replace(/\/$/,"");let M=0;for(;T.indexOf(I+"/")!==0;){const x=I.lastIndexOf("/");if(x<0||(I=I.slice(0,x),I.match(/^([^\/]+:\/)?\/*$/)))return T;++M}return Array(M+1).join("../")+T.substr(I.length+1)}t.relative=u;const f=function(){return!("__proto__"in Object.create(null))}();function d(I){return I}function h(I){return m(I)?"$"+I:I}t.toSetString=f?d:h;function p(I){return m(I)?I.slice(1):I}t.fromSetString=f?d:p;function m(I){if(!I)return!1;const T=I.length;if(T<9||I.charCodeAt(T-1)!==95||I.charCodeAt(T-2)!==95||I.charCodeAt(T-3)!==111||I.charCodeAt(T-4)!==116||I.charCodeAt(T-5)!==111||I.charCodeAt(T-6)!==114||I.charCodeAt(T-7)!==112||I.charCodeAt(T-8)!==95||I.charCodeAt(T-9)!==95)return!1;for(let M=T-10;M>=0;M--)if(I.charCodeAt(M)!==36)return!1;return!0}function b(I,T,M){let x=w(I.source,T.source);return x!==0||(x=I.originalLine-T.originalLine,x!==0)||(x=I.originalColumn-T.originalColumn,x!==0||M)||(x=I.generatedColumn-T.generatedColumn,x!==0)||(x=I.generatedLine-T.generatedLine,x!==0)?x:w(I.name,T.name)}t.compareByOriginalPositions=b;function _(I,T,M){let x=I.generatedLine-T.generatedLine;return x!==0||(x=I.generatedColumn-T.generatedColumn,x!==0||M)||(x=w(I.source,T.source),x!==0)||(x=I.originalLine-T.originalLine,x!==0)||(x=I.originalColumn-T.originalColumn,x!==0)?x:w(I.name,T.name)}t.compareByGeneratedPositionsDeflated=_;function w(I,T){return I===T?0:I===null?1:T===null?-1:I>T?1:-1}function v(I,T){let M=I.generatedLine-T.generatedLine;return M!==0||(M=I.generatedColumn-T.generatedColumn,M!==0)||(M=w(I.source,T.source),M!==0)||(M=I.originalLine-T.originalLine,M!==0)||(M=I.originalColumn-T.originalColumn,M!==0)?M:w(I.name,T.name)}t.compareByGeneratedPositionsInflated=v;function S(I){return JSON.parse(I.replace(/^\)]}'[^\n]*\n/,""))}t.parseSourceMapInput=S;function L(I,T,M){if(T=T||"",I&&(I[I.length-1]!=="/"&&T[0]!=="/"&&(I+="/"),T=I+T),M){const x=i(M);if(!x)throw new Error("sourceMapURL could not be parsed");if(x.path){const V=x.path.lastIndexOf("/");V>=0&&(x.path=x.path.substring(0,V+1))}T=l(s(x),T)}return c(T)}t.computeSourceURL=L})(mo);var Tf={};let $C=class I_{constructor(){this._array=[],this._set=new Map}static fromArray(e,n){const r=new I_;for(let i=0,s=e.length;i=0)return n;throw new Error('"'+e+'" is not in the set.')}at(e){if(e>=0&&en||r==n&&s>=i||Jy.compareByGeneratedPositionsInflated(t,e)<=0}let zC=class{constructor(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}unsortedForEach(e,n){this._array.forEach(e,n)}add(e){jC(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))}toArray(){return this._sorted||(this._array.sort(Jy.compareByGeneratedPositionsInflated),this._sorted=!0),this._array}};qy.MappingList=zC;const go=Wy,pt=mo,gc=Tf.ArraySet,WC=qy.MappingList;let Xy=class O_{constructor(e){e||(e={}),this._file=pt.getArg(e,"file",null),this._sourceRoot=pt.getArg(e,"sourceRoot",null),this._skipValidation=pt.getArg(e,"skipValidation",!1),this._sources=new gc,this._names=new gc,this._mappings=new WC,this._sourcesContents=null}static fromSourceMap(e){const n=e.sourceRoot,r=new O_({file:e.file,sourceRoot:n});return e.eachMapping(function(i){const s={generated:{line:i.generatedLine,column:i.generatedColumn}};i.source!=null&&(s.source=i.source,n!=null&&(s.source=pt.relative(n,s.source)),s.original={line:i.originalLine,column:i.originalColumn},i.name!=null&&(s.name=i.name)),r.addMapping(s)}),e.sources.forEach(function(i){let s=i;n!==null&&(s=pt.relative(n,i)),r._sources.has(s)||r._sources.add(s);const o=e.sourceContentFor(i);o!=null&&r.setSourceContent(i,o)}),r}addMapping(e){const n=pt.getArg(e,"generated"),r=pt.getArg(e,"original",null);let i=pt.getArg(e,"source",null),s=pt.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,i,s),i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),s!=null&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:i,name:s})}setSourceContent(e,n){let r=e;this._sourceRoot!=null&&(r=pt.relative(this._sourceRoot,r)),n!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[pt.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[pt.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))}applySourceMap(e,n,r){let i=n;if(n==null){if(e.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);i=e.file}const s=this._sourceRoot;s!=null&&(i=pt.relative(s,i));const o=this._mappings.toArray().length>0?new gc:this._sources,a=new gc;this._mappings.unsortedForEach(function(c){if(c.source===i&&c.originalLine!=null){const f=e.originalPositionFor({line:c.originalLine,column:c.originalColumn});f.source!=null&&(c.source=f.source,r!=null&&(c.source=pt.join(r,c.source)),s!=null&&(c.source=pt.relative(s,c.source)),c.originalLine=f.line,c.originalColumn=f.column,f.name!=null&&(c.name=f.name))}const l=c.source;l!=null&&!o.has(l)&&o.add(l);const u=c.name;u!=null&&!a.has(u)&&a.add(u)},this),this._sources=o,this._names=a,e.sources.forEach(function(c){const l=e.sourceContentFor(c);l!=null&&(r!=null&&(c=pt.join(r,c)),s!=null&&(c=pt.relative(s,c)),this.setSourceContent(c,l))},this)}_validateMapping(e,n,r,i){if(n&&typeof n.line!="number"&&typeof n.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!n&&!r&&!i)){if(!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:i}))}}_serializeMappings(){let e=0,n=1,r=0,i=0,s=0,o=0,a="",c,l,u,f;const d=this._mappings.toArray();for(let h=0,p=d.length;h0){if(!pt.compareByGeneratedPositionsInflated(l,d[h-1]))continue;c+=","}c+=go.encode(l.generatedColumn-e),e=l.generatedColumn,l.source!=null&&(f=this._sources.indexOf(l.source),c+=go.encode(f-o),o=f,c+=go.encode(l.originalLine-1-i),i=l.originalLine-1,c+=go.encode(l.originalColumn-r),r=l.originalColumn,l.name!=null&&(u=this._names.indexOf(l.name),c+=go.encode(u-s),s=u)),a+=c}return a}_generateSourcesContent(e,n){return e.map(function(r){if(!this._sourcesContents)return null;n!=null&&(r=pt.relative(n,r));const i=pt.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null},this)}toJSON(){const e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e}toString(){return JSON.stringify(this.toJSON())}};Xy.prototype._version=3,zy.SourceMapGenerator=Xy;var Zy={};(function(t){t.GREATEST_LOWER_BOUND=1,t.LEAST_UPPER_BOUND=2;function e(n,r,i,s,o,a){const c=Math.floor((r-n)/2)+n,l=o(i,s[c],!0);return l===0?c:l>0?r-c>1?e(c,r,i,s,o,a):a==t.LEAST_UPPER_BOUND?r1?e(n,c,i,s,o,a):a==t.LEAST_UPPER_BOUND?c:n<0?-1:n}t.search=function(r,i,s,o){if(i.length===0)return-1;let a=e(-1,i.length,r,i,s,o||t.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&s(i[a],i[a-1],!0)===0;)--a;return a}})(Zy);var yo={exports:{}},GC={},HC=Object.freeze({__proto__:null,default:GC}),Yy=N_(HC);if((function(){return typeof window<"u"&&this===window}).call()){let t=null;yo.exports=function(){if(typeof t=="string")return fetch(t).then(n=>n.arrayBuffer());if(t instanceof ArrayBuffer)return Promise.resolve(t);throw new Error("You must provide the string URL or ArrayBuffer contents of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer")},yo.exports.initialize=e=>t=e}else{const t=Yy,e=Yy;yo.exports=function(){return new Promise((r,i)=>{const s=e.join(__dirname,"mappings.wasm");t.readFile(s,null,(o,a)=>{if(o){i(o);return}r(a.buffer)})})},yo.exports.initialize=n=>{console.debug("SourceMapConsumer.initialize is a no-op when running in node.js")}}var Qy=yo.exports;const VC=Qy;function KC(){this.generatedLine=0,this.generatedColumn=0,this.lastGeneratedColumn=null,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}let _o=null;var qC=function(){if(_o)return _o;const e=[];return _o=VC().then(n=>WebAssembly.instantiate(n,{env:{mapping_callback(r,i,s,o,a,c,l,u,f,d){const h=new KC;h.generatedLine=r+1,h.generatedColumn=i,s&&(h.lastGeneratedColumn=o-1),a&&(h.source=c,h.originalLine=l+1,h.originalColumn=u,f&&(h.name=d)),e[e.length-1](h)},start_all_generated_locations_for(){console.time("all_generated_locations_for")},end_all_generated_locations_for(){console.timeEnd("all_generated_locations_for")},start_compute_column_spans(){console.time("compute_column_spans")},end_compute_column_spans(){console.timeEnd("compute_column_spans")},start_generated_location_for(){console.time("generated_location_for")},end_generated_location_for(){console.timeEnd("generated_location_for")},start_original_location_for(){console.time("original_location_for")},end_original_location_for(){console.timeEnd("original_location_for")},start_parse_mappings(){console.time("parse_mappings")},end_parse_mappings(){console.timeEnd("parse_mappings")},start_sort_by_generated_location(){console.time("sort_by_generated_location")},end_sort_by_generated_location(){console.timeEnd("sort_by_generated_location")},start_sort_by_original_location(){console.time("sort_by_original_location")},end_sort_by_original_location(){console.timeEnd("sort_by_original_location")}}})).then(n=>({exports:n.instance.exports,withMappingCallback:(r,i)=>{e.push(r);try{i()}finally{e.pop()}}})).then(null,n=>{throw _o=null,n}),_o};const he=mo,xf=Zy,yc=Tf.ArraySet,JC=Qy,XC=qC,Rf=Symbol("smcInternal");class ut{constructor(e,n){return e==Rf?Promise.resolve(this):YC(e,n)}static initialize(e){JC.initialize(e["lib/mappings.wasm"])}static fromSourceMap(e,n){return QC(e,n)}static async with(e,n,r){const i=await new ut(e,n);try{return await r(i)}finally{i.destroy()}}_parseMappings(e,n){throw new Error("Subclasses must implement _parseMappings")}eachMapping(e,n,r){throw new Error("Subclasses must implement eachMapping")}allGeneratedPositionsFor(e){throw new Error("Subclasses must implement allGeneratedPositionsFor")}destroy(){throw new Error("Subclasses must implement destroy")}}ut.prototype._version=3,ut.GENERATED_ORDER=1,ut.ORIGINAL_ORDER=2,ut.GREATEST_LOWER_BOUND=1,ut.LEAST_UPPER_BOUND=2;class bo extends ut{constructor(e,n){return super(Rf).then(r=>{let i=e;typeof e=="string"&&(i=he.parseSourceMapInput(e));const s=he.getArg(i,"version");let o=he.getArg(i,"sources");const a=he.getArg(i,"names",[]);let c=he.getArg(i,"sourceRoot",null);const l=he.getArg(i,"sourcesContent",null),u=he.getArg(i,"mappings"),f=he.getArg(i,"file",null);if(s!=r._version)throw new Error("Unsupported version: "+s);return c&&(c=he.normalize(c)),o=o.map(String).map(he.normalize).map(function(d){return c&&he.isAbsolute(c)&&he.isAbsolute(d)?he.relative(c,d):d}),r._names=yc.fromArray(a.map(String),!0),r._sources=yc.fromArray(o,!0),r._absoluteSources=r._sources.toArray().map(function(d){return he.computeSourceURL(c,d,n)}),r.sourceRoot=c,r.sourcesContent=l,r._mappings=u,r._sourceMapURL=n,r.file=f,r._computedColumnSpans=!1,r._mappingsPtr=0,r._wasm=null,XC().then(d=>(r._wasm=d,r))})}_findSourceIndex(e){let n=e;if(this.sourceRoot!=null&&(n=he.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);for(let r=0;r{a.source!==null&&(a.source=this._sources.at(a.source),a.source=he.computeSourceURL(o,a.source,this._sourceMapURL),a.name!==null&&(a.name=this._names.at(a.name))),e.call(i,a)},()=>{switch(s){case ut.GENERATED_ORDER:this._wasm.exports.by_generated_location(this._getMappingsPtr());break;case ut.ORIGINAL_ORDER:this._wasm.exports.by_original_location(this._getMappingsPtr());break;default:throw new Error("Unknown order of iteration.")}})}allGeneratedPositionsFor(e){let n=he.getArg(e,"source");const r=he.getArg(e,"line"),i=e.column||0;if(n=this._findSourceIndex(n),n<0)return[];if(r<1)throw new Error("Line numbers must be >= 1");if(i<0)throw new Error("Column numbers must be >= 0");const s=[];return this._wasm.withMappingCallback(o=>{let a=o.lastGeneratedColumn;this._computedColumnSpans&&a===null&&(a=1/0),s.push({line:o.generatedLine,column:o.generatedColumn,lastColumn:a})},()=>{this._wasm.exports.all_generated_locations_for(this._getMappingsPtr(),n,r-1,"column"in e,i)}),s}destroy(){this._mappingsPtr!==0&&(this._wasm.exports.free_mappings(this._mappingsPtr),this._mappingsPtr=0)}computeColumnSpans(){this._computedColumnSpans||(this._wasm.exports.compute_column_spans(this._getMappingsPtr()),this._computedColumnSpans=!0)}originalPositionFor(e){const n={generatedLine:he.getArg(e,"line"),generatedColumn:he.getArg(e,"column")};if(n.generatedLine<1)throw new Error("Line numbers must be >= 1");if(n.generatedColumn<0)throw new Error("Column numbers must be >= 0");let r=he.getArg(e,"bias",ut.GREATEST_LOWER_BOUND);r==null&&(r=ut.GREATEST_LOWER_BOUND);let i;if(this._wasm.withMappingCallback(s=>i=s,()=>{this._wasm.exports.original_location_for(this._getMappingsPtr(),n.generatedLine-1,n.generatedColumn,r)}),i&&i.generatedLine===n.generatedLine){let s=he.getArg(i,"source",null);s!==null&&(s=this._sources.at(s),s=he.computeSourceURL(this.sourceRoot,s,this._sourceMapURL));let o=he.getArg(i,"name",null);return o!==null&&(o=this._names.at(o)),{source:s,line:he.getArg(i,"originalLine",null),column:he.getArg(i,"originalColumn",null),name:o}}return{source:null,line:null,column:null,name:null}}hasContentsOfAllSources(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1}sourceContentFor(e,n){if(!this.sourcesContent)return null;const r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];let i=e;this.sourceRoot!=null&&(i=he.relative(this.sourceRoot,i));let s;if(this.sourceRoot!=null&&(s=he.urlParse(this.sourceRoot))){const o=i.replace(/^file:\/\//,"");if(s.scheme=="file"&&this._sources.has(o))return this.sourcesContent[this._sources.indexOf(o)];if((!s.path||s.path=="/")&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(n)return null;throw new Error('"'+i+'" is not in the SourceMap.')}generatedPositionFor(e){let n=he.getArg(e,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};const r={source:n,originalLine:he.getArg(e,"line"),originalColumn:he.getArg(e,"column")};if(r.originalLine<1)throw new Error("Line numbers must be >= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");let i=he.getArg(e,"bias",ut.GREATEST_LOWER_BOUND);i==null&&(i=ut.GREATEST_LOWER_BOUND);let s;if(this._wasm.withMappingCallback(o=>s=o,()=>{this._wasm.exports.generated_location_for(this._getMappingsPtr(),r.source,r.originalLine-1,r.originalColumn,i)}),s&&s.source===r.source){let o=s.lastGeneratedColumn;return this._computedColumnSpans&&o===null&&(o=1/0),{line:he.getArg(s,"generatedLine",null),column:he.getArg(s,"generatedColumn",null),lastColumn:o}}return{line:null,column:null,lastColumn:null}}}bo.prototype.consumer=ut;class ZC extends ut{constructor(e,n){return super(Rf).then(r=>{let i=e;typeof e=="string"&&(i=he.parseSourceMapInput(e));const s=he.getArg(i,"version"),o=he.getArg(i,"sections");if(s!=r._version)throw new Error("Unsupported version: "+s);r._sources=new yc,r._names=new yc,r.__generatedMappings=null,r.__originalMappings=null,r.__generatedMappingsUnsorted=null,r.__originalMappingsUnsorted=null;let a={line:-1,column:0};return Promise.all(o.map(c=>{if(c.url)throw new Error("Support for url field in sections not implemented.");const l=he.getArg(c,"offset"),u=he.getArg(l,"line"),f=he.getArg(l,"column");if(u({generatedOffset:{generatedLine:u+1,generatedColumn:f+1},consumer:h}))})).then(c=>(r._sections=c,r))})}get _generatedMappings(){return this.__generatedMappings||this._sortGeneratedMappings(),this.__generatedMappings}get _originalMappings(){return this.__originalMappings||this._sortOriginalMappings(),this.__originalMappings}get _generatedMappingsUnsorted(){return this.__generatedMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappingsUnsorted}get _originalMappingsUnsorted(){return this.__originalMappingsUnsorted||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappingsUnsorted}_sortGeneratedMappings(){const e=this._generatedMappingsUnsorted;e.sort(he.compareByGeneratedPositionsDeflated),this.__generatedMappings=e}_sortOriginalMappings(){const e=this._originalMappingsUnsorted;e.sort(he.compareByOriginalPositions),this.__originalMappings=e}get sources(){const e=[];for(let n=0;na.push(c));for(let c=0;c= 1");if(r.originalColumn<0)throw new Error("Column numbers must be >= 0");const i=[];let s=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",he.compareByOriginalPositions,xf.LEAST_UPPER_BOUND);if(s>=0){let o=this._originalMappings[s];if(e.column===void 0){const a=o.originalLine;for(;o&&o.originalLine===a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:he.getArg(o,"generatedLine",null),column:he.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}else{const a=o.originalColumn;for(;o&&o.originalLine===n&&o.originalColumn==a;){let c=o.lastGeneratedColumn;this._computedColumnSpans&&c===null&&(c=1/0),i.push({line:he.getArg(o,"generatedLine",null),column:he.getArg(o,"generatedColumn",null),lastColumn:c}),o=this._originalMappings[++s]}}}return i}destroy(){for(let e=0;e=0;n--)this.prepend(e[n]);else if(e[is]||typeof e=="string")this.children.unshift(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this}walk(e){let n;for(let r=0,i=this.children.length;r0){for(n=[],r=0;rString.fromCharCode(t)),oL=on({name:"Whitespace",pattern:/ +/}),aL=on({name:"WhitespaceSkipped",pattern:/ +/,group:Et.SKIPPED}),If=on({name:"Newline",line_breaks:!0,start_chars_hint:[` +`,"\r"],pattern:/\n|\r\n?/}),t_=on({name:"StringLiteral",pattern:/[^ $;\r\n]+/,start_chars_hint:sL}),Of=on({name:"StringLiteralDouble",pattern:/"(?:[^\\"]|\\(?:[^\n\r]|u[0-9a-fA-F]{4}))*"/}),Nf=on({name:"EscapedDollar",pattern:"$$"}),Cf=on({name:"MaybeFlag",pattern:/\$[^-0-9"!;@#/?\s]+[^-"!;@#/?\s]*/}),Lf=on({name:"NumberLiteral",pattern:/\$-?(\d*\.)?\d+([eE][+-]?\d+)?[jJ]?[lL]?\+?/}),n_=on({name:"HyperLinkText",pattern:/;[^;\r\n]*/,start_chars_hint:[";"]});function cL(t,e=""){return on({name:e||t,pattern:new RegExp(t.toLowerCase(),"i")})}const r_=Object.keys(hc).map(t=>cL(`\\$(${t})`,t)),lL=[oL,If,...r_,Of,t_,Lf,Nf,n_,Cf],uL=new Et(lL,{skipValidations:!Qn,ensureOptimizations:Qn}),fL=new Et([aL,If,...r_,Of,t_,Lf,Nf,n_,Cf],{skipValidations:!Qn,ensureOptimizations:Qn});function Mf(t,e=!1){return e?fL.tokenize(t):uL.tokenize(t)}function i_(t,e,n,r,i,s,o,a){return{disablewrap:!1,measureonly:!1,measuredwidth:0,writefullwidth:void 0,x:0,y:0,iseven:!0,active:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},reset:{color:n,bg:r,topedge:i,leftedge:s,rightedge:o,bottomedge:a},width:t,height:e,char:[],color:[],bg:[],changed(){}}}function s_(t){t.active={...t.reset}}function o_(t,e){const n=e.y;function r(){++e.x;const a=e.active.rightedge??e.width-1;!e.disablewrap&&e.x>a&&(e.x=e.active.leftedge??0,++e.y),e.x>e.measuredwidth&&(e.measuredwidth=e.x)}function i(){return e.x>=(e.active.leftedge??0)&&e.x<=(e.active.rightedge??e.width-1)&&e.y>=(e.active.topedge??0)&&e.y<=(e.active.bottomedge??e.height-1)}function s(a){for(let c=0;ce.measuredwidth&&(e.measuredwidth=e.x+1);const o=e.active.leftedge??0;if(k(e.writefullwidth)&&(e.x>o||e.y===n)){const c=(e.active.rightedge??e.width-1)-e.x;if(c>0){s_(e);const l=String.fromCharCode(e.writefullwidth).repeat(c),u=e.x+e.y*e.width;mL(u,u+l.length,e.active.color,e.active.bg,e),pL(u,l,e)}}}function hL(t,e,n){const r=Mf(t);r.tokens&&(o_(r.tokens,e),s_(e))}function dL(t,e,n){const r=Mf(t);if(!r.tokens)return;const i=i_(e,n,be.WHITE,be.BLACK);return i.measureonly=!0,o_(r.tokens,i),i.x>0&&++i.y,i}function pL(t,e,n){let r=0;const i=t+e.length;for(let s=t;s{this.MANY(()=>this.SUBRULE(this.line))}));ye(this,"line",this.RULED("line",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt)},{ALT:()=>this.CONSUME(to)}])}));ye(this,"stmt",this.RULED("stmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.short_commands)),this.MANY(()=>this.SUBRULE(this.commands))}}])}));ye(this,"inline",this.RULED("inline",()=>{this.SUBRULE(this.instmt)}));ye(this,"instmt",this.RULED("instmt",()=>{this.OR([{ALT:()=>this.SUBRULE(this.stmt_label)},{ALT:()=>this.SUBRULE(this.stmt_stat)},{ALT:()=>this.SUBRULE(this.stmt_text)},{ALT:()=>this.SUBRULE(this.stmt_comment)},{ALT:()=>this.SUBRULE(this.stmt_hyperlink)},{ALT:()=>this.SUBRULE(this.stmt_command)},{ALT:()=>this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}])}));ye(this,"stmt_label",this.RULED("stmt_label",()=>{this.CONSUME(l0)}));ye(this,"stmt_stat",this.RULED("stmt_stat",()=>{this.CONSUME(Wu)}));ye(this,"stmt_text",this.RULED("stmt_text",()=>{this.OR([{ALT:()=>this.CONSUME(a0)}])}));ye(this,"stmt_comment",this.RULED("stmt_comment",()=>{this.CONSUME(c0)}));ye(this,"stmt_hyperlink",this.RULED("stmt_hyperlink",()=>{this.CONSUME(u0),this.SUBRULE(this.words),this.CONSUME(f0)}));ye(this,"stmt_command",this.RULED("stmt_command",()=>{this.CONSUME(Zi),this.AT_LEAST_ONE(()=>this.SUBRULE(this.commands))}));ye(this,"short_commands",this.RULED("short_commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)}])}));ye(this,"commands",this.RULED("commands",()=>{this.OR([{ALT:()=>this.SUBRULE(this.words)},{ALT:()=>this.SUBRULE(this.short_go)},{ALT:()=>this.SUBRULE(this.short_try)},{ALT:()=>this.SUBRULE(this.command_play)},{ALT:()=>this.SUBRULE(this.structured_cmd)}])}));ye(this,"structured_cmd",this.RULED("structured_cmd",()=>{this.OR([{ALT:()=>this.SUBRULE(this.command_debugger)},{ALT:()=>this.SUBRULE(this.command_if)},{ALT:()=>this.SUBRULE(this.command_while)},{ALT:()=>this.SUBRULE(this.command_repeat)},{ALT:()=>this.SUBRULE(this.command_waitfor)},{ALT:()=>this.SUBRULE(this.command_foreach)},{ALT:()=>this.SUBRULE(this.command_break)},{ALT:()=>this.SUBRULE(this.command_continue)}])}));ye(this,"short_go",this.RULED("short_go",()=>{this.CONSUME(Ju),this.SUBRULE(this.words)}));ye(this,"short_try",this.RULED("short_try",()=>{this.CONSUME(S0),this.SUBRULE(this.words)}));ye(this,"command_debugger",this.RULED("command_debugger",()=>{this.CONSUME(R0)}));ye(this,"command_if",this.RULED("command_if",()=>{this.CONSUME(Xu),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_if_block))}));ye(this,"command_if_block",this.RULED("command_if_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(ec),this.MANY(()=>this.SUBRULE(this.line)),this.MANY2({GATE:this.BACKTRACK(this.command_else_if),DEF:()=>this.SUBRULE(this.command_else_if)}),this.OPTION(()=>this.SUBRULE(this.command_else)),this.MANY3(()=>this.CONSUME3(to)),this.CONSUME4(Zi),this.CONSUME4(Zu)}}])}));ye(this,"command_block",this.RULED("command_block",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(ec),this.MANY(()=>this.SUBRULE(this.line)),this.CONSUME(Zi),this.CONSUME(Zu)}}])}));ye(this,"command_fork",this.RULED("command_fork",()=>{this.OR([{ALT:()=>this.SUBRULE(this.inline)},{ALT:()=>{this.CONSUME(ec),this.MANY({GATE:this.BACKTRACK(this.line),DEF:()=>this.SUBRULE(this.line)})}}])}));ye(this,"command_else_if",this.RULED("command_else_if",()=>{this.CONSUME(Zi),this.CONSUME(Yu),this.CONSUME(Xu),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_fork))}));ye(this,"command_else",this.RULED("command_else",()=>{this.CONSUME(Zi),this.CONSUME(Yu),this.OPTION(()=>this.SUBRULE(this.command_fork))}));ye(this,"command_while",this.RULED("command_while",()=>{this.CONSUME(I0),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_repeat",this.RULED("command_repeat",()=>{this.CONSUME(O0),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_waitfor",this.RULED("command_waitfor",()=>{this.CONSUME(N0),this.SUBRULE(this.words)}));ye(this,"command_foreach",this.RULED("command_foreach",()=>{this.CONSUME(C0),this.SUBRULE(this.words),this.OPTION(()=>this.SUBRULE(this.command_block))}));ye(this,"command_break",this.RULED("command_break",()=>{this.CONSUME(L0)}));ye(this,"command_continue",this.RULED("command_continue",()=>{this.CONSUME(M0)}));ye(this,"command_play",this.RULED("command_play",()=>{this.CONSUME(x0)}));ye(this,"expr",this.RULED("expr",()=>{this.SUBRULE1(this.and_test),this.MANY(()=>{this.CONSUME(Gu),this.SUBRULE2(this.and_test)})}));ye(this,"and_test",this.RULED("and_test",()=>{this.SUBRULE1(this.not_test),this.MANY(()=>{this.CONSUME(Vu),this.SUBRULE2(this.not_test)})}));ye(this,"not_test",this.RULED("not_test",()=>{this.OR([{ALT:()=>{this.CONSUME(Hu),this.SUBRULE1(this.not_test)}},{ALT:()=>this.SUBRULE2(this.comparison)}])}));ye(this,"comparison",this.RULED("comparison",()=>{this.SUBRULE1(this.arith_expr),this.MANY(()=>{this.SUBRULE(this.comp_op),this.SUBRULE2(this.arith_expr)})}));ye(this,"comp_op",this.RULED("comp_op",()=>{this.OR([{ALT:()=>this.CONSUME(p0)},{ALT:()=>this.CONSUME(m0)},{ALT:()=>this.CONSUME(g0)},{ALT:()=>this.CONSUME(y0)},{ALT:()=>this.CONSUME(_0)},{ALT:()=>this.CONSUME(b0)}])}));ye(this,"expr_value",this.RULED("expr_value",()=>{this.SUBRULE1(this.and_test_value),this.MANY(()=>{this.CONSUME(Gu),this.SUBRULE2(this.and_test_value)})}));ye(this,"and_test_value",this.RULED("and_test_value",()=>{this.SUBRULE1(this.not_test_value),this.MANY(()=>{this.CONSUME(Vu),this.SUBRULE2(this.not_test_value)})}));ye(this,"not_test_value",this.RULED("not_test_value",()=>{this.OR([{ALT:()=>{this.CONSUME(Hu),this.SUBRULE1(this.not_test_value)}},{ALT:()=>this.SUBRULE2(this.arith_expr)}])}));ye(this,"arith_expr",this.RULED("arith_expr",()=>{this.SUBRULE1(this.term),this.MANY(()=>this.SUBRULE2(this.arith_expr_item))}));ye(this,"arith_expr_item",this.RULED("arith_expr_item",()=>{this.OR([{ALT:()=>this.CONSUME(Ku)},{ALT:()=>this.CONSUME(qu)}]),this.SUBRULE(this.term)}));ye(this,"term",this.RULED("term",()=>{this.SUBRULE1(this.factor),this.MANY(()=>this.SUBRULE2(this.term_item))}));ye(this,"term_item",this.RULED("term_item",()=>{this.OR([{ALT:()=>this.CONSUME(v0)},{ALT:()=>this.CONSUME(Ju)},{ALT:()=>this.CONSUME(E0)},{ALT:()=>this.CONSUME(k0)}]),this.SUBRULE(this.factor)}));ye(this,"factor",this.RULED("factor",()=>{this.OR1([{ALT:()=>{this.OR2([{ALT:()=>this.CONSUME(Ku)},{ALT:()=>this.CONSUME(qu)}]),this.SUBRULE(this.factor)}},{ALT:()=>this.SUBRULE(this.power)}])}));ye(this,"power",this.RULED("power",()=>{this.SUBRULE(this.token),this.OPTION(()=>{this.CONSUME(w0),this.SUBRULE(this.factor)})}));ye(this,"words",this.RULED("words",()=>{this.AT_LEAST_ONE(()=>this.SUBRULE(this.expr))}));ye(this,"token",this.RULED("token",()=>{this.OR([{ALT:()=>this.CONSUME(h0)},{ALT:()=>this.CONSUME(zt)},{ALT:()=>this.CONSUME(d0)},{ALT:()=>{this.CONSUME(A0),this.SUBRULE(this.expr),this.CONSUME(T0)}}])}));this.performSelfAnalysis()}PEEK(n,r,...i){console.info(n,i.map(s=>[s.image,s.tokenType]),r)}RULED(n,r,i){const s=gL.some(o=>n.includes(o));return this.RULE(n,()=>{const a=(a_++).toString().padStart(3),c=s?"font-weight: bold;":"";if(c_&&!this.RECORDING_PHASE){const l=[this.LA(1),this.LA(2),this.LA(3)].map(u=>`[${u.tokenType.name} ${u.image.replaceAll(` +`,"\\n")}]`);console.info(`${a}%c> ${n} ${l.join(" ")}`,c)}r(),c_&&!this.RECORDING_PHASE&&console.info(`${a}%c< ${n} `,c),a_--},i)}}const ss=new yL;if(nN){const t=ss.getGAstProductions(),e=tN(t);console.info(e)}const _L=ss.getBaseCstVisitorConstructor();var se=(t=>(t[t.PROGRAM=0]="PROGRAM",t[t.API=1]="API",t[t.LINE=2]="LINE",t[t.MARK=3]="MARK",t[t.GOTO=4]="GOTO",t[t.COUNT=5]="COUNT",t[t.TEXT=6]="TEXT",t[t.LABEL=7]="LABEL",t[t.HYPERLINK=8]="HYPERLINK",t[t.STAT=9]="STAT",t[t.MOVE=10]="MOVE",t[t.COMMAND=11]="COMMAND",t[t.LITERAL=12]="LITERAL",t[t.IF=13]="IF",t[t.IF_CHECK=14]="IF_CHECK",t[t.IF_BLOCK=15]="IF_BLOCK",t[t.ELSE_IF=16]="ELSE_IF",t[t.ELSE=17]="ELSE",t[t.WHILE=18]="WHILE",t[t.BREAK=19]="BREAK",t[t.CONTINUE=20]="CONTINUE",t[t.REPEAT=21]="REPEAT",t[t.WAITFOR=22]="WAITFOR",t[t.FOREACH=23]="FOREACH",t[t.OR=24]="OR",t[t.AND=25]="AND",t[t.NOT=26]="NOT",t[t.COMPARE=27]="COMPARE",t[t.COMPARE_ITEM=28]="COMPARE_ITEM",t[t.OPERATOR=29]="OPERATOR",t[t.OPERATOR_ITEM=30]="OPERATOR_ITEM",t[t.EXPR=31]="EXPR",t))(se||{}),ki=(t=>(t[t.IS_EQ=0]="IS_EQ",t[t.IS_NOT_EQ=1]="IS_NOT_EQ",t[t.IS_LESS_THAN=2]="IS_LESS_THAN",t[t.IS_GREATER_THAN=3]="IS_GREATER_THAN",t[t.IS_LESS_THAN_OR_EQ=4]="IS_LESS_THAN_OR_EQ",t[t.IS_GREATER_THAN_OR_EQ=5]="IS_GREATER_THAN_OR_EQ",t))(ki||{}),rr=(t=>(t[t.EMPTY=0]="EMPTY",t[t.PLUS=1]="PLUS",t[t.MINUS=2]="MINUS",t[t.POWER=3]="POWER",t[t.MULTIPLY=4]="MULTIPLY",t[t.DIVIDE=5]="DIVIDE",t[t.MOD_DIVIDE=6]="MOD_DIVIDE",t[t.FLOOR_DIVIDE=7]="FLOOR_DIVIDE",t[t.UNI_PLUS=8]="UNI_PLUS",t[t.UNI_MINUS=9]="UNI_MINUS",t))(rr||{}),bc=(t=>(t[t.NUMBER=0]="NUMBER",t[t.STRING=1]="STRING",t[t.TEMPLATE=2]="TEMPLATE",t))(bc||{});function bL(t){return!!(t!=null&&t.tokenType)}function Tr(t,e){const[n]=t??[];return((n==null?void 0:n.image)??e).trimStart().replaceAll(/^"|"$/g,"")}class wL extends _L{constructor(){super();ye(this,"unique",0);Qn&&this.validateVisitor()}getnodelocation(n){const r=Object.values(n).flat().filter(i=>!!i).map(i=>i&&bL(i)?{startLine:i.startLine,startColumn:i.startColumn,startOffset:i.startOffset,endLine:i.endLine,endColumn:i.endColumn,endOffset:i.endOffset}:i!=null&&i.location?{...i.location}:{startLine:0,startColumn:0,startOffset:0,endLine:0,endColumn:0,endOffset:0}).filter(i=>i.startLine!==0&&i.endLine!==0);return{startLine:Math.min(...r.map(i=>i.startLine??1)),startColumn:Math.min(...r.map(i=>i.startColumn??1)),startOffset:Math.min(...r.map(i=>i.startOffset??1)),endLine:Math.max(...r.map(i=>i.endLine??1)),endColumn:Math.max(...r.map(i=>i.endColumn??1)),endOffset:Math.max(...r.map(i=>i.endOffset??1))}}createcodenode(n,r){return[{...r,...this.getnodelocation(n),lineindex:0}]}createstringnode(n,r){return this.createcodenode(n,{type:12,literal:1,value:r})}createmarknode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:3,id:r,comment:i}))}creategotonode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:4,id:r,comment:i}))}createlinenode(n,r){return this.createcodenode(n,{type:2,stmts:r})}createapinode(n,r,i){return this.createlinenode(n,this.createcodenode(n,{type:1,words:i,method:r}))}createlogicnode(n,r,i,s){return this.createlinenode(n,this.createcodenode(n,{type:14,skip:i,words:s,method:r}))}createcountnode(n){return this.createcodenode(n,{type:5,index:this.unique++})}go(n){return Array.isArray(n)?n.map(r=>this.visit(r)).flat():k(n)?[this.visit(n)].flat():[]}program(n){return this.unique=0,this.createcodenode(n,{type:0,lines:[this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:"restart"})),this.go(n.line)].flat()})}line(n){return n.stmt?this.go(n.stmt):[]}stmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.short_commands?[this.go(n.short_commands),this.go(n.commands)].flat():[]}inline(n){return this.go(n.instmt)}instmt(n){return n.stmt_label?this.go(n.stmt_label):n.stmt_stat?this.go(n.stmt_stat):n.stmt_text?this.go(n.stmt_text):n.stmt_comment?this.go(n.stmt_comment):n.stmt_command?this.go(n.stmt_command):n.stmt_hyperlink?this.go(n.stmt_hyperlink):n.commands?this.go(n.commands):[]}stmt_label(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!0,name:Tr(n.token_label,":").slice(1).trim()}))}stmt_stat(n){return this.createlinenode(n,this.createcodenode(n,{type:9,value:Tr(n.token_stat,"@").slice(1)}))}stmt_text(n){return this.createlinenode(n,this.createcodenode(n,{type:6,value:Tr(n.token_text,"")}))}stmt_comment(n){return this.createlinenode(n,this.createcodenode(n,{type:7,active:!1,name:Tr(n.token_comment,"'").slice(1).trim()}))}stmt_hyperlink(n){return this.createlinenode(n,this.createcodenode(n,{type:8,link:this.go(n.words),text:Tr(n.token_hyperlinktext,";").slice(1)}))}stmt_command(n){return n.commands?this.go(n.commands):[]}short_commands(n){return n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):[]}commands(n){return n.words?this.createlinenode(n,this.createcodenode(n,{type:11,words:this.go(n.words)})):n.short_go?this.go(n.short_go):n.short_try?this.go(n.short_try):n.command_play?this.go(n.command_play):n.structured_cmd?this.go(n.structured_cmd):[]}structured_cmd(n){return n.command_if?this.go(n.command_if):n.command_while?this.go(n.command_while):n.command_repeat?this.go(n.command_repeat):n.command_waitfor?this.go(n.command_waitfor):n.command_foreach?this.go(n.command_foreach):n.command_break?this.go(n.command_break):n.command_continue?this.go(n.command_continue):[]}short_go(n){return n.token_divide?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!0,words:this.go(n.words)})):[]}short_try(n){return n.token_query?this.createlinenode(n,this.createcodenode(n,{type:10,wait:!1,words:this.go(n.words)})):[]}command_if(n){const[r]=this.createlogicnode(n,"if","",this.go(n.words)),[i]=this.go(n.command_if_block)??[];return this.createcodenode(n,{type:13,check:r,block:i})}command_if_block(n){const r=ht(),i=ht();return this.createcodenode(n,{type:15,skip:r,done:i,lines:[this.go(n.inline),this.go(n.line),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"alt logic")].flat(),altlines:[this.go(n.command_else_if),this.go(n.command_else),this.createmarknode(n,i,"end of if")].flat()})}command_block(n){return[this.go(n.inline),this.go(n.line)].flat()}command_fork(n){return[this.go(n.inline),this.go(n.line)].flat()}command_else_if(n){const r=ht(),i=ht();return this.createcodenode(n,{type:16,done:i,lines:[this.createlogicnode(n,"if",r,this.go(n.words)),this.go(n.command_fork),this.creategotonode(n,i,"end of if"),this.createmarknode(n,r,"skip")].flat()})}command_else(n){return this.createcodenode(n,{type:17,lines:this.go(n.command_fork)})}command_while(n){const r=ht(),i=ht();return this.createcodenode(n,{type:18,loop:r,done:i,lines:[this.createmarknode(n,r,"start of while"),this.createlogicnode(n,"if",i,this.go(n.words)),this.go(n.command_block),this.creategotonode(n,r,"loop of while"),this.createmarknode(n,i,"end of while")].flat()})}command_repeat(n){const r=ht(),i=ht(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:21,loop:r,done:i,lines:[this.createapinode(n,"repeatstart",o),this.createmarknode(n,r,"start of repeat"),this.createlogicnode(n,"repeat",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of repeat"),this.createmarknode(n,i,"end of repeat")].flat()})}command_foreach(n){const r=ht(),i=ht(),o=[this.createcountnode(n),this.go(n.words)].flat();return this.createcodenode(n,{type:23,loop:r,done:i,lines:[this.createapinode(n,"foreachstart",o),this.createmarknode(n,r,"start of foreach"),this.createlogicnode(n,"foreach",i,o),this.go(n.command_block),this.creategotonode(n,r,"loop of foreach"),this.createmarknode(n,i,"end of foreach")].flat()})}command_waitfor(n){return this.createcodenode(n,{type:22,words:this.go(n.words)})}command_break(n){return this.createcodenode(n,{type:19,goto:0})}command_continue(n){return this.createcodenode(n,{type:20,goto:0})}command_play(n){const r=Tr(n.token_command_play,""),i=r.replace("bgplay","").replace("play","").trim(),s=r.includes("bgplay");return this.createlinenode(n,this.createcodenode(n,{type:11,words:[this.createstringnode(n,s?"bgplay":"play"),this.createstringnode(n,i)].flat()}))}expr(n){return n.and_test.length===1?this.go(n.and_test):this.createcodenode(n,{type:24,items:this.go(n.and_test)})}and_test(n){return n.not_test.length===1?this.go(n.not_test):this.createcodenode(n,{type:25,items:this.go(n.not_test)})}not_test(n){return n.comparison?this.go(n.comparison):n.not_test?this.createcodenode(n,{type:26,items:this.go(n.not_test)}):[]}comparison(n){if(n.arith_expr.length===1)return this.go(n.arith_expr);const[r,i]=this.go(n.arith_expr),[s]=this.go(n.comp_op);return this.createcodenode(n,{type:27,lhs:r,compare:s,rhs:i})}comp_op(n){return n.token_iseq?this.createcodenode(n,{type:28,method:0}):n.token_isnoteq?this.createcodenode(n,{type:28,method:1}):n.token_islessthan?this.createcodenode(n,{type:28,method:2}):n.token_isgreaterthan?this.createcodenode(n,{type:28,method:3}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:4}):n.token_isgreaterthanorequal?this.createcodenode(n,{type:28,method:5}):[]}expr_value(n){return n.and_test_value.length===1?this.go(n.and_test_value):this.createcodenode(n,{type:24,items:this.go(n.and_test_value)})}and_test_value(n){return n.not_test_value.length===1?this.go(n.not_test_value):this.createcodenode(n,{type:25,items:this.go(n.not_test_value)})}not_test_value(n){return n.arith_expr?this.go(n.arith_expr):n.not_test_value?this.createcodenode(n,{type:26,items:this.go(n.not_test_value)}):[]}arith_expr(n){const r=this.go(n.term);return n.arith_expr_item?this.createcodenode(n,{type:29,lhs:r[0],items:this.go(n.arith_expr_item)}):r}arith_expr_item(n){return this.createcodenode(n,{type:30,operator:n.token_plus?1:2,rhs:this.go(n.term)[0]})}term(n){return n.term_item?this.createcodenode(n,{type:29,lhs:this.go(n.factor)[0],items:this.go(n.term_item)}):this.go(n.factor)}term_item(n){let r=0;return n.token_multiply&&(r=4),n.token_divide&&(r=5),n.token_moddivide&&(r=6),n.token_floordivide&&(r=7),this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})}factor(n){if(n.power)return this.go(n.power);let r=0;return n.token_plus&&(r=8),n.token_minus&&(r=9),this.createcodenode(n,{type:29,lhs:void 0,items:this.createcodenode(n,{type:30,operator:r,rhs:this.go(n.factor)[0]})})}power(n){const r=this.go(n.token);return n.factor?this.createcodenode(n,{type:29,lhs:r[0],items:this.createcodenode(n,{type:30,operator:3,rhs:this.go(n.factor)[0]})}):r}words(n){return this.go(n.expr)}token(n){if(n.token_stringliteraldouble){const r=Tr(n.token_stringliteraldouble,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:2,value:r})}if(n.token_stringliteral){const r=Tr(n.token_stringliteral,"").replaceAll(/(^"|"$)/g,"");return this.createcodenode(n,{type:12,literal:1,value:r})}if(n.token_numberliteral){const r=parseFloat(Tr(n.token_numberliteral,"0"));return this.createcodenode(n,{type:12,literal:0,value:r})}return n.token_lparen?this.createcodenode(n,{type:31,words:this.go(n.expr)}):[]}}const vL=new wL,en={labels:{},internal:0,lineindex:0,linelookup:{},isfirststat:!1},wc="zss.js";function Le(t,e){return new iL(t.startLine??1,t.startColumn??1,wc,e)}function Uf(t){return t.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Pf(t){return`'${Uf(t)}'`}function vc(t){if(t.startsWith('"'))return vc(t.replaceAll(/(^"|"$)/g,""));const e=Mf(t);return e.errors.length?t:`['${e.tokens.map(r=>r.tokenType===Cf?`', api.get('${Uf(r.image.substring(1))}'), '`:Uf(r.image)).join("")}'].join('')`}function Si(t){return t.filter(e=>e!==void 0).map(Be)}function l_(t){return Le(t,"")}function EL(t,e){const n=[];return t.forEach(r=>{n.push(r,e)}),n.pop(),n}function mt(t,e,n){return Le(t,[`api.${e}(`,...EL(n,", "),")"])}function kL(t){if(t.type===se.COMPARE&&t.compare.type===se.COMPARE_ITEM)switch(t.compare.method){case ki.IS_EQ:return mt(t,"isEq",[Be(t.lhs),Be(t.rhs)]);case ki.IS_NOT_EQ:return mt(t,"isNotEq",[Be(t.lhs),Be(t.rhs)]);case ki.IS_LESS_THAN:return mt(t,"isLessThan",[Be(t.lhs),Be(t.rhs)]);case ki.IS_GREATER_THAN:return mt(t,"isGreaterThan",[Be(t.lhs),Be(t.rhs)]);case ki.IS_LESS_THAN_OR_EQ:return mt(t,"isLessThanOrEq",[Be(t.lhs),Be(t.rhs)]);case ki.IS_GREATER_THAN_OR_EQ:return mt(t,"isGreaterThanOrEq",[Be(t.lhs),Be(t.rhs)])}return Le(t,"")}function Ai(t,e,n){return t.prepend(`api.${e}(`),t.add([", ",Be(n),")"])}function u_(t,e,n){return t.prepend(`api.${e}(`),t.add([Be(n),")"])}function SL(t,e){if(t.type===se.OPERATOR_ITEM)switch(t.operator){case rr.PLUS:return Ai(e,"opPlus",t.rhs);case rr.MINUS:return Ai(e,"opMinus",t.rhs);case rr.POWER:return Ai(e,"opPower",t.rhs);case rr.MULTIPLY:return Ai(e,"opMultiply",t.rhs);case rr.DIVIDE:return Ai(e,"opDivide",t.rhs);case rr.MOD_DIVIDE:return Ai(e,"opModDivide",t.rhs);case rr.FLOOR_DIVIDE:return Ai(e,"opFloorDivide",t.rhs);case rr.UNI_PLUS:return u_(e,"opUniPlus",t.rhs);case rr.UNI_MINUS:return u_(e,"opUniMinus",t.rhs)}return Le(t,"")}function AL(t){if(t.type===se.OPERATOR){const e=t.lhs?Be(t.lhs):Le(t,"");return t.items.forEach(n=>SL(n,e)),e}return Le(t,"")}function Ec(t,e){return Le(t,[mt(t,"jump",[`${e}`]),"; continue;"])}function xr(t){return en.linelookup[t??""]??-1}function Df(t,e){en.linelookup[t]=e}function wo(t,e,n){for(let r=0;rr.add(Be(i))),f_(n.altlines,se.ELSE_IF,xr(n.done)),n.altlines.forEach(i=>r.add(Be(i))),r}return Le(t,Be(t.check))}case se.IF_CHECK:{const n=xr(t.skip);return n===-1?Le(t,[" ",mt(t,t.method,Si(t.words)),`; +`]):Le(t,[" if (!",mt(t,t.method,Si(t.words)),") { ",Ec(t,n),` } +`])}case se.ELSE_IF:case se.ELSE:{const n=Le(t,"");return t.lines.forEach(r=>n.add(Be(r))),n}case se.WHILE:{const n=xr(t.loop),r=xr(t.done),i=Le(t,"");return wo(t.lines,se.IF_CHECK,t.done),t.lines.forEach(s=>{switch(s.type){case se.BREAK:s.goto=r;break;case se.CONTINUE:s.goto=n;break}i.add(Be(s))}),i}case se.REPEAT:{const n=xr(t.loop),r=xr(t.done),i=Le(t,"");return wo(t.lines,se.IF_CHECK,t.done),t.lines.forEach(s=>{switch(s.type){case se.BREAK:s.goto=r;break;case se.CONTINUE:s.goto=n;break}i.add(Be(s))}),i}case se.WAITFOR:{const n=Le(t,"");return n.add([" if (!",mt(t,"if",Si(t.words)),`) { api.i(${t.lineindex-1}); } +`]),n}case se.FOREACH:{const n=xr(t.loop),r=xr(t.done),i=Le(t,"");return wo(t.lines,se.IF_CHECK,t.done),t.lines.forEach(s=>{switch(s.type){case se.BREAK:s.goto=r;break;case se.CONTINUE:s.goto=n;break}i.add(Be(s))}),i}case se.BREAK:return Le(t,[" ",Ec(t,t.goto),` +`]);case se.CONTINUE:return Le(t,[" ",Ec(t,t.goto),` +`]);case se.OR:return mt(t,"or",t.items.map(Be));case se.AND:return mt(t,"and",t.items.map(Be));case se.NOT:return mt(t,"not",t.items.map(Be));case se.COMPARE:return kL(t);case se.OPERATOR:return AL(t);case se.EXPR:return mt(t,"expr",t.words.map(Be));default:return console.error("",t.type,t),l_(t)}}function ir(t){if(k(t))switch(t.type===se.LINE&&++en.lineindex,t.lineindex=en.lineindex,t.type){case se.PROGRAM:t.lines.forEach(ir);break;case se.LINE:t.stmts.forEach(ir);break;case se.MARK:Df(t.id,t.lineindex);break;case se.IF:ir(t.check),ir(t.block);break;case se.IF_BLOCK:t.lines.forEach(ir),t.altlines.forEach(ir);break;case se.ELSE_IF:t.lines.forEach(ir);break;case se.ELSE:case se.WHILE:case se.REPEAT:case se.FOREACH:t.lines.forEach(ir);break;case se.MOVE:case se.COMMAND:case se.WAITFOR:case se.IF_CHECK:t.words.forEach(ir);break}}function TL(t){return en.labels={},en.internal=1,en.lineindex=0,en.isfirststat=!0,ir(t),{...Be(t).toStringWithSourceMap({file:`${wc}.map`}),...en}}const kc={HALT_AT_COUNT:256};function xL(t){return He(t)?t.length>0?1:0:t??0}function Ot(t){return`${t??""}`}function h_(t){return`${t}_chip`}function RL(t,e,n){var c,l;const r=h_(t),i=as(r);let s;He(i.lb)||(i.lb=fs(Object.entries(n.labels??{})),i.lk="",i.mg=void 0,i.ec=1,i.lc=0,i.ys=0,i.ps=0,i.es=(((c=n.errors)==null?void 0:c.length)??0)!==0?1:0);function o(u,f){N.words=f;const d=CC(e,u);return k(d)?d(a,f):u!=="send"?o("send",[u,...f]):0}const a={halt(){zL(r)},id(){return t},senderid(u=t){return`vm:${u??t}`},set(u,f){const[d,h]=MC(e,a,u,f);if(d)return h},get(u){const[f,d]=LC(e,a,u);if(f)return d},bucket(u){const f=a.get("bucket");He(f)?f.push(u):a.set("bucket",[u])},tick(u){const f=ke(i.ps)?i.ps:0,d=f%u===0;if(i.ps=f+1,d===!1)return!1;if(a.shouldtick()===!1)return jy(e,a),!1;i.lc=0,i.ys=0,N.get=a.get,UC(e,a);try{const h=s==null?void 0:s.next();h!=null&&h.done&&(tt("chip","crash","generator logic unexpectedly exited"),i.es=1)}catch(h){tt("chip","crash",h.message),i.es=1}return jy(e,a),!0},isended(){return i.es===1},shouldtick(){return i.es===0||a.hm()!==0},shouldhalt(){return ke(i.lc)?++i.lc>kc.HALT_AT_COUNT:!0},hm(){if(He(i.mg)&&He(i.lb)){const[,u]=i.mg;if(k(u))for(let f=0;fke(p)&&p>0)??0}}return 0},yield(){i.ys=1},jump(u){i.ec=u},sy(){return!!i.ys||a.shouldhalt()},emit(u,f,d){Te.emit(u,a.senderid(),f,d)},send(u,f,d,h){Te.emit(`${a.senderid(u)}:${f}`,t,d,h)},lock(u){i.lk=u},unlock(){i.lk=""},message(u){i.lk&&u.sender!==i.lk||(i.mg=[u.id,u.target,u.data,u.sender,u.player])},zap(u){if(He(i.lb))for(let f=0;fm>0);p>=0&&(h[p]*=-1)}}},restore(u){if(He(i.lb))for(let f=0;fh.fileName===wc);return{line:(d==null?void 0:d.lineNumber)??0,column:(d==null?void 0:d.columnNumber)??0}},text(u){return o("text",[u])},stat(...u){return o("stat",u)},hyperlink(...u){return o("hyperlink",u)},command(...u){if(u.length===0)return 0;const[f,...d]=u;return o(Ot(f),d)},if(...u){const[f,d]=ne(u,0,[q.ANY]),h=xL(f);return h&&d0,m=i[d];return p&&He(m)&&a.command(...m),p?1:0},foreachstart(u,...f){const[d,h,p,m]=ne(f,0,[q.STRING,q.NUMBER,q.NUMBER,q.MAYBE_NUMBER]);let b=Math.min(h,p),_=Math.max(h,p);const w=(m??0)||1;if(w<0){const v=b;b=_,_=v}return a.set(d,b-w),0},foreach(u,...f){const[d,h,p,m,b]=ne(f,0,[q.STRING,q.NUMBER,q.NUMBER,q.MAYBE_NUMBER]);let _=Math.min(h,p),w=Math.max(h,p);const v=(m??0)||1;if(v<0){const I=_;_=w,w=I}let S=a.get(d);!ke(S)||S<_||S>w?S=_:S+=v;const L=S<=w?1:0;return L&&(a.set(d,S),bh?1:0},isLessThanOrEq(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d<=h?1:0},isGreaterThanOrEq(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d>=h?1:0},opPlus(u,f){const[d]=ne([u],0,[q.ANY]),[h]=ne([f],0,[q.ANY]);return d+h},opMinus(u,f){const[d]=ne([u],0,[q.ANY]),[h]=ne([f],0,[q.ANY]);return d-h},opPower(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return Math.pow(d,h)},opMultiply(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d*h},opDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d/h},opModDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return d%h},opFloorDivide(u,f){const[d]=ne([u],0,[q.NUMBER]),[h]=ne([f],0,[q.NUMBER]);return Math.floor(d/h)},opUniPlus(u){const[f]=ne([u],0,[q.NUMBER]);return+f},opUniMinus(u){const[f]=ne([u],0,[q.NUMBER]);return-f}};return s=(l=n.code)==null?void 0:l.call(n,a),a}function Sc(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var d_={exports:{}};/*! + + JSZip v3.10.1 - A JavaScript class for generating and reading zip files + + + (c) 2009-2016 Stuart Knightley + Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. + + JSZip uses the library pako released under the MIT license : + https://github.com/nodeca/pako/blob/main/LICENSE + */(function(t,e){(function(n){t.exports=n()})(function(){return function n(r,i,s){function o(l,u){if(!i[l]){if(!r[l]){var f=typeof Sc=="function"&⪼if(!u&&f)return f(l,!0);if(a)return a(l,!0);var d=new Error("Cannot find module '"+l+"'");throw d.code="MODULE_NOT_FOUND",d}var h=i[l]={exports:{}};r[l][0].call(h.exports,function(p){var m=r[l][1][p];return o(m||p)},h,h.exports,n,r,i,s)}return i[l].exports}for(var a=typeof Sc=="function"&&Sc,c=0;c>2,h=(3&l)<<4|u>>4,p=1>6:64,m=2>4,u=(15&d)<<4|(h=a.indexOf(c.charAt(m++)))>>2,f=(3&h)<<6|(p=a.indexOf(c.charAt(m++))),w[b++]=l,h!==64&&(w[b++]=u),p!==64&&(w[b++]=f);return w}},{"./support":30,"./utils":32}],2:[function(n,r,i){var s=n("./external"),o=n("./stream/DataWorker"),a=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function l(u,f,d,h,p){this.compressedSize=u,this.uncompressedSize=f,this.crc32=d,this.compression=h,this.compressedContent=p}l.prototype={getContentWorker:function(){var u=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),f=this;return u.on("end",function(){if(this.streamInfo.data_length!==f.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},l.createWorkerFrom=function(u,f,d){return u.pipe(new a).pipe(new c("uncompressedSize")).pipe(f.compressWorker(d)).pipe(new c("compressedSize")).withStreamInfo("compression",f)},r.exports=l},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,i){var s=n("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,i){var s=n("./utils"),o=function(){for(var a,c=[],l=0;l<256;l++){a=l;for(var u=0;u<8;u++)a=1&a?3988292384^a>>>1:a>>>1;c[l]=a}return c}();r.exports=function(a,c){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(l,u,f,d){var h=o,p=d+f;l^=-1;for(var m=d;m>>8^h[255&(l^u[m])];return-1^l}(0|c,a,a.length,0):function(l,u,f,d){var h=o,p=d+f;l^=-1;for(var m=d;m>>8^h[255&(l^u.charCodeAt(m))];return-1^l}(0|c,a,a.length,0):0}},{"./utils":32}],5:[function(n,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(n,r,i){var s=null;s=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:s}},{lie:37}],7:[function(n,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=n("pako"),a=n("./utils"),c=n("./stream/GenericWorker"),l=s?"uint8array":"array";function u(f,d){c.call(this,"FlateWorker/"+f),this._pako=null,this._pakoAction=f,this._pakoOptions=d,this.meta={}}i.magic="\b\0",a.inherits(u,c),u.prototype.processChunk=function(f){this.meta=f.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(l,f.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var f=this;this._pako.onData=function(d){f.push({data:d,meta:f.meta})}},i.compressWorker=function(f){return new u("Deflate",f)},i.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,i){function s(h,p){var m,b="";for(m=0;m>>=8;return b}function o(h,p,m,b,_,w){var v,S,L=h.file,I=h.compression,T=w!==l.utf8encode,M=a.transformTo("string",w(L.name)),x=a.transformTo("string",l.utf8encode(L.name)),V=L.comment,oe=a.transformTo("string",w(V)),O=a.transformTo("string",l.utf8encode(V)),E=x.length!==L.name.length,g=O.length!==V.length,C="",W="",B="",Z=L.dir,H=L.date,Y={crc32:0,compressedSize:0,uncompressedSize:0};p&&!m||(Y.crc32=h.crc32,Y.compressedSize=h.compressedSize,Y.uncompressedSize=h.uncompressedSize);var $=0;p&&($|=8),T||!E&&!g||($|=2048);var F=0,ue=0;Z&&(F|=16),_==="UNIX"?(ue=798,F|=function(ee,Ae){var je=ee;return ee||(je=Ae?16893:33204),(65535&je)<<16}(L.unixPermissions,Z)):(ue=20,F|=function(ee){return 63&(ee||0)}(L.dosPermissions)),v=H.getUTCHours(),v<<=6,v|=H.getUTCMinutes(),v<<=5,v|=H.getUTCSeconds()/2,S=H.getUTCFullYear()-1980,S<<=4,S|=H.getUTCMonth()+1,S<<=5,S|=H.getUTCDate(),E&&(W=s(1,1)+s(u(M),4)+x,C+="up"+s(W.length,2)+W),g&&(B=s(1,1)+s(u(oe),4)+O,C+="uc"+s(B.length,2)+B);var Q="";return Q+=` +\0`,Q+=s($,2),Q+=I.magic,Q+=s(v,2),Q+=s(S,2),Q+=s(Y.crc32,4),Q+=s(Y.compressedSize,4),Q+=s(Y.uncompressedSize,4),Q+=s(M.length,2),Q+=s(C.length,2),{fileRecord:f.LOCAL_FILE_HEADER+Q+M+C,dirRecord:f.CENTRAL_FILE_HEADER+s(ue,2)+Q+s(oe.length,2)+"\0\0\0\0"+s(F,4)+s(b,4)+M+C+oe}}var a=n("../utils"),c=n("../stream/GenericWorker"),l=n("../utf8"),u=n("../crc32"),f=n("../signature");function d(h,p,m,b){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=p,this.zipPlatform=m,this.encodeFileName=b,this.streamFiles=h,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(d,c),d.prototype.push=function(h){var p=h.meta.percent||0,m=this.entriesCount,b=this._sources.length;this.accumulate?this.contentBuffer.push(h):(this.bytesWritten+=h.data.length,c.prototype.push.call(this,{data:h.data,meta:{currentFile:this.currentFile,percent:m?(p+100*(m-b-1))/m:100}}))},d.prototype.openedSource=function(h){this.currentSourceOffset=this.bytesWritten,this.currentFile=h.file.name;var p=this.streamFiles&&!h.file.dir;if(p){var m=o(h,p,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:m.fileRecord,meta:{percent:0}})}else this.accumulate=!0},d.prototype.closedSource=function(h){this.accumulate=!1;var p=this.streamFiles&&!h.file.dir,m=o(h,p,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(m.dirRecord),p)this.push({data:function(b){return f.DATA_DESCRIPTOR+s(b.crc32,4)+s(b.compressedSize,4)+s(b.uncompressedSize,4)}(h),meta:{percent:100}});else for(this.push({data:m.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},d.prototype.flush=function(){for(var h=this.bytesWritten,p=0;p=this.index;c--)l=(l<<8)+this.byteAt(c);return this.index+=a,l},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},r.exports=o},{"../utils":32}],19:[function(n,r,i){var s=n("./Uint8ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,i){var s=n("./DataReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var c=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(n,r,i){var s=n("./ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,c},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,i){var s=n("../utils"),o=n("../support"),a=n("./ArrayReader"),c=n("./StringReader"),l=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(f){var d=s.getTypeOf(f);return s.checkSupport(d),d!=="string"||o.uint8array?d==="nodebuffer"?new l(f):o.uint8array?new u(s.transformTo("uint8array",f)):new a(s.transformTo("array",f)):new c(f)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,i){var s=n("./GenericWorker"),o=n("../utils");function a(c){s.call(this,"ConvertWorker to "+c),this.destType=c}o.inherits(a,s),a.prototype.processChunk=function(c){this.push({data:o.transformTo(this.destType,c.data),meta:c.meta})},r.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,i){var s=n("./GenericWorker"),o=n("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(a,s),a.prototype.processChunk=function(c){this.streamInfo.crc32=o(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(c){o.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}s.inherits(a,o),a.prototype.processChunk=function(c){if(c){var l=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=l+c.data.length}o.prototype.processChunk.call(this,c)},r.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(c){o.call(this,"DataWorker");var l=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){l.dataIsReady=!0,l.data=u,l.max=u&&u.length||0,l.type=s.getTypeOf(u),l.isPaused||l._tickAndRepeat()},function(u){l.error(u)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,l=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,l);break;case"uint8array":c=this.data.subarray(this.index,l);break;case"array":case"nodebuffer":c=this.data.slice(this.index,l)}return this.index=l,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var c=0;c "+o:o}},r.exports=s},{}],29:[function(n,r,i){var s=n("../utils"),o=n("./ConvertWorker"),a=n("./GenericWorker"),c=n("../base64"),l=n("../support"),u=n("../external"),f=null;if(l.nodestream)try{f=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function d(p,m){return new u.Promise(function(b,_){var w=[],v=p._internalType,S=p._outputType,L=p._mimeType;p.on("data",function(I,T){w.push(I),m&&m(T)}).on("error",function(I){w=[],_(I)}).on("end",function(){try{var I=function(T,M,x){switch(T){case"blob":return s.newBlob(s.transformTo("arraybuffer",M),x);case"base64":return c.encode(M);default:return s.transformTo(T,M)}}(S,function(T,M){var x,V=0,oe=null,O=0;for(x=0;x"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!n("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,i){for(var s=n("./utils"),o=n("./support"),a=n("./nodejsUtils"),c=n("./stream/GenericWorker"),l=new Array(256),u=0;u<256;u++)l[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;l[254]=l[254]=1;function f(){c.call(this,"utf-8 decode"),this.leftOver=null}function d(){c.call(this,"utf-8 encode")}i.utf8encode=function(h){return o.nodebuffer?a.newBufferFrom(h,"utf-8"):function(p){var m,b,_,w,v,S=p.length,L=0;for(w=0;w>>6:(b<65536?m[v++]=224|b>>>12:(m[v++]=240|b>>>18,m[v++]=128|b>>>12&63),m[v++]=128|b>>>6&63),m[v++]=128|63&b);return m}(h)},i.utf8decode=function(h){return o.nodebuffer?s.transformTo("nodebuffer",h).toString("utf-8"):function(p){var m,b,_,w,v=p.length,S=new Array(2*v);for(m=b=0;m>10&1023,S[b++]=56320|1023&_)}return S.length!==b&&(S.subarray?S=S.subarray(0,b):S.length=b),s.applyFromCharCode(S)}(h=s.transformTo(o.uint8array?"uint8array":"array",h))},s.inherits(f,c),f.prototype.processChunk=function(h){var p=s.transformTo(o.uint8array?"uint8array":"array",h.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var m=p;(p=new Uint8Array(m.length+this.leftOver.length)).set(this.leftOver,0),p.set(m,this.leftOver.length)}else p=this.leftOver.concat(p);this.leftOver=null}var b=function(w,v){var S;for((v=v||w.length)>w.length&&(v=w.length),S=v-1;0<=S&&(192&w[S])==128;)S--;return S<0||S===0?v:S+l[w[S]]>v?S:v}(p),_=p;b!==p.length&&(o.uint8array?(_=p.subarray(0,b),this.leftOver=p.subarray(b,p.length)):(_=p.slice(0,b),this.leftOver=p.slice(b,p.length))),this.push({data:i.utf8decode(_),meta:h.meta})},f.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=f,s.inherits(d,c),d.prototype.processChunk=function(h){this.push({data:i.utf8encode(h.data),meta:h.meta})},i.Utf8EncodeWorker=d},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,i){var s=n("./support"),o=n("./base64"),a=n("./nodejsUtils"),c=n("./external");function l(m){return m}function u(m,b){for(var _=0;_>8;this.dir=!!(16&this.externalFileAttributes),h==0&&(this.dosPermissions=63&this.externalFileAttributes),h==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var h=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=h.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=h.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=h.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=h.readInt(4))}},readExtraFields:function(h){var p,m,b,_=h.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});h.index+4<_;)p=h.readInt(2),m=h.readInt(2),b=h.readData(m),this.extraFields[p]={id:p,length:m,value:b};h.setIndex(_)},handleUTF8:function(){var h=f.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=l.utf8decode(this.fileName),this.fileCommentStr=l.utf8decode(this.fileComment);else{var p=this.findExtraFieldUnicodePath();if(p!==null)this.fileNameStr=p;else{var m=o.transformTo(h,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(m)}var b=this.findExtraFieldUnicodeComment();if(b!==null)this.fileCommentStr=b;else{var _=o.transformTo(h,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(_)}}},findExtraFieldUnicodePath:function(){var h=this.extraFields[28789];if(h){var p=s(h.value);return p.readInt(1)!==1||c(this.fileName)!==p.readInt(4)?null:l.utf8decode(p.readData(h.length-5))}return null},findExtraFieldUnicodeComment:function(){var h=this.extraFields[25461];if(h){var p=s(h.value);return p.readInt(1)!==1||c(this.fileComment)!==p.readInt(4)?null:l.utf8decode(p.readData(h.length-5))}return null}},r.exports=d},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,r,i){function s(p,m,b){this.name=p,this.dir=b.dir,this.date=b.date,this.comment=b.comment,this.unixPermissions=b.unixPermissions,this.dosPermissions=b.dosPermissions,this._data=m,this._dataBinary=b.binary,this.options={compression:b.compression,compressionOptions:b.compressionOptions}}var o=n("./stream/StreamHelper"),a=n("./stream/DataWorker"),c=n("./utf8"),l=n("./compressedObject"),u=n("./stream/GenericWorker");s.prototype={internalStream:function(p){var m=null,b="string";try{if(!p)throw new Error("No output type specified.");var _=(b=p.toLowerCase())==="string"||b==="text";b!=="binarystring"&&b!=="text"||(b="string"),m=this._decompressWorker();var w=!this._dataBinary;w&&!_&&(m=m.pipe(new c.Utf8EncodeWorker)),!w&&_&&(m=m.pipe(new c.Utf8DecodeWorker))}catch(v){(m=new u("error")).error(v)}return new o(m,b,"")},async:function(p,m){return this.internalStream(p).accumulate(m)},nodeStream:function(p,m){return this.internalStream(p||"nodebuffer").toNodejsStream(m)},_compressWorker:function(p,m){if(this._data instanceof l&&this._data.compression.magic===p.magic)return this._data.getCompressedWorker();var b=this._decompressWorker();return this._dataBinary||(b=b.pipe(new c.Utf8EncodeWorker)),l.createWorkerFrom(b,p,m)},_decompressWorker:function(){return this._data instanceof l?this._data.getContentWorker():this._data instanceof u?this._data:new a(this._data)}};for(var f=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],d=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},h=0;h>>6:(h<65536?d[b++]=224|h>>>12:(d[b++]=240|h>>>18,d[b++]=128|h>>>12&63),d[b++]=128|h>>>6&63),d[b++]=128|63&h);return d},i.buf2binstring=function(f){return u(f,f.length)},i.binstring2buf=function(f){for(var d=new s.Buf8(f.length),h=0,p=d.length;h>10&1023,w[p++]=56320|1023&m)}return u(w,p)},i.utf8border=function(f,d){var h;for((d=d||f.length)>f.length&&(d=f.length),h=d-1;0<=h&&(192&f[h])==128;)h--;return h<0||h===0?d:h+c[f[h]]>d?h:d}},{"./common":41}],43:[function(n,r,i){r.exports=function(s,o,a,c){for(var l=65535&s|0,u=s>>>16&65535|0,f=0;a!==0;){for(a-=f=2e3>>1:o>>>1;a[c]=o}return a}();r.exports=function(o,a,c,l){var u=s,f=l+c;o^=-1;for(var d=l;d>>8^u[255&(o^a[d])];return-1^o}},{}],46:[function(n,r,i){var s,o=n("../utils/common"),a=n("./trees"),c=n("./adler32"),l=n("./crc32"),u=n("./messages"),f=0,d=4,h=0,p=-2,m=-1,b=4,_=2,w=8,v=9,S=286,L=30,I=19,T=2*S+1,M=15,x=3,V=258,oe=V+x+1,O=42,E=113,g=1,C=2,W=3,B=4;function Z(y,K){return y.msg=u[K],K}function H(y){return(y<<1)-(4y.avail_out&&(G=y.avail_out),G!==0&&(o.arraySet(y.output,K.pending_buf,K.pending_out,G,y.next_out),y.next_out+=G,K.pending_out+=G,y.total_out+=G,y.avail_out-=G,K.pending-=G,K.pending===0&&(K.pending_out=0))}function F(y,K){a._tr_flush_block(y,0<=y.block_start?y.block_start:-1,y.strstart-y.block_start,K),y.block_start=y.strstart,$(y.strm)}function ue(y,K){y.pending_buf[y.pending++]=K}function Q(y,K){y.pending_buf[y.pending++]=K>>>8&255,y.pending_buf[y.pending++]=255&K}function ee(y,K){var G,R,A=y.max_chain_length,D=y.strstart,J=y.prev_length,X=y.nice_match,z=y.strstart>y.w_size-oe?y.strstart-(y.w_size-oe):0,te=y.window,le=y.w_mask,re=y.prev,de=y.strstart+V,Ze=te[D+J-1],Ue=te[D+J];y.prev_length>=y.good_match&&(A>>=2),X>y.lookahead&&(X=y.lookahead);do if(te[(G=K)+J]===Ue&&te[G+J-1]===Ze&&te[G]===te[D]&&te[++G]===te[D+1]){D+=2,G++;do;while(te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&te[++D]===te[++G]&&Dz&&--A!=0);return J<=y.lookahead?J:y.lookahead}function Ae(y){var K,G,R,A,D,J,X,z,te,le,re=y.w_size;do{if(A=y.window_size-y.lookahead-y.strstart,y.strstart>=re+(re-oe)){for(o.arraySet(y.window,y.window,re,re,0),y.match_start-=re,y.strstart-=re,y.block_start-=re,K=G=y.hash_size;R=y.head[--K],y.head[K]=re<=R?R-re:0,--G;);for(K=G=re;R=y.prev[--K],y.prev[K]=re<=R?R-re:0,--G;);A+=re}if(y.strm.avail_in===0)break;if(J=y.strm,X=y.window,z=y.strstart+y.lookahead,te=A,le=void 0,le=J.avail_in,te=x)for(D=y.strstart-y.insert,y.ins_h=y.window[D],y.ins_h=(y.ins_h<=x&&(y.ins_h=(y.ins_h<=x)if(R=a._tr_tally(y,y.strstart-y.match_start,y.match_length-x),y.lookahead-=y.match_length,y.match_length<=y.max_lazy_match&&y.lookahead>=x){for(y.match_length--;y.strstart++,y.ins_h=(y.ins_h<=x&&(y.ins_h=(y.ins_h<=x&&y.match_length<=y.prev_length){for(A=y.strstart+y.lookahead-x,R=a._tr_tally(y,y.strstart-1-y.prev_match,y.prev_length-x),y.lookahead-=y.prev_length-1,y.prev_length-=2;++y.strstart<=A&&(y.ins_h=(y.ins_h<y.pending_buf_size-5&&(G=y.pending_buf_size-5);;){if(y.lookahead<=1){if(Ae(y),y.lookahead===0&&K===f)return g;if(y.lookahead===0)break}y.strstart+=y.lookahead,y.lookahead=0;var R=y.block_start+G;if((y.strstart===0||y.strstart>=R)&&(y.lookahead=y.strstart-R,y.strstart=R,F(y,!1),y.strm.avail_out===0)||y.strstart-y.block_start>=y.w_size-oe&&(F(y,!1),y.strm.avail_out===0))return g}return y.insert=0,K===d?(F(y,!0),y.strm.avail_out===0?W:B):(y.strstart>y.block_start&&(F(y,!1),y.strm.avail_out),g)}),new _e(4,4,8,4,je),new _e(4,5,16,8,je),new _e(4,6,32,32,je),new _e(4,4,16,16,we),new _e(8,16,32,32,we),new _e(8,16,128,128,we),new _e(8,32,128,256,we),new _e(32,128,258,1024,we),new _e(32,258,258,4096,we)],i.deflateInit=function(y,K){return kt(y,K,w,15,8,0)},i.deflateInit2=kt,i.deflateReset=gt,i.deflateResetKeep=$e,i.deflateSetHeader=function(y,K){return y&&y.state?y.state.wrap!==2?p:(y.state.gzhead=K,h):p},i.deflate=function(y,K){var G,R,A,D;if(!y||!y.state||5>8&255),ue(R,R.gzhead.time>>16&255),ue(R,R.gzhead.time>>24&255),ue(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),ue(R,255&R.gzhead.os),R.gzhead.extra&&R.gzhead.extra.length&&(ue(R,255&R.gzhead.extra.length),ue(R,R.gzhead.extra.length>>8&255)),R.gzhead.hcrc&&(y.adler=l(y.adler,R.pending_buf,R.pending,0)),R.gzindex=0,R.status=69):(ue(R,0),ue(R,0),ue(R,0),ue(R,0),ue(R,0),ue(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),ue(R,3),R.status=E);else{var J=w+(R.w_bits-8<<4)<<8;J|=(2<=R.strategy||R.level<2?0:R.level<6?1:R.level===6?2:3)<<6,R.strstart!==0&&(J|=32),J+=31-J%31,R.status=E,Q(R,J),R.strstart!==0&&(Q(R,y.adler>>>16),Q(R,65535&y.adler)),y.adler=1}if(R.status===69)if(R.gzhead.extra){for(A=R.pending;R.gzindex<(65535&R.gzhead.extra.length)&&(R.pending!==R.pending_buf_size||(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending!==R.pending_buf_size));)ue(R,255&R.gzhead.extra[R.gzindex]),R.gzindex++;R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),R.gzindex===R.gzhead.extra.length&&(R.gzindex=0,R.status=73)}else R.status=73;if(R.status===73)if(R.gzhead.name){A=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending===R.pending_buf_size)){D=1;break}D=R.gzindexA&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),D===0&&(R.gzindex=0,R.status=91)}else R.status=91;if(R.status===91)if(R.gzhead.comment){A=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>A&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),$(y),A=R.pending,R.pending===R.pending_buf_size)){D=1;break}D=R.gzindexA&&(y.adler=l(y.adler,R.pending_buf,R.pending-A,A)),D===0&&(R.status=103)}else R.status=103;if(R.status===103&&(R.gzhead.hcrc?(R.pending+2>R.pending_buf_size&&$(y),R.pending+2<=R.pending_buf_size&&(ue(R,255&y.adler),ue(R,y.adler>>8&255),y.adler=0,R.status=E)):R.status=E),R.pending!==0){if($(y),y.avail_out===0)return R.last_flush=-1,h}else if(y.avail_in===0&&H(K)<=H(G)&&K!==d)return Z(y,-5);if(R.status===666&&y.avail_in!==0)return Z(y,-5);if(y.avail_in!==0||R.lookahead!==0||K!==f&&R.status!==666){var X=R.strategy===2?function(z,te){for(var le;;){if(z.lookahead===0&&(Ae(z),z.lookahead===0)){if(te===f)return g;break}if(z.match_length=0,le=a._tr_tally(z,0,z.window[z.strstart]),z.lookahead--,z.strstart++,le&&(F(z,!1),z.strm.avail_out===0))return g}return z.insert=0,te===d?(F(z,!0),z.strm.avail_out===0?W:B):z.last_lit&&(F(z,!1),z.strm.avail_out===0)?g:C}(R,K):R.strategy===3?function(z,te){for(var le,re,de,Ze,Ue=z.window;;){if(z.lookahead<=V){if(Ae(z),z.lookahead<=V&&te===f)return g;if(z.lookahead===0)break}if(z.match_length=0,z.lookahead>=x&&0z.lookahead&&(z.match_length=z.lookahead)}if(z.match_length>=x?(le=a._tr_tally(z,1,z.match_length-x),z.lookahead-=z.match_length,z.strstart+=z.match_length,z.match_length=0):(le=a._tr_tally(z,0,z.window[z.strstart]),z.lookahead--,z.strstart++),le&&(F(z,!1),z.strm.avail_out===0))return g}return z.insert=0,te===d?(F(z,!0),z.strm.avail_out===0?W:B):z.last_lit&&(F(z,!1),z.strm.avail_out===0)?g:C}(R,K):s[R.level].func(R,K);if(X!==W&&X!==B||(R.status=666),X===g||X===W)return y.avail_out===0&&(R.last_flush=-1),h;if(X===C&&(K===1?a._tr_align(R):K!==5&&(a._tr_stored_block(R,0,0,!1),K===3&&(Y(R.head),R.lookahead===0&&(R.strstart=0,R.block_start=0,R.insert=0))),$(y),y.avail_out===0))return R.last_flush=-1,h}return K!==d?h:R.wrap<=0?1:(R.wrap===2?(ue(R,255&y.adler),ue(R,y.adler>>8&255),ue(R,y.adler>>16&255),ue(R,y.adler>>24&255),ue(R,255&y.total_in),ue(R,y.total_in>>8&255),ue(R,y.total_in>>16&255),ue(R,y.total_in>>24&255)):(Q(R,y.adler>>>16),Q(R,65535&y.adler)),$(y),0=G.w_size&&(D===0&&(Y(G.head),G.strstart=0,G.block_start=0,G.insert=0),te=new o.Buf8(G.w_size),o.arraySet(te,K,le-G.w_size,G.w_size,0),K=te,le=G.w_size),J=y.avail_in,X=y.next_in,z=y.input,y.avail_in=le,y.next_in=0,y.input=K,Ae(G);G.lookahead>=x;){for(R=G.strstart,A=G.lookahead-(x-1);G.ins_h=(G.ins_h<>>=x=M>>>24,v-=x,(x=M>>>16&255)===0)C[u++]=65535&M;else{if(!(16&x)){if(!(64&x)){M=S[(65535&M)+(w&(1<>>=x,v-=x),v<15&&(w+=g[c++]<>>=x=M>>>24,v-=x,!(16&(x=M>>>16&255))){if(!(64&x)){M=L[(65535&M)+(w&(1<>>=x,v-=x,(x=u-f)>3,w&=(1<<(v-=V<<3))-1,s.next_in=c,s.next_out=u,s.avail_in=c>>24&255)+(O>>>8&65280)+((65280&O)<<8)+((255&O)<<24)}function w(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(O){var E;return O&&O.state?(E=O.state,O.total_in=O.total_out=E.total=0,O.msg="",E.wrap&&(O.adler=1&E.wrap),E.mode=p,E.last=0,E.havedict=0,E.dmax=32768,E.head=null,E.hold=0,E.bits=0,E.lencode=E.lendyn=new s.Buf32(m),E.distcode=E.distdyn=new s.Buf32(b),E.sane=1,E.back=-1,d):h}function S(O){var E;return O&&O.state?((E=O.state).wsize=0,E.whave=0,E.wnext=0,v(O)):h}function L(O,E){var g,C;return O&&O.state?(C=O.state,E<0?(g=0,E=-E):(g=1+(E>>4),E<48&&(E&=15)),E&&(E<8||15=B.wsize?(s.arraySet(B.window,E,g-B.wsize,B.wsize,0),B.wnext=0,B.whave=B.wsize):(C<(W=B.wsize-B.wnext)&&(W=C),s.arraySet(B.window,E,g-C,W,B.wnext),(C-=W)?(s.arraySet(B.window,E,g-C,C,0),B.wnext=C,B.whave=B.wsize):(B.wnext+=W,B.wnext===B.wsize&&(B.wnext=0),B.whave>>8&255,g.check=a(g.check,D,2,0),F=$=0,g.mode=2;break}if(g.flags=0,g.head&&(g.head.done=!1),!(1&g.wrap)||(((255&$)<<8)+($>>8))%31){O.msg="incorrect header check",g.mode=30;break}if((15&$)!=8){O.msg="unknown compression method",g.mode=30;break}if(F-=4,y=8+(15&($>>>=4)),g.wbits===0)g.wbits=y;else if(y>g.wbits){O.msg="invalid window size",g.mode=30;break}g.dmax=1<>8&1),512&g.flags&&(D[0]=255&$,D[1]=$>>>8&255,g.check=a(g.check,D,2,0)),F=$=0,g.mode=3;case 3:for(;F<32;){if(H===0)break e;H--,$+=C[B++]<>>8&255,D[2]=$>>>16&255,D[3]=$>>>24&255,g.check=a(g.check,D,4,0)),F=$=0,g.mode=4;case 4:for(;F<16;){if(H===0)break e;H--,$+=C[B++]<>8),512&g.flags&&(D[0]=255&$,D[1]=$>>>8&255,g.check=a(g.check,D,2,0)),F=$=0,g.mode=5;case 5:if(1024&g.flags){for(;F<16;){if(H===0)break e;H--,$+=C[B++]<>>8&255,g.check=a(g.check,D,2,0)),F=$=0}else g.head&&(g.head.extra=null);g.mode=6;case 6:if(1024&g.flags&&(H<(ee=g.length)&&(ee=H),ee&&(g.head&&(y=g.head.extra_len-g.length,g.head.extra||(g.head.extra=new Array(g.head.extra_len)),s.arraySet(g.head.extra,C,B,ee,y)),512&g.flags&&(g.check=a(g.check,C,ee,B)),H-=ee,B+=ee,g.length-=ee),g.length))break e;g.length=0,g.mode=7;case 7:if(2048&g.flags){if(H===0)break e;for(ee=0;y=C[B+ee++],g.head&&y&&g.length<65536&&(g.head.name+=String.fromCharCode(y)),y&&ee>9&1,g.head.done=!0),O.adler=g.check=0,g.mode=12;break;case 10:for(;F<32;){if(H===0)break e;H--,$+=C[B++]<>>=7&F,F-=7&F,g.mode=27;break}for(;F<3;){if(H===0)break e;H--,$+=C[B++]<>>=1)){case 0:g.mode=14;break;case 1:if(V(g),g.mode=20,E!==6)break;$>>>=2,F-=2;break e;case 2:g.mode=17;break;case 3:O.msg="invalid block type",g.mode=30}$>>>=2,F-=2;break;case 14:for($>>>=7&F,F-=7&F;F<32;){if(H===0)break e;H--,$+=C[B++]<>>16^65535)){O.msg="invalid stored block lengths",g.mode=30;break}if(g.length=65535&$,F=$=0,g.mode=15,E===6)break e;case 15:g.mode=16;case 16:if(ee=g.length){if(H>>=5,F-=5,g.ndist=1+(31&$),$>>>=5,F-=5,g.ncode=4+(15&$),$>>>=4,F-=4,286>>=3,F-=3}for(;g.have<19;)g.lens[J[g.have++]]=0;if(g.lencode=g.lendyn,g.lenbits=7,G={bits:g.lenbits},K=l(0,g.lens,0,19,g.lencode,0,g.work,G),g.lenbits=G.bits,K){O.msg="invalid code lengths set",g.mode=30;break}g.have=0,g.mode=19;case 19:for(;g.have>>16&255,Ge=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=C[B++]<>>=we,F-=we,g.lens[g.have++]=Ge;else{if(Ge===16){for(R=we+2;F>>=we,F-=we,g.have===0){O.msg="invalid bit length repeat",g.mode=30;break}y=g.lens[g.have-1],ee=3+(3&$),$>>>=2,F-=2}else if(Ge===17){for(R=we+3;F>>=we)),$>>>=3,F-=3}else{for(R=we+7;F>>=we)),$>>>=7,F-=7}if(g.have+ee>g.nlen+g.ndist){O.msg="invalid bit length repeat",g.mode=30;break}for(;ee--;)g.lens[g.have++]=y}}if(g.mode===30)break;if(g.lens[256]===0){O.msg="invalid code -- missing end-of-block",g.mode=30;break}if(g.lenbits=9,G={bits:g.lenbits},K=l(u,g.lens,0,g.nlen,g.lencode,0,g.work,G),g.lenbits=G.bits,K){O.msg="invalid literal/lengths set",g.mode=30;break}if(g.distbits=6,g.distcode=g.distdyn,G={bits:g.distbits},K=l(f,g.lens,g.nlen,g.ndist,g.distcode,0,g.work,G),g.distbits=G.bits,K){O.msg="invalid distances set",g.mode=30;break}if(g.mode=20,E===6)break e;case 20:g.mode=21;case 21:if(6<=H&&258<=Y){O.next_out=Z,O.avail_out=Y,O.next_in=B,O.avail_in=H,g.hold=$,g.bits=F,c(O,Q),Z=O.next_out,W=O.output,Y=O.avail_out,B=O.next_in,C=O.input,H=O.avail_in,$=g.hold,F=g.bits,g.mode===12&&(g.back=-1);break}for(g.back=0;_e=(A=g.lencode[$&(1<>>16&255,Ge=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=C[B++]<>$e)])>>>16&255,Ge=65535&A,!($e+(we=A>>>24)<=F);){if(H===0)break e;H--,$+=C[B++]<>>=$e,F-=$e,g.back+=$e}if($>>>=we,F-=we,g.back+=we,g.length=Ge,_e===0){g.mode=26;break}if(32&_e){g.back=-1,g.mode=12;break}if(64&_e){O.msg="invalid literal/length code",g.mode=30;break}g.extra=15&_e,g.mode=22;case 22:if(g.extra){for(R=g.extra;F>>=g.extra,F-=g.extra,g.back+=g.extra}g.was=g.length,g.mode=23;case 23:for(;_e=(A=g.distcode[$&(1<>>16&255,Ge=65535&A,!((we=A>>>24)<=F);){if(H===0)break e;H--,$+=C[B++]<>$e)])>>>16&255,Ge=65535&A,!($e+(we=A>>>24)<=F);){if(H===0)break e;H--,$+=C[B++]<>>=$e,F-=$e,g.back+=$e}if($>>>=we,F-=we,g.back+=we,64&_e){O.msg="invalid distance code",g.mode=30;break}g.offset=Ge,g.extra=15&_e,g.mode=24;case 24:if(g.extra){for(R=g.extra;F>>=g.extra,F-=g.extra,g.back+=g.extra}if(g.offset>g.dmax){O.msg="invalid distance too far back",g.mode=30;break}g.mode=25;case 25:if(Y===0)break e;if(ee=Q-Y,g.offset>ee){if((ee=g.offset-ee)>g.whave&&g.sane){O.msg="invalid distance too far back",g.mode=30;break}Ae=ee>g.wnext?(ee-=g.wnext,g.wsize-ee):g.wnext-ee,ee>g.length&&(ee=g.length),je=g.window}else je=W,Ae=Z-g.offset,ee=g.length;for(YT?(x=Ae[je+b[E]],F[ue+b[E]]):(x=96,0),w=1<>Z)+(v-=w)]=M<<24|x<<16|V|0,v!==0;);for(w=1<>=1;if(w!==0?($&=w-1,$+=w):$=0,E++,--Q[O]==0){if(O===C)break;O=f[d+b[E]]}if(W>>7)]}function ue(A,D){A.pending_buf[A.pending++]=255&D,A.pending_buf[A.pending++]=D>>>8&255}function Q(A,D,J){A.bi_valid>_-J?(A.bi_buf|=D<>_-A.bi_valid,A.bi_valid+=J-_):(A.bi_buf|=D<>>=1,J<<=1,0<--D;);return J>>>1}function je(A,D,J){var X,z,te=new Array(b+1),le=0;for(X=1;X<=b;X++)te[X]=le=le+J[X-1]<<1;for(z=0;z<=D;z++){var re=A[2*z+1];re!==0&&(A[2*z]=Ae(te[re]++,re))}}function we(A){var D;for(D=0;D>1;1<=J;J--)$e(A,te,J);for(z=de;J=A.heap[1],A.heap[1]=A.heap[A.heap_len--],$e(A,te,1),X=A.heap[1],A.heap[--A.heap_max]=J,A.heap[--A.heap_max]=X,te[2*z]=te[2*J]+te[2*X],A.depth[z]=(A.depth[J]>=A.depth[X]?A.depth[J]:A.depth[X])+1,te[2*J+1]=te[2*X+1]=z,A.heap[1]=z++,$e(A,te,1),2<=A.heap_len;);A.heap[--A.heap_max]=A.heap[1],function(Ue,kn){var Eo,sr,ko,ft,Rc,Wf,Or=kn.dyn_tree,x_=kn.max_code,fM=kn.stat_desc.static_tree,hM=kn.stat_desc.has_stree,dM=kn.stat_desc.extra_bits,R_=kn.stat_desc.extra_base,So=kn.stat_desc.max_length,Ic=0;for(ft=0;ft<=b;ft++)Ue.bl_count[ft]=0;for(Or[2*Ue.heap[Ue.heap_max]+1]=0,Eo=Ue.heap_max+1;Eo>=7;z>>=1)if(1&Ze&&re.dyn_ltree[2*de]!==0)return o;if(re.dyn_ltree[18]!==0||re.dyn_ltree[20]!==0||re.dyn_ltree[26]!==0)return a;for(de=32;de>>3,(te=A.static_len+3+7>>>3)<=z&&(z=te)):z=te=J+5,J+4<=z&&D!==-1?R(A,D,J,X):A.strategy===4||te===z?(Q(A,2+(X?1:0),3),gt(A,oe,O)):(Q(A,4+(X?1:0),3),function(re,de,Ze,Ue){var kn;for(Q(re,de-257,5),Q(re,Ze-1,5),Q(re,Ue-4,4),kn=0;kn>>8&255,A.pending_buf[A.d_buf+2*A.last_lit+1]=255&D,A.pending_buf[A.l_buf+A.last_lit]=255&J,A.last_lit++,D===0?A.dyn_ltree[2*J]++:(A.matches++,D--,A.dyn_ltree[2*(g[J]+f+1)]++,A.dyn_dtree[2*F(D)]++),A.last_lit===A.lit_bufsize-1},i._tr_align=function(A){Q(A,2,3),ee(A,v,oe),function(D){D.bi_valid===16?(ue(D,D.bi_buf),D.bi_buf=0,D.bi_valid=0):8<=D.bi_valid&&(D.pending_buf[D.pending++]=255&D.bi_buf,D.bi_buf>>=8,D.bi_valid-=8)}(A)}},{"../utils/common":41}],53:[function(n,r,i){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,i){(function(s){(function(o,a){if(!o.setImmediate){var c,l,u,f,d=1,h={},p=!1,m=o.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(o);b=b&&b.setTimeout?b:o,c={}.toString.call(o.process)==="[object process]"?function(S){process.nextTick(function(){w(S)})}:function(){if(o.postMessage&&!o.importScripts){var S=!0,L=o.onmessage;return o.onmessage=function(){S=!1},o.postMessage("","*"),o.onmessage=L,S}}()?(f="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",v,!1):o.attachEvent("onmessage",v),function(S){o.postMessage(f+S,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(S){w(S.data)},function(S){u.port2.postMessage(S)}):m&&"onreadystatechange"in m.createElement("script")?(l=m.documentElement,function(S){var L=m.createElement("script");L.onreadystatechange=function(){w(S),L.onreadystatechange=null,l.removeChild(L),L=null},l.appendChild(L)}):function(S){setTimeout(w,0,S)},b.setImmediate=function(S){typeof S!="function"&&(S=new Function(""+S));for(var L=new Array(arguments.length-1),I=0;I"u"?s===void 0?this:s:self)}).call(this,typeof Pt<"u"?Pt:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(d_);var IL=d_.exports,Bf=Ii(IL);const p_={"application/andrew-inset":["ez"],"application/appinstaller":["appinstaller"],"application/applixware":["aw"],"application/appx":["appx"],"application/appxbundle":["appxbundle"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/automationml-aml+xml":["aml"],"application/automationml-amlx+zip":["amlx"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cpl+xml":["cpl"],"application/cu-seeme":["cu"],"application/cwl":["cwl"],"application/dash+xml":["mpd"],"application/dash-patch+xml":["mpp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdf":["fdf"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["*js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/media-policy-dataset+xml":["mpf"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["*mp4","*mpg4","mp4s","m4p"],"application/msix":["msix"],"application/msixbundle":["msixbundle"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-keys":["asc"],"application/pgp-signature":["sig","*asc"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/sql":["sql"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/watcherinfo+xml":["wif"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xfdf":["xfdf"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/aac":["adts","aac"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avci":["avci"],"image/avcs":["avcs"],"image/avif":["avif"],"image/bmp":["bmp","dib"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/dpx":["dpx"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm","jpgm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/jt":["jt"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/prc":["prc"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/u3d":["u3d"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/javascript":["js","mjs"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["md","markdown"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/wgsl":["wgsl"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","*jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};Object.freeze(p_);var En=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},os,vo,Ti;class OL{constructor(...e){os.set(this,new Map),vo.set(this,new Map),Ti.set(this,new Map);for(const n of e)this.define(n)}define(e,n=!1){for(let[r,i]of Object.entries(e)){r=r.toLowerCase(),i=i.map(a=>a.toLowerCase()),En(this,Ti,"f").has(r)||En(this,Ti,"f").set(r,new Set);const s=En(this,Ti,"f").get(r);let o=!0;for(let a of i){const c=a.startsWith("*");if(a=c?a.slice(1):a,s==null||s.add(a),o&&En(this,vo,"f").set(r,a),o=!1,c)continue;const l=En(this,os,"f").get(a);if(l&&l!=r&&!n)throw new Error(`"${r} -> ${a}" conflicts with "${l} -> ${a}". Pass \`force=true\` to override this definition.`);En(this,os,"f").set(a,r)}}return this}getType(e){if(typeof e!="string")return null;const n=e.replace(/^.*[/\\]/,"").toLowerCase(),r=n.replace(/^.*\./,"").toLowerCase(),i=n.length{throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances")},Object.freeze(this);for(const e of En(this,Ti,"f").values())Object.freeze(e);return this}_getTestState(){return{types:En(this,os,"f"),extensions:En(this,vo,"f")}}}os=new WeakMap,vo=new WeakMap,Ti=new WeakMap;var NL=new OL(p_)._freeze();function m_(t,e){switch([...e.slice(0,4)].map(i=>i.toString(16)).join("").toUpperCase()){case"89504E47":return"image/png";case"47494638":return"image/gif";case"25504446":return"application/pdf";case"FFD8FFDB":case"FFD8FFE0":case"FFD8FFE1":return"image/jpeg";case"504B0304":return"application/zip"}return NL.getType(t)??"application/octet-stream"}function CL(t){const e=dy(t,{}),n=tr(e),r=lo(e),i=Un(We.MAIN);if(!k(i))return;const s=co(e),o=df(i,s,n);k(o)?Nt("memory",`${i.name} already has a [${r}] named ${n}`):(yy(i,e),__(e.id,i.id),Nt("memory",`created [${r}] ${n} in ${i.name}`))}async function LL(t){const e=await t.text();CL(e)}async function ML(t,e){try{Nt("parsezipfile",t.name);const n=await t.arrayBuffer();(await new Bf().loadAsync(n)).forEach((s,o)=>{o.async("uint8array").then(a=>{const c=m_(s,a),l=new File([a],o.name,{type:c});e(l)}).catch(a=>{tt("memory","crash",a.message)})})}catch(n){tt("memory","crash",n.message)}}async function UL(t,e){try{Nt("parsebinaryfile",t.name);const n=await t.arrayBuffer(),r=t.name.split(".").slice(-1)[0]??"";e(Pe(r),new Uint8Array(n))}catch(n){tt("memory","crash",n.message)}}function Ff(t){if(!t||t.type===void 0)return;const e=[{start:t.startOffset,end:t.endOffset??0}];return Object.keys(t).forEach(n=>{if(n!=="parent"){const r=t[n];He(r)?r.forEach(i=>{e.push(Ff(i))}):e.push(Ff(r))}}),t.range={start:Math.min(...e.filter(n=>n).map(n=>(n==null?void 0:n.start)??0)),end:Math.max(...e.filter(n=>n).map(n=>(n==null?void 0:n.end)??0))},t.range}function PL(t){const e=D0(`${t} +`);if(e.errors.length>0)return e;ss.input=e.tokens;const n=ss.program();if(ss.errors.length>0)return{tokens:e.tokens,errors:ss.errors.map(i=>({offset:i.token.startOffset,line:i.token.startLine,column:i.token.startColumn,length:i.token.image.length,message:i.message}))};const[r]=vL.go(n);return r?(Ff(r),{tokens:e.tokens,cst:n,ast:r}):{tokens:e.tokens,cst:n,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]}}const $f=Object.getPrototypeOf(function*(){}).constructor;function DL(t,e){const n=`compile-${t}`;console.time(n);const r=PL(e);if(console.timeEnd(n),r.errors&&r.errors.length>0)return r;if(!r.ast)return{...r,errors:[{message:"no ast output",offset:0,line:0,column:0,length:0}]};const i=TL(r.ast);if(i.code){rN&&console.info(i.code);try{return{...r,...i,source:i.code,code:new $f("api",i.code)}}catch(s){return{errors:[{message:`unexpected error ${s.message}`,offset:0,line:0,column:0,length:0}],source:"",code:new $f("api"," ")}}}return{...r,...i,source:"",code:new $f("api"," ")}}function BL(){const t={},e={};function n(i,s){const o=t[s];if(o)return o;const a=DL(i,s);return t[s]=a,a}const r={ids(){return Object.keys(e)},has(i){return k(e[i])},isended(i){const s=e[i];return k(s)?s.isended():!0},halt(i){const s=e[i];return k(s)&&(s.halt(),delete e[i]),!!s},gc(){const i=r.ids();for(let s=0;s[_,w]);p.slice(h-5,h).forEach(([_,w])=>{tt("os","build",`$grey${w+1} $grey${_}`)});const[m,b]=p[h]??[];if(Se(m)&&k(b)){const _=(d.column??1)-1,w=_+d.length,v=_{tt("os","build",_)}),!1}}return!!(l!=null&&l.tick(o))},once(i,s,o,a){const c=r.tick(i,s,1,o,a);return r.halt(i)&&c},message(i){const{target:s,path:o}=Zf(i.target),a=e[s];if(k(a)){const c={...i,target:o};a.message(c)}}};return r}const Rr=BL();var We=(t=>(t.MAIN="main",t.TITLE="title",t.PLAYER="player",t.CONTENT="content",t.GADGETSTORE="gadgetstore",t.GADGETSYNC="gadgetsync",t))(We||{});const it={defaultplayer:H_(),software:{main:"",content:""},books:new Map,chips:new Map,loaders:new Map,chipindex:new Map,codepageindex:new Map,binaryfiles:new Map};function FL(t){console.info("memorysetdefaultplayer",t),it.defaultplayer=t}function Jr(){return it.defaultplayer}function Ac(){return[...it.books.values()]}function $L(){const[t]=it.books.values();return t}function Xr(t){const e=Pe(t);return it.books.get(t)??Ac().find(n=>n.name===e)}function Tc(t,e){k(Xr(e))&&(it.software[t]=e)}function Ht(t){return Xr(it.software[t])}function g_(t){const e=gy([]);return Se(t)&&(e.name=t),y_(e),Nt("memory",`created [book] ${e.name}`),e}function jL(t){let e=Xr(t);return k(e)||(e=gy([]),e.name=t),y_(e),Nt("memory",`created [book] ${e.name}`),e}function Un(t,e){let n=k(e)?jL(e):Ht(t);return k(n)||(k(n)||(n=$L()),k(n)||(n=g_(e)),k(n)&&Nt("memory",`opened [book] ${n.name} for ${t}`)),Tc(t,n.id),n}function xi(t,e,n){const r=Un(t);let i=vi(r,e);if(k(i))return i;const s=py(n);return i=dy(s==="object"?`@${e} +`:`@${s} ${e} +`,{}),yy(r,i),__(i.id,r.id),$l("memory","",it.defaultplayer),i}function as(t){const e=Un("main");return es(e,t)}function zL(t){const e=Un("main");return pf(e,t)}function WL(t,e){it.books.clear(),t.forEach(r=>{it.books.set(r.id,r),r.name==="main"&&(it.software.main=r.id)});const n=Xr(e);if(k(n)&&Tc("main",n.id),!it.software.main){const r=it.books.values().next();r.value&&(it.software.main=r.value.id)}}function y_(t){return it.books.set(t.id,t),t.id}function GL(t){const e=Xr(t);e&&it.books.delete(e.id)}function __(t,e){it.codepageindex.set(t,e)}function HL(t){if(!Se(t)||!t)return tt("memory","login",`failed for playerid ==>${t}<==`,t);const e=Ht("main");if(!k(e))return tt("memory","login:main","login failed to find book 'main'",t);const n=lc(e,t);if(k(n))return!0;const r=Qi(e,"title");if(!k(r))return tt("memory","login:title","login failed to find board 'title'",t);const i=cc(e,"player");if(!k(i))return tt("memory","login:player","login failed to find object type 'player'",t);const s=i.name??"player",o=Ef(r,{x:0,y:0},s,t);return k(o==null?void 0:o.id)?(o.player=t,mf(e,t,r.id),!0):!1}function b_(t){const e=Ht("main"),n=lc(e,t);mf(e,t,""),uo(e,n,ns(n,t)),My(n,t),pf(e,t),pf(e,h_(t))}function VL(t){const e=Ht("main"),n=vy(e);for(let r=0;rIo*5&&(n.tickertime=0,n.tickertext=""),N.isplayer){const f=as(N.element.id??"");f.inputcurrent=0}pb(s).forEach(f=>{N[f]=s[f]})}function qL(){const t=Ht("main");if(!k(t))return;const e=t.timestamp+1,n=kc.HALT_AT_COUNT;kc.HALT_AT_COUNT=n*2,it.loaders.forEach((i,s)=>{Rr.tick(s,ho.LOADER,1,"loader",i),Rr.isended(s)&&(Rr.halt(s),it.loaders.delete(s))}),kc.HALT_AT_COUNT=n,t.timestamp=e,N.timestamp=e,vy(t).forEach(i=>{const s=VN(t,i,e);for(let o=0;o{const c=ao(a);return Object.keys(c).filter(u=>s.includes(Pe(u))).length===s.length});for(let a=0;att("memory","crash",i.message));break;case"application/zip":ML(e,i=>E_(t,i)).catch(i=>tt("memory","crash",i.message));break;case"application/octet-stream":UL(e,(i,s)=>{ZL(t,e,i,s)}).catch(i=>tt("memory","crash",i.message));break;default:e.arrayBuffer().then(i=>{const s=m_(e.name,new Uint8Array(i));if(s)n(s);else return tt("memory","loadfile",`unsupported file ${e.name}`)}).catch(i=>tt("memory","crash",i.message));return}}n((e==null?void 0:e.type)??"")}let k_=0;function YL(){switch(k_++){case 0:return be.BLUE;case 1:return be.GREEN;case 2:return be.CYAN;case 3:return be.RED;case 4:return be.PURPLE;case 5:return be.YELLOW;default:return k_=0,be.WHITE}}function QL(t,e,n,r,i,s){const o=[];let a=e;const c=a===0,l=ze,u=rn,f=c?be.BLACK:be.ONCLEAR,d=_p(t,a++,l,u,f);o.push(d);const h=sk(t,a++,l,u);o.push(h);const p=a++,m=ik(t,p);o.push(m);const b=_p(t,a++,l,u,be.ONCLEAR);o.push(b);const _={...i_(ze,rn,YL(),be.ONCLEAR),...b},w=ok(t,a++);i&&o.push(w),r.terrain.forEach((T,M)=>{if(T){const x=Mn(n,T);d.char[M]=T.char??(x==null?void 0:x.char)??0,d.color[M]=T.color??(x==null?void 0:x.color)??f,d.bg[M]=T.bg??(x==null?void 0:x.bg)??f,d.color[M]!==be.ONCLEAR&&(s[M]=d.color[M])}});const v=r.objects??{};Object.values(v).forEach(T=>{if(k(T.removed)||k(T.headless))return;const M=T.id??"",x=_y(n,T),V=rk(t,p,M),oe=T.lx??T.x??0,O=T.ly??T.y??0,E=oe+O*ze;if(V.x=T.x??0,V.y=T.y??0,V.char=T.char??(x==null?void 0:x.char)??1,V.color=T.color??(x==null?void 0:x.color)??be.WHITE,V.bg=T.bg??(x==null?void 0:x.bg)??be.ONBORROW,m.sprites.push(V),V.bg===be.ONSHADOW&&(V.bg=be.ONCLEAR,h.alphas[oe+O*l]=.5),V.bg===be.ONBORROW&&(V.bg=s[E]??be.BLACK),V.color!==be.ONCLEAR&&(s[E]=V.color),Se(T.tickertext)&&ke(T.tickertime)&&T.tickertext.length){const g=ze,C=dL(T.tickertext,g,rn-1),W=(C==null?void 0:C.measuredwidth)??1,B=T.x??0,Z=T.y??0,H=Zze&&(_.x=ze-W),_.x<0&&(_.x=0),hL(T.tickertext,_)}M===t&&(w.focusx=V.x,w.focusy=V.y,w.focusid=M)});function S(T,M){if(!(T<0||T>=ze||M<0||M>=rn))return h.alphas[T+M*ze]}const L=[[1,1,1,1,1],[1,3,5,3,1],[1,5,12,5,1],[1,3,5,3,1],[1,1,1,1,1]].flat(),I=new Array(h.alphas.length);for(let T=0;Tk(oe)?oe*L[O]:void 0).filter(k);I[T]=ui(Nk(V),0,1)}return h.alphas=I,o}function eM(t){const e=Ht("main"),n=lc(e,t),r=[];if(!k(e)||!k(n))return r;const i=new Array(ze*rn).fill(0),s=Qi(e,n.over??""),o=Qi(e,n.under??""),a=[s,n,o].filter(k);let c=0;for(let l=0;l{const e=Ht(We.MAIN),n=es(e,We.GADGETSTORE);let r=n[t];return k(r)||(n[t]=r=jl()),r});const S_=ls("gadgetserver",["tock"],t=>{const e=Ht(We.MAIN),n=(e==null?void 0:e.activelist)??[],r=es(e,We.GADGETSYNC);switch(t.target){case"tock":for(let i=0;i{const r=new Bf;for(let i=0;i{e(rM(i))}).catch(n)})}async function oM(t){return new Promise((e,n)=>{const r=new Bf;r.loadAsync(nM(t),{base64:!0}).then(async()=>{const i=[],s=[];r.forEach((o,a)=>s.push(a));for(let o=0;o{var e;switch(t.target){case"init":k(t.player)&&!T_&&(T_=!0,t.player,FL(t.player),Pn.reply(t,"ackinit",!0,t.player));break;case"books":t.player===Jr()&&jf("vm:books",async()=>{if(He(t.data)){const[n,r]=t.data,i=await oM(n),s=i.map(o=>o.name);WL(i,r),et(Pn.name(),`loading ${s.join(", ")}`),Pn.reply(t,"ackbooks",!0,t.player)}});break;case"login":t.player&&HL(t.player)&&(Ri[t.player]=0,et(Pn.name(),`login from ${t.player}`),Pn.reply(t,"acklogin",!0,t.player));break;case"endgame":t.player===Jr()&&jf("vm:endgame",async()=>{t.player&&(b_(t.player),FE("vm",t.player),await zf(),HE("vm",t.player))});break;case"doot":t.player&&(Ri[t.player]=0,fp(Pn.name(),"active",t.player));break;case"input":if(t.player){const n=as(t.player),[r=Ft.NONE,i=0]=t.data??[Ft.NONE,0];He(n.inputqueue)||(n.inputqueue=[]),r!==Ft.NONE&&n.inputqueue.push([r,i])}break;case"codewatch":if(t.player&&He(t.data)){const[n,r]=t.data;if(!k(cs[r])){const i=hp(n,r);cs[r]=gp(i,s=>{const o=Xr(n),a=vi(o,r);k(a)&&(a.code=s,UN(a))})}Ir[n]=Ir[n]??{},Ir[n][r]=Ir[n][r]??new Set,Ir[n][r].add(t.player)}break;case"coderelease":if(t.player&&He(t.data)){const[n,r]=t.data;k(Ir[n])&&k(Ir[n][r])&&(Ir[n][r].delete(t.player),Ir[n][r].size===0&&((e=cs[r])==null||e.call(cs),cs[r]=void 0))}break;case"tick":t.player!=="locked"&&qL();break;case"second":{VL(Ri);const n=Object.keys(Ri);for(let r=0;r=aM&&(delete Ri[i],b_(i),Nt(Pn.name(),"player logout",i),Pn.emit("logout",void 0,i))}bb()===!1&&++A_>=cM&&(A_=0,$l(Pn.name(),"",Jr()));break}case"flush":t.player===Jr()&&jf("vm:flush",async()=>{Se(t.data)?await zf(`${t.data} `):await zf()});break;case"cli":t.player===Jr()&&XL(t.player,t.data);break;case"loadfile":t.player===Jr()&&E_(t.player,t.data);break;default:KL(t);break}});function lM(){jE(Pn.name(),Jr())}const{forward:uM}=yb(t=>postMessage(t));onmessage=function(e){uM(e.data)},setTimeout(lM,100)})(); diff --git a/assets/stubspace-Mt81ZBb1.js b/assets/stubspace-Mt81ZBb1.js new file mode 100644 index 00000000..761c4c76 --- /dev/null +++ b/assets/stubspace-Mt81ZBb1.js @@ -0,0 +1,10 @@ +(function(){"use strict";const T=new Set,_={emit(e,r,t,s){_.invoke(he(e,r,t,s))},invoke(e){T.forEach(r=>r.handle(e))},connect(e){T.add(e)},disconnect(e){T.delete(e)}};var q=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},x={};(function(e){var r=q&&q.__spreadArray||function(a,l,c){if(c||arguments.length===2)for(var h=0,d=l.length,v;hc.length?l:c})}function n(a){return a.reduce(function(l,c){return l.lengthcrypto.getRandomValues(new Uint8Array(e)),te=(e,r,t)=>{let s=(2<{let o="";for(;;){let u=t(n),f=n;for(;f--;)if(o+=e[u[f]&s]||"",o.length===i)return o}}},B=(e,r=21)=>te(e,r,re),se=(e=21)=>{let r="",t=crypto.getRandomValues(new Uint8Array(e));for(;e--;)r+=ee[t[e]&63];return r};var H="abcdefghijklmnopqrstuvwxyz",F="ABCDEFGHIJKLMNOPQRSTUVWXYZ",$="0123456789",ne="346789ABCDEFGHJKLMNPQRTUVWXYabcdefghijkmnpqrtwxyz",ae="6789BCDFGHJKLMNPQRTWbcdfghjkmnpqrtwz";const ie=$,oe=H,le=F;var ue=ie+oe+le,k={lowercase:H,uppercase:F,numbers:$,nolookalikes:ne,nolookalikesSafe:ae,alphanumeric:ue};function Q(){return`sid_${se(12).replaceAll("-",".")}`}const fe=B(k.numbers,4),ce=B(`${k.numbers}${k.lowercase}`,16);function de(){return`pid_${fe()}_${ce()}`}function N(e){return e.toLowerCase().trim()}function he(e,r,t,s){return{id:Q(),target:e,sender:r,data:t,player:s}}function pe(e){const[r,...t]=e.split(":");return{target:r,path:t.join(":")}}function G(e,r,t){const s=Q(),n=N(e),i=r.map(N),o={id(){return s},name(){return e},topics(){return r},emit(u,f,a){_.emit(u,s,f,a)},reply(u,f,a,l){o.emit(`${u.sender}:${f}`,a,l)},handle(u){const{target:f,path:a}=pe(u.target),l=N(f);i.findIndex(c=>c==="all"||c===l)!==-1&&t(u),(s===f||l==="all"||n===l)&&t({...u,target:a})}};return _.connect(o),o}/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017-2022 Joachim Wester + * MIT licensed + */var ve=function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,n){s.__proto__=n}||function(s,n){for(var i in n)n.hasOwnProperty(i)&&(s[i]=n[i])},e(r,t)};return function(r,t){e(r,t);function s(){this.constructor=r}r.prototype=t===null?Object.create(t):(s.prototype=t.prototype,new s)}}(),ye=Object.prototype.hasOwnProperty;function R(e,r){return ye.call(e,r)}function P(e){if(Array.isArray(e)){for(var r=new Array(e.length),t=0;t=48&&s<=57){r++;continue}return!1}return!0}function g(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function K(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function L(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var r=0,t=e.length;r0&&f[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&h===void 0&&(a[d]===void 0?h=f.slice(0,l).join("/"):l==c-1&&(h=r.path),h!==void 0&&v(r,0,e,h)),l++,Array.isArray(a)){if(d==="-")d=a.length;else{if(t&&!I(d))throw new p("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,r,e);I(d)&&(d=~~d)}if(l>=c){if(t&&r.op==="add"&&d>a.length)throw new p("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,r,e);var o=ge[r.op].call(r,a,d,e);if(o.test===!1)throw new p("Test operation failed","TEST_OPERATION_FAILED",i,r,e);return o}}else if(l>=c){var o=b[r.op].call(r,a,d,e);if(o.test===!1)throw new p("Test operation failed","TEST_OPERATION_FAILED",i,r,e);return o}if(a=a[d],t&&l0)throw new p('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",r,e,t);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new p("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",r,e,t);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new p("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",r,e,t);if((e.op==="add"||e.op==="replace"||e.op==="test")&&L(e.value))throw new p("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",r,e,t);if(t){if(e.op=="add"){var n=e.path.split("/").length,i=s.split("/").length;if(n!==i+1&&n!==i)throw new p("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",r,e,t)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==s)throw new p("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",r,e,t)}else if(e.op==="move"||e.op==="copy"){var o={op:"_get",path:e.from,value:void 0},u=X([o],t);if(u&&u.name==="OPERATION_PATH_UNRESOLVABLE")throw new p("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",r,e,t)}}}else throw new p("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",r,e,t)}function X(e,r,t){try{if(!Array.isArray(e))throw new p("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(r)D(y(r),y(e),t||!0);else{t=t||E;for(var s=0;s0&&(e.patches=[],e.callback&&e.callback(s)),s}function S(e,r,t,s,n){if(r!==e){typeof r.toJSON=="function"&&(r=r.toJSON());for(var i=P(r),o=P(e),u=!1,f=o.length-1;f>=0;f--){var a=o[f],l=e[a];if(R(r,a)&&!(r[a]===void 0&&l!==void 0&&Array.isArray(r)===!1)){var c=r[a];typeof l=="object"&&l!=null&&typeof c=="object"&&c!=null&&Array.isArray(l)===Array.isArray(c)?S(l,c,t,s+"/"+g(a),n):l!==c&&(n&&t.push({op:"test",path:s+"/"+g(a),value:y(l)}),t.push({op:"replace",path:s+"/"+g(a),value:y(c)}))}else Array.isArray(e)===Array.isArray(r)?(n&&t.push({op:"test",path:s+"/"+g(a),value:y(l)}),t.push({op:"remove",path:s+"/"+g(a)}),u=!0):(n&&t.push({op:"test",path:s,value:e}),t.push({op:"replace",path:s,value:r}))}if(!(!u&&i.length==o.length))for(var f=0;f{r.has(i.id)||(r.add(i.id),e(i))});function n(){_.disconnect(s)}return{forward:t,disconnect:n}}function je(e,r){_.emit("started",e,void 0,r)}let z=de();const Z=G("stub",["init","second"],e=>{switch(e.target){case"init":z=(z||e.player)??"",Z.reply(e,"ackinit",!0,e.player);break}});function Ce(){je(Z.name(),z)}const{forward:Se}=De(e=>postMessage(e));onmessage=function(r){Se(r.data)},setTimeout(Ce,100)})(); diff --git a/index.html b/index.html index 0657ff43..66d2ffd0 100644 --- a/index.html +++ b/index.html @@ -4,7 +4,7 @@ - ZSS - main:0.20.35:4073cbc2eadd6c815c696c03fc2dfa170a1baa65 + ZSS - main:0.20.45:65e41c1f46855d3c27e618e07de02e4735bca24b @@ -36,7 +36,7 @@ }(window.location)) - +