@kayelaa/canvas 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var fe=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var me=(r,e)=>{for(var n in e)fe(r,n,{get:e[n],enumerable:!0})},Xe=(r,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ne(e))!Oe.call(r,s)&&s!==n&&fe(r,s,{get:()=>e[s],enumerable:!(i=$e(e,s))||i.enumerable});return r};var qe=r=>Xe(fe({},"__esModule",{value:!0}),r);var Kt={};me(Kt,{Kayla:()=>N,LEA:()=>$,default:()=>kt});module.exports=qe(Kt);var $={};me($,{DeltaTweenII:()=>re,ENVIRONMENT:()=>ge,GEmitterMemory:()=>ye,LeaEntityII:()=>z,LeaEventEmitter:()=>T,LeaGameII:()=>B,LeaRendererII:()=>X,LeaSceneII:()=>q,LeaSerializers:()=>Ee,LeaTickerII:()=>ne,LeaTimeout:()=>ie,LeaUtilsII:()=>k,LiaAudio:()=>U,LiaAudioSrc:()=>H,LiaOscSFX:()=>M,LiaSFXMap:()=>Je,NOTE_NAMES:()=>Re,RectLeaEntity:()=>W,Vector2:()=>A,colToRGBA:()=>We,defaultSFXConfig:()=>Te,editRGBA:()=>Ye,generateUUID:()=>Me,getAvoidAngle:()=>Ve,getEnvironment:()=>Ke,getNormalizedColor:()=>Be,getRayHit:()=>Le,isInitiallyMobile:()=>tt,isMobile:()=>De,isNode:()=>Y,isNote:()=>Qe,isWeb:()=>C,parseFillStyle:()=>ke,raycastAvoid:()=>et,scaleCoord:()=>je,setAnimInterval:()=>_e,sfxHit:()=>Ae,sfxJump:()=>Pe,sfxLaser:()=>Fe,sfxUIClick:()=>Se,sfxUIHover:()=>Ie,shortUID:()=>Ze,tinyUID:()=>se});var T=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let i=this.#e.get(e)||[];return i.push(n),this.#e.set(e,i),this}once(e,n){let i=(...s)=>{this.off(e,i),n(...s)};return this.on(e,i),this}off(e,n){let i=this.#e.get(e);if(!i)return this;let s=i.indexOf(n);return s>=0&&i.splice(s,1),this}emit(e,...n){let i=this.#e.get(e);if(!i||i.length===0){if(e==="error")throw n[0];return!1}return i.slice().forEach(s=>s(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},X=class extends T{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:i,cameraWidth:s,cameraHeight:o}={}){if(!C)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=i??e.height,this.#n=s??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,n=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,n),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!C)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!C||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!C||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},ne=class extends T{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(C&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new ie(e,this)}createTween(e,n=()=>{}){let i=new re(e),s=(o=0)=>{if(i.finished){this.off("tick",s);return}i.update(o)};return i.on("finish",()=>{this.off("tick",s)}),i.on("delta",o=>{n(o)}),this.on("tick",s),i}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=C&&!isFinite(this.tickInterval)?_e(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ee;(t=>{function r(a){return a===!0?1:0}t.booleanExport=r;function e(a){return a===0?!1:a===1}t.booleanImport=e;function n(a){return`${a.x}|${a.y}`}t.vec2Export=n;function i(a){let[u,c]=a.split("|"),y=parseFloat(u),v=parseFloat(c);if(isNaN(y)||isNaN(v))throw new Error(`Invalid Vector2 string: ${a}`);return new A(y,v)}t.vec2Import=i,t.booleanMap={mapExport:r,mapImport:e};function o(a){return u=>Number(u.toFixed(a))}t.createRounder=o;function d(a=10){return{mapExport(u){return Math.round(u/a)},mapImport(u){return u*a}}}t.createLowPrecision=d;function p(a){return Math.round(a)}t.lightWeightRounder=p;function l(a=100){return{mapExport(u){return Math.round(u*a)},mapImport(u){return u/a}}}t.createPercent=l;function h(a){let u=new Map(Object.entries(a));return{mapExport:c=>u.get(c)??null,mapImport:c=>Array.from(u.entries()).find(([y,v])=>v===c)?.[0]??null}}t.createLookup=h;function f(a){let u=a*(180/Math.PI);return Math.round((u%360+360)%360)}t.radToDeg=f;function g(a){return a*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:f,mapImport:g};function x(a=10){let u=d(a);return{mapExport(c){return u.mapExport(f(c))},mapImport(c){return u.mapImport(g(c))}}}t.createLowPrecisionRadToDeg=x})(Ee||={});var z=class r extends T{name="";scaleRotate=0;scale=1;constructor(e,n=0,i=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new A(n,i),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(n){this.emit("error",n)}}handleDraw(e){if(!(Y||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([s,{mapExport:o}])=>{let d=Reflect.get(this,s);return o?o(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(s=>!this.nonSerializableProperties.includes(s)&&!e.includes(s.toString())),i=Object.fromEntries(n.map(s=>{let o=Reflect.get(this,s);if(Y&&typeof o=="number"){let d=o.toString().split("."),l=(d[1]?d[1].length:0)>2?Number(o.toFixed(2)):o;return[s,l]}return[s,o]}));return JSON.parse(JSON.stringify(i))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let i={};for(let s=0;s<n.length;s++){let o=e[s];if(!o)break;let[d,{mapImport:p}]=o,l=n[s];if(p&&(l=p(l)),typeof d!="string")break;try{Reflect.set(i,d,l)}catch(h){console.error(h)}}return i}},q=class extends T{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!Y&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((i,s)=>i.z-s.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof z))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof z))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},B=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,i=16){this.ticker=new ne(i),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",s=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(s)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},k={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=k.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return k.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[k.randomInt(0,r.length-1)]},createBezier(r,e,n,i){function s(p,l,h,f,g){let b=1-p;return b*b*b*l+3*b*b*p*h+3*b*p*p*f+p*p*p*g}function o(p,l,h,f,g){let b=1-p;return 3*b*b*(h-l)+6*b*p*(f-h)+3*p*p*(g-f)}function d(p){let l=p;for(let h=0;h<6;h++){let f=s(l,0,r,n,1),g=o(l,0,r,n,1);if(g===0)break;l-=(f-p)/g}return k.clamp(l,0,1)}return function(l){l=k.clamp(l,0,1);let h=d(l);return s(h,0,e,i,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return k.normalizeRad(-r)},degToRadFlipY(r){return k.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=k.normalizeRad(r),e=k.normalizeRad(e);let n=k.normalizeRad(e-r),i=k.normalizeRad(r-e);return n<=i?1:-1}},re=class extends T{constructor({delta:e,ms:n,easing:i}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=i??(s=>s),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=k.clamp(this.elapsed/this.duration,0,1),i=this.easing(n),s=this.delta*i,o=s-this.lastValue;this.lastValue=s,this.emit("delta",o),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},W=class extends z{constructor(e,n=0,i=0,s=50,o=50){super(e,n,i),this.width=s,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},ie=class extends T{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(i=>this._resolve=i),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},A=class r{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),i=Math.sin(e);return new r(this.x*n-this.y*i,this.x*i+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),i=e.normalized();return n.x*i.x+n.y*i.y}lengthSquaredTo(e){let n=this.x-e.x,i=this.y-e.y;return n*n+i*i}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let n=this.x-e.x,i=this.y-e.y;return n*n+i*i}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function Be(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[i,s,o,d=1]=n[1].split(",").map(p=>parseFloat(p));return{r:Math.max(0,Math.min(255,Math.floor(i))),g:Math.max(0,Math.min(255,Math.floor(s))),b:Math.max(0,Math.min(255,Math.floor(o))),a:Math.max(0,Math.min(1,Math.floor(d*255)/255))}}return ke(r)}function We(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function ke(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,i,s;if(r.length===7)n=parseInt(r.slice(1,3),16),i=parseInt(r.slice(3,5),16),s=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),i=parseInt(r[2]+r[2],16),s=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:i,b:s,a:1}}let e=r.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function Ye(r,{r:e,g:n,b:i,a:s}={}){let[o,d,p,l,h]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??d}, ${n??p}, ${i??l}, ${s??(h||1)})`}function je(r,e,n){return n+(r-n)*e}function Ke(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var ge=Ke(),Y=ge==="node",C=ge==="web",U=class r{static unlock(){C&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=C?new AudioContext:null;static masterGain=C?this.audioCtx.createGain():null;static musicGain=C?this.audioCtx.createGain():null;static sfxGain=C?this.audioCtx.createGain():null;static{C&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,i,s;if(typeof caches<"u"&&(s=await caches.open(n),i=await s.match(e)),!i){if(i=await fetch(e),!i.ok)throw new Error(`Failed to fetch ${e}`);s&&await s.put(e,i.clone())}let o=await i.arrayBuffer(),d=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,i=1,s=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let d=new H(o);d.buffer=o;let p=1-.12,l=1+.12;d.playbackRate=i??p+Math.random()*(l-p);let h=this.audioCtx.createGain();h.gain.value=n,d.tempGain=h,d.connect(h),h.connect(this.sfxGain),d.onended=()=>{d.disconnect(),h.disconnect()},d.start(),s&&this.sfsx.set(e,{source:d,gain:h})}catch(o){console.error(o)}}static async playLoop(e,n=1,{loopStart:i=0,loopEnd:s=null,exclusive:o=!0,skipMS:d=0}={}){if(o)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let p=this.getCached(e);if(!p)return;let l=new H(p);l.buffer=p,l.loop=!0,typeof i=="number"&&(l.loopStart=i),typeof s=="number"&&(l.loopEnd=s);let h=this.audioCtx.createGain();h.gain.value=n,l.tempGain=h,l.playbackRate=1,l.onended=()=>{l.disconnect(),h.disconnect()},l.connect(h),h.connect(this.musicGain),l.start(0,d/1e3);let f=++this.loopIdCounter;return this.loops.set(f,{source:l,gain:h}),f}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:i=1,loop:s=!1,loopStart:o=0,loopEnd:d=null,isMusic:p=!1,gain:l=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let f=new H(h);f.loop=s,f.loopStart=o,f.loopEnd=typeof d=="number"?d:h.duration,f.playbackRate=i;let g=this.audioCtx.createGain();return g.gain.value=n,f.connect(g),f.tempGain=g,g.connect(l||(p?this.musicGain:this.sfxGain)),f.onended=()=>{f.disconnect(),g.disconnect()},f}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}},Re=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Qe(r){return Re.includes(r)}var H=class{numberOfInputs;numberOfOutputs;constructor(e,n=U.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=C?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let i=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-i/this.playbackRate,this.source.start(0,i),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,i){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,i!==void 0?this.source.start(this.context.currentTime+e,n,i):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let i=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%i}if(this.isPlaying=!1,e>0){let i=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,i),this.output.gain.linearRampToValueAtTime(0,i+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,i=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,i),e}disconnect(e,n,i){e===void 0?this.output.disconnect():this.output.disconnect(e,n,i)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Te={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},M=class r{constructor(e={}){this.ctx=U.audioCtx,this.cfg=structuredClone(Te),Object.assign(this.cfg,e)}ctx;cfg;play(e=U.sfxGain){let n=this.ctx,i=n.currentTime,s=this.cfg,o=n.createGain();o.gain.setValueAtTime(1e-4,i);let d=s.ampEnv;o.gain.exponentialRampToValueAtTime(d.volume,i+d.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),i+d.attack+d.decay),o.gain.exponentialRampToValueAtTime(1e-4,i+s.duration+d.release);let p=o,l;s.filter.enabled&&(l=n.createBiquadFilter(),l.type=s.filter.type,l.frequency.value=s.filter.freq,l.Q.value=s.filter.Q,l.connect(o),p=l);let h;if(s.osc.enabled){if(h=n.createOscillator(),h.type=s.osc.type,h.frequency.value=s.osc.freq,h.detune.value=s.osc.detune,s.pitchEnv.amount!==0){let a=Math.pow(2,s.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(s.osc.freq*a,i+s.pitchEnv.decay)}h.connect(p),h.start(i),h.stop(i+s.duration+d.release)}let f;if(s.noise.enabled){let a=n.sampleRate*s.duration,u=n.createBuffer(1,a,n.sampleRate),c=u.getChannelData(0);for(let y=0;y<a;y++)c[y]=(Math.random()*2-1)*s.noise.level;f=n.createBufferSource(),f.buffer=u,f.connect(p),f.start(i),f.stop(i+s.duration+d.release)}let g,b;s.lfo.enabled&&h&&(g=n.createOscillator(),g.frequency.value=s.lfo.rate,b=n.createGain(),b.gain.value=s.lfo.depth,g.connect(b),s.lfo.target==="freq"?b.connect(h.frequency):s.lfo.target==="gain"?b.connect(o.gain):s.lfo.target==="filter"&&l&&b.connect(l.frequency),g.start(i),g.stop(i+s.duration)),o.connect(e);let x=[h,f,g,b,l,o],t=i+s.duration+d.release;setTimeout(()=>{x.forEach(a=>a?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,n,i,s){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:i,release:s}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,i){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:i,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,i){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:i,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},Se=new M({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Ie=new M({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Pe=new M({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),Fe=new M({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),Ae=new M({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2}),Je=new Map([["ui_click",Se],["ui_hover",Ie],["jump",Pe],["laser",Fe],["hit",Ae]]);function Ze(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),i=Array.from(n).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}function se(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),i=Array.from(n).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}var ye=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${Me()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n)}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(i=>i!==n))}_emit(e,n){this.events[e]?.forEach(i=>i(n))}send(e,n){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,n)}_receive(e,n){e?this._emit(e,n):this._emit("message",n)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function Me(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let r=new Uint8Array(16);return crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128,[...r].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function _e(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Le(r,e,n,i,s){let o=Math.cos(s),d=Math.sin(s),p=[];if(o!==0){let l=(0-r)/o,h=e+l*d;l>0&&h>=0&&h<=i&&p.push({side:"left",t:l})}if(o!==0){let l=(n-r)/o,h=e+l*d;l>0&&h>=0&&h<=i&&p.push({side:"right",t:l})}if(d!==0){let l=(0-e)/d,h=r+l*o;l>0&&h>=0&&h<=n&&p.push({side:"top",t:l})}if(d!==0){let l=(i-e)/d,h=r+l*o;l>0&&h>=0&&h<=n&&p.push({side:"bottom",t:l})}return p.length===0?null:(p.sort((l,h)=>l.t-h.t),p[0])}function Ve(r,e){let n;switch(e){case"left":case"right":n=Math.PI-r;break;case"top":case"bottom":n=2*Math.PI-r;break}return(n%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function et(r,e,n,i,s){let o=Le(r,e,n,i,s);return o?{...o,avoidAngle:Ve(s,o.side)}:null}function De(){return Y?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var tt=De();var N={};me(N,{JSX:()=>ze,KaylaContext:()=>ae,KaylaFragment:()=>bt,KaylaInternals:()=>D,KaylaRect:()=>_,createContext:()=>at,createElement:()=>st,createGame:()=>nt,createReassignableObject:()=>vt,createRenderer:()=>it,createScene:()=>rt,createUseHook:()=>Ct,self:()=>xe,setLogLevel:()=>wt,useClick:()=>ht,useContext:()=>gt,useCurrentGame:()=>pt,useCurrentRenderer:()=>ft,useCurrentScene:()=>mt,useCurrentTicker:()=>yt,useDisposableRef:()=>xt,useEffect:()=>ve,useEntity:()=>dt,useExports:()=>he,useFiber:()=>He,useFiberControl:()=>we,useGlobalClick:()=>Ge,useInitialization:()=>oe,useNextStack:()=>Ce,usePaint:()=>ue,useRect:()=>le,useRef:()=>be,useSelf:()=>V,useShouldRefresh:()=>lt,useState:()=>ot,useTick:()=>ct,useViewportEffect:()=>ut});function nt({width:r,height:e,updateHz:n="frames"}){return new D.KaylaGame(r,e,n==="frames"?1/0:n)}function rt(r){let e=new q(r);return new D.KaylaScene(e)}function it(r){return new D.KaylaRenderer(r)}function st(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+se(),{type:r,props:n}}var _;(i=>{function r(s,o){return!(s.right<o.left||s.left>o.right||s.bottom<o.top||s.top>o.bottom)}i.rawCollision=r;function e(s,o,d){let p=o*Math.PI/180,l=Math.cos(p),h=Math.sin(p),f=1/0;return l>0&&(f=Math.min(f,(d.right-s.x)/l)),l<0&&(f=Math.min(f,(d.left-s.x)/l)),h>0&&(f=Math.min(f,(d.bottom-s.y)/h)),h<0&&(f=Math.min(f,(d.top-s.y)/h)),A.from(o).scale(f)}i.getCurrToBound=e;function n(s){let{left:o,right:d,top:p,bottom:l,width:h,height:f,x:g=0,y:b=0}=s;if(h===null||f===null)throw new Error("width and height are required");let x,t;if(o!=null&&d!=null){if(Math.abs(d-o-h)>1e-6)throw new Error("left, right, and width mismatch");x=o}else g!=null?x=g-h/2:o!=null?x=o:d!=null?x=d-h:x=0;if(p!=null&&l!=null){if(Math.abs(l-p-f)>1e-6)throw new Error("top, bottom, and height mismatch");t=p}else b!=null?t=b-f/2:p!=null?t=p:l!=null?t=l-f:t=0;return{left:x,right:x+h,top:t,bottom:t+f,width:h,height:f,x:x+h/2,y:t+f/2}}i.createRawRect=n})(_||={});var D;(b=>{class r extends B{#e;#t;constructor(t,a,u){super(t,a,u),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}b.KaylaGame=r;class e extends X{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",a=>{if(this.game)for(let u of this.game.scenes.values())u.handleDraw(a)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new T,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=a=>this.onPointerAll(a,"down"),this.onPointerUp=a=>this.onPointerAll(a,"up"),this.onPointerCancel=a=>this.onPointerAll(a,"cancel"),this.onPointerMove=a=>this.onPointerAll(a,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,a){this.pointerPosUpdater(t);let u=e.getClickType(t);if(u!=="invalid"){t.preventDefault();let c=this.getMousePos();this.pointerEvents.emit("action",c,u,a)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,a){let u=this.canvas.getBoundingClientRect(),c=(t-u.left)/u.width,y=(a-u.top)/u.height,v=c*this.viewportWidth*this.cameraWidth/u.width,K=y*this.viewportHeight*this.cameraHeight/u.height;return new A(v,K)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let a=u=>{t(u,new i)};return this.on("draw",a),()=>{this.off("draw",a)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}b.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return be(xe)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let a=be(null);return(a.current===null||a.current===void 0)&&(a.current=t()),a.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let a=this.current;a.onInits[this.current.useInitCallIndex]=t,a.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return V(()=>new b.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return V(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return V(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:a=>{t.setMaxChildren(a)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:a=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let c=this.current.state[this.current.useStateCallIndex]??new s(this.current,t,{alwaysRecall:a});return this.current.state[this.current.useStateCallIndex]=c,this.current.useStateCallIndex++,c}useShouldRefresh(t){let a=this.current;if(!a)throw new Error("useShouldRefresh must be called inside a component");a.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),a.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let u=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=u,this.current.useRefCallIndex++,u}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,a){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=a}useGlobalClick(t,a){if(!this.current)throw new Error("Hook 'useGlobalClick' must be executed in the top level scope of a component.");a??={},this.current.onGlobalClick[this.current.useGlobalClickCallIndex]={handler:t,config:a},this.current.useGlobalClickCallIndex++}useClick(t,a){if(!this.current)throw new Error("Hook 'useClick' must be executed in the top level scope of a component.");a??={};let u=this.current;Ge((c,y,v)=>{let K=u.entity;if(!K)return;let S=K.getRawRect(),j=_.createRawRect({x:c.x,y:c.y,width:3,height:3});_.rawCollision(S,j)&&t(c,y,v)},a)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,a,u,...c)=>{let y=t?.fc?.name||"anonymous",v=t?.key?` key=${t.key}`:"";this.logger[a](`${u} <${y}${v}>`,...c)}}}b.GlobalKayla=n;class i{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}b.KaylaEvent=i;class s{#e;#t;#n;alwaysRecall;constructor(t,a,{alwaysRecall:u=!1}={}){this.#t=t,this.#e=a??void 0,this.#n=Date.now(),this.alwaysRecall=u}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
1
+ "use strict";var fe=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var me=(r,e)=>{for(var n in e)fe(r,n,{get:e[n],enumerable:!0})},Xe=(r,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ne(e))!Oe.call(r,a)&&a!==n&&fe(r,a,{get:()=>e[a],enumerable:!(i=$e(e,a))||i.enumerable});return r};var qe=r=>Xe(fe({},"__esModule",{value:!0}),r);var Tt={};me(Tt,{Kayla:()=>N,LEA:()=>$,default:()=>kt});module.exports=qe(Tt);var $={};me($,{DeltaTweenII:()=>re,ENVIRONMENT:()=>be,GEmitterMemory:()=>ye,LeaEntityII:()=>z,LeaEventEmitter:()=>T,LeaGameII:()=>B,LeaRendererII:()=>X,LeaSceneII:()=>q,LeaSerializers:()=>Ee,LeaTickerII:()=>ne,LeaTimeout:()=>ie,LeaUtilsII:()=>K,LiaAudio:()=>U,LiaAudioSrc:()=>H,LiaOscSFX:()=>M,LiaSFXMap:()=>Je,NOTE_NAMES:()=>ke,RectLeaEntity:()=>W,Vector2:()=>A,colToRGBA:()=>We,defaultSFXConfig:()=>Te,editRGBA:()=>Ye,generateUUID:()=>Me,getAvoidAngle:()=>Ve,getEnvironment:()=>Re,getNormalizedColor:()=>Be,getRayHit:()=>Le,isInitiallyMobile:()=>tt,isMobile:()=>Ge,isNode:()=>Y,isNote:()=>Qe,isWeb:()=>C,parseFillStyle:()=>Ke,raycastAvoid:()=>et,scaleCoord:()=>je,setAnimInterval:()=>_e,sfxHit:()=>Ae,sfxJump:()=>Ie,sfxLaser:()=>Fe,sfxUIClick:()=>Pe,sfxUIHover:()=>Se,shortUID:()=>Ze,tinyUID:()=>se});var T=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let i=this.#e.get(e)||[];return i.push(n),this.#e.set(e,i),this}once(e,n){let i=(...a)=>{this.off(e,i),n(...a)};return this.on(e,i),this}off(e,n){let i=this.#e.get(e);if(!i)return this;let a=i.indexOf(n);return a>=0&&i.splice(a,1),this}emit(e,...n){let i=this.#e.get(e);if(!i||i.length===0){if(e==="error")throw n[0];return!1}return i.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},X=class extends T{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:i,cameraWidth:a,cameraHeight:o}={}){if(!C)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=i??e.height,this.#n=a??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,n=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,n),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!C)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!C||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!C||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},ne=class extends T{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(C&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new ie(e,this)}createTween(e,n=()=>{}){let i=new re(e),a=(o=0)=>{if(i.finished){this.off("tick",a);return}i.update(o)};return i.on("finish",()=>{this.off("tick",a)}),i.on("delta",o=>{n(o)}),this.on("tick",a),i}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=C&&!isFinite(this.tickInterval)?_e(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ee;(t=>{function r(s){return s===!0?1:0}t.booleanExport=r;function e(s){return s===0?!1:s===1}t.booleanImport=e;function n(s){return`${s.x}|${s.y}`}t.vec2Export=n;function i(s){let[u,c]=s.split("|"),y=parseFloat(u),v=parseFloat(c);if(isNaN(y)||isNaN(v))throw new Error(`Invalid Vector2 string: ${s}`);return new A(y,v)}t.vec2Import=i,t.booleanMap={mapExport:r,mapImport:e};function o(s){return u=>Number(u.toFixed(s))}t.createRounder=o;function d(s=10){return{mapExport(u){return Math.round(u/s)},mapImport(u){return u*s}}}t.createLowPrecision=d;function p(s){return Math.round(s)}t.lightWeightRounder=p;function l(s=100){return{mapExport(u){return Math.round(u*s)},mapImport(u){return u/s}}}t.createPercent=l;function h(s){let u=new Map(Object.entries(s));return{mapExport:c=>u.get(c)??null,mapImport:c=>Array.from(u.entries()).find(([y,v])=>v===c)?.[0]??null}}t.createLookup=h;function f(s){let u=s*(180/Math.PI);return Math.round((u%360+360)%360)}t.radToDeg=f;function b(s){return s*(Math.PI/180)}t.degToRad=b,t.angleRadToDeg={mapExport:f,mapImport:b};function x(s=10){let u=d(s);return{mapExport(c){return u.mapExport(f(c))},mapImport(c){return u.mapImport(b(c))}}}t.createLowPrecisionRadToDeg=x})(Ee||={});var z=class r extends T{name="";scaleRotate=0;scale=1;constructor(e,n=0,i=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new A(n,i),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(n){this.emit("error",n)}}handleDraw(e){if(!(Y||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:o}])=>{let d=Reflect.get(this,a);return o?o(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),i=Object.fromEntries(n.map(a=>{let o=Reflect.get(this,a);if(Y&&typeof o=="number"){let d=o.toString().split("."),l=(d[1]?d[1].length:0)>2?Number(o.toFixed(2)):o;return[a,l]}return[a,o]}));return JSON.parse(JSON.stringify(i))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let i={};for(let a=0;a<n.length;a++){let o=e[a];if(!o)break;let[d,{mapImport:p}]=o,l=n[a];if(p&&(l=p(l)),typeof d!="string")break;try{Reflect.set(i,d,l)}catch(h){console.error(h)}}return i}},q=class extends T{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!Y&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((i,a)=>i.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof z))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof z))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},B=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,i=16){this.ticker=new ne(i),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(a)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},K={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=K.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return K.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[K.randomInt(0,r.length-1)]},createBezier(r,e,n,i){function a(p,l,h,f,b){let g=1-p;return g*g*g*l+3*g*g*p*h+3*g*p*p*f+p*p*p*b}function o(p,l,h,f,b){let g=1-p;return 3*g*g*(h-l)+6*g*p*(f-h)+3*p*p*(b-f)}function d(p){let l=p;for(let h=0;h<6;h++){let f=a(l,0,r,n,1),b=o(l,0,r,n,1);if(b===0)break;l-=(f-p)/b}return K.clamp(l,0,1)}return function(l){l=K.clamp(l,0,1);let h=d(l);return a(h,0,e,i,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return K.normalizeRad(-r)},degToRadFlipY(r){return K.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=K.normalizeRad(r),e=K.normalizeRad(e);let n=K.normalizeRad(e-r),i=K.normalizeRad(r-e);return n<=i?1:-1}},re=class extends T{constructor({delta:e,ms:n,easing:i}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=i??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=K.clamp(this.elapsed/this.duration,0,1),i=this.easing(n),a=this.delta*i,o=a-this.lastValue;this.lastValue=a,this.emit("delta",o),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},W=class extends z{constructor(e,n=0,i=0,a=50,o=50){super(e,n,i),this.width=a,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},ie=class extends T{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(i=>this._resolve=i),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},A=class r{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),i=Math.sin(e);return new r(this.x*n-this.y*i,this.x*i+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),i=e.normalized();return n.x*i.x+n.y*i.y}lengthSquaredTo(e){let n=this.x-e.x,i=this.y-e.y;return n*n+i*i}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let n=this.x-e.x,i=this.y-e.y;return n*n+i*i}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function Be(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[i,a,o,d=1]=n[1].split(",").map(p=>parseFloat(p));return{r:Math.max(0,Math.min(255,Math.floor(i))),g:Math.max(0,Math.min(255,Math.floor(a))),b:Math.max(0,Math.min(255,Math.floor(o))),a:Math.max(0,Math.min(1,Math.floor(d*255)/255))}}return Ke(r)}function We(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function Ke(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,i,a;if(r.length===7)n=parseInt(r.slice(1,3),16),i=parseInt(r.slice(3,5),16),a=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),i=parseInt(r[2]+r[2],16),a=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:i,b:a,a:1}}let e=r.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function Ye(r,{r:e,g:n,b:i,a}={}){let[o,d,p,l,h]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??d}, ${n??p}, ${i??l}, ${a??(h||1)})`}function je(r,e,n){return n+(r-n)*e}function Re(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var be=Re(),Y=be==="node",C=be==="web",U=class r{static unlock(){C&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=C?new AudioContext:null;static masterGain=C?this.audioCtx.createGain():null;static musicGain=C?this.audioCtx.createGain():null;static sfxGain=C?this.audioCtx.createGain():null;static{C&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,i,a;if(typeof caches<"u"&&(a=await caches.open(n),i=await a.match(e)),!i){if(i=await fetch(e),!i.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,i.clone())}let o=await i.arrayBuffer(),d=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,i=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let d=new H(o);d.buffer=o;let p=1-.12,l=1+.12;d.playbackRate=i??p+Math.random()*(l-p);let h=this.audioCtx.createGain();h.gain.value=n,d.tempGain=h,d.connect(h),h.connect(this.sfxGain),d.onended=()=>{d.disconnect(),h.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:h})}catch(o){console.error(o)}}static async playLoop(e,n=1,{loopStart:i=0,loopEnd:a=null,exclusive:o=!0,skipMS:d=0}={}){if(o)for(let b of this.loops.keys())this.stopLoop(b);this.audioBufferCache.has(e)||await this.preLoad(e);let p=this.getCached(e);if(!p)return;let l=new H(p);l.buffer=p,l.loop=!0,typeof i=="number"&&(l.loopStart=i),typeof a=="number"&&(l.loopEnd=a);let h=this.audioCtx.createGain();h.gain.value=n,l.tempGain=h,l.playbackRate=1,l.onended=()=>{l.disconnect(),h.disconnect()},l.connect(h),h.connect(this.musicGain),l.start(0,d/1e3);let f=++this.loopIdCounter;return this.loops.set(f,{source:l,gain:h}),f}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:i=1,loop:a=!1,loopStart:o=0,loopEnd:d=null,isMusic:p=!1,gain:l=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let f=new H(h);f.loop=a,f.loopStart=o,f.loopEnd=typeof d=="number"?d:h.duration,f.playbackRate=i;let b=this.audioCtx.createGain();return b.gain.value=n,f.connect(b),f.tempGain=b,b.connect(l||(p?this.musicGain:this.sfxGain)),f.onended=()=>{f.disconnect(),b.disconnect()},f}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}},ke=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Qe(r){return ke.includes(r)}var H=class{numberOfInputs;numberOfOutputs;constructor(e,n=U.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=C?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let i=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-i/this.playbackRate,this.source.start(0,i),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,i){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,i!==void 0?this.source.start(this.context.currentTime+e,n,i):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let i=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%i}if(this.isPlaying=!1,e>0){let i=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,i),this.output.gain.linearRampToValueAtTime(0,i+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,i=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,i),e}disconnect(e,n,i){e===void 0?this.output.disconnect():this.output.disconnect(e,n,i)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Te={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},M=class r{constructor(e={}){this.ctx=U.audioCtx,this.cfg=structuredClone(Te),Object.assign(this.cfg,e)}ctx;cfg;play(e=U.sfxGain){let n=this.ctx,i=n.currentTime,a=this.cfg,o=n.createGain();o.gain.setValueAtTime(1e-4,i);let d=a.ampEnv;o.gain.exponentialRampToValueAtTime(d.volume,i+d.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),i+d.attack+d.decay),o.gain.exponentialRampToValueAtTime(1e-4,i+a.duration+d.release);let p=o,l;a.filter.enabled&&(l=n.createBiquadFilter(),l.type=a.filter.type,l.frequency.value=a.filter.freq,l.Q.value=a.filter.Q,l.connect(o),p=l);let h;if(a.osc.enabled){if(h=n.createOscillator(),h.type=a.osc.type,h.frequency.value=a.osc.freq,h.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let s=Math.pow(2,a.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(a.osc.freq*s,i+a.pitchEnv.decay)}h.connect(p),h.start(i),h.stop(i+a.duration+d.release)}let f;if(a.noise.enabled){let s=n.sampleRate*a.duration,u=n.createBuffer(1,s,n.sampleRate),c=u.getChannelData(0);for(let y=0;y<s;y++)c[y]=(Math.random()*2-1)*a.noise.level;f=n.createBufferSource(),f.buffer=u,f.connect(p),f.start(i),f.stop(i+a.duration+d.release)}let b,g;a.lfo.enabled&&h&&(b=n.createOscillator(),b.frequency.value=a.lfo.rate,g=n.createGain(),g.gain.value=a.lfo.depth,b.connect(g),a.lfo.target==="freq"?g.connect(h.frequency):a.lfo.target==="gain"?g.connect(o.gain):a.lfo.target==="filter"&&l&&g.connect(l.frequency),b.start(i),b.stop(i+a.duration)),o.connect(e);let x=[h,f,b,g,l,o],t=i+a.duration+d.release;setTimeout(()=>{x.forEach(s=>s?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,n,i,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:i,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,i){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:i,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,i){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:i,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},Pe=new M({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Se=new M({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Ie=new M({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),Fe=new M({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),Ae=new M({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2}),Je=new Map([["ui_click",Pe],["ui_hover",Se],["jump",Ie],["laser",Fe],["hit",Ae]]);function Ze(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),i=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}function se(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),i=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}var ye=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${Me()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n)}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(i=>i!==n))}_emit(e,n){this.events[e]?.forEach(i=>i(n))}send(e,n){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,n)}_receive(e,n){e?this._emit(e,n):this._emit("message",n)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function Me(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let r=new Uint8Array(16);return crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128,[...r].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function _e(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Le(r,e,n,i,a){let o=Math.cos(a),d=Math.sin(a),p=[];if(o!==0){let l=(0-r)/o,h=e+l*d;l>0&&h>=0&&h<=i&&p.push({side:"left",t:l})}if(o!==0){let l=(n-r)/o,h=e+l*d;l>0&&h>=0&&h<=i&&p.push({side:"right",t:l})}if(d!==0){let l=(0-e)/d,h=r+l*o;l>0&&h>=0&&h<=n&&p.push({side:"top",t:l})}if(d!==0){let l=(i-e)/d,h=r+l*o;l>0&&h>=0&&h<=n&&p.push({side:"bottom",t:l})}return p.length===0?null:(p.sort((l,h)=>l.t-h.t),p[0])}function Ve(r,e){let n;switch(e){case"left":case"right":n=Math.PI-r;break;case"top":case"bottom":n=2*Math.PI-r;break}return(n%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function et(r,e,n,i,a){let o=Le(r,e,n,i,a);return o?{...o,avoidAngle:Ve(a,o.side)}:null}function Ge(){return Y?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var tt=Ge();var N={};me(N,{JSX:()=>ze,KaylaContext:()=>ae,KaylaFragment:()=>vt,KaylaInternals:()=>G,KaylaRect:()=>_,createContext:()=>at,createElement:()=>st,createGame:()=>nt,createReassignableObject:()=>Ct,createRenderer:()=>it,createScene:()=>rt,createUseHook:()=>Kt,self:()=>xe,setLogLevel:()=>Et,useClick:()=>ct,useContext:()=>xt,useCurrentGame:()=>mt,useCurrentRenderer:()=>yt,useCurrentScene:()=>bt,useCurrentTicker:()=>gt,useDisposableRef:()=>wt,useEffect:()=>ve,useEntity:()=>ft,useExports:()=>he,useFiber:()=>He,useFiberControl:()=>we,useGlobalClick:()=>De,useGlobalPointer:()=>ht,useInitialization:()=>oe,useNextStack:()=>Ce,usePaint:()=>ue,usePointer:()=>dt,useRect:()=>le,useRef:()=>ge,useSelf:()=>V,useShouldRefresh:()=>lt,useState:()=>ot,useTick:()=>pt,useViewportEffect:()=>ut});function nt({width:r,height:e,updateHz:n="frames"}){return new G.KaylaGame(r,e,n==="frames"?1/0:n)}function rt(r){let e=new q(r);return new G.KaylaScene(e)}function it(r){return new G.KaylaRenderer(r)}function st(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+se(),{type:r,props:n}}var _;(i=>{function r(a,o){return!(a.right<o.left||a.left>o.right||a.bottom<o.top||a.top>o.bottom)}i.rawCollision=r;function e(a,o,d){let p=o*Math.PI/180,l=Math.cos(p),h=Math.sin(p),f=1/0;return l>0&&(f=Math.min(f,(d.right-a.x)/l)),l<0&&(f=Math.min(f,(d.left-a.x)/l)),h>0&&(f=Math.min(f,(d.bottom-a.y)/h)),h<0&&(f=Math.min(f,(d.top-a.y)/h)),A.from(o).scale(f)}i.getCurrToBound=e;function n(a){let{left:o,right:d,top:p,bottom:l,width:h,height:f,x:b=0,y:g=0}=a;if(h===null||f===null)throw new Error("width and height are required");let x,t;if(o!=null&&d!=null){if(Math.abs(d-o-h)>1e-6)throw new Error("left, right, and width mismatch");x=o}else b!=null?x=b-h/2:o!=null?x=o:d!=null?x=d-h:x=0;if(p!=null&&l!=null){if(Math.abs(l-p-f)>1e-6)throw new Error("top, bottom, and height mismatch");t=p}else g!=null?t=g-f/2:p!=null?t=p:l!=null?t=l-f:t=0;return{left:x,right:x+h,top:t,bottom:t+f,width:h,height:f,x:x+h/2,y:t+f/2}}i.createRawRect=n})(_||={});var G;(g=>{class r extends B{#e;#t;constructor(t,s,u){super(t,s,u),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}g.KaylaGame=r;class e extends X{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",s=>{if(this.game)for(let u of this.game.scenes.values())u.handleDraw(s)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new T,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=s=>this.onPointerAll(s,"down"),this.onPointerUp=s=>this.onPointerAll(s,"up"),this.onPointerCancel=s=>this.onPointerAll(s,"cancel"),this.onPointerMove=s=>this.onPointerAll(s,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,s){this.pointerPosUpdater(t);let u=e.getClickType(t);if(u!=="invalid"||s==="move"||s==="cancel"){t.preventDefault();let c=this.getMousePos();this.pointerEvents.emit("action",c,u,s)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,s){let u=this.canvas.getBoundingClientRect(),c=(t-u.left)/u.width,y=(s-u.top)/u.height,v=c*this.viewportWidth*this.cameraWidth/u.width,R=y*this.viewportHeight*this.cameraHeight/u.height;return new A(v,R)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let s=u=>{t(u,new i)};return this.on("draw",s),()=>{this.off("draw",s)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}g.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return ge(xe)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let s=ge(null);return(s.current===null||s.current===void 0)&&(s.current=t()),s.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let s=this.current;s.onInits[this.current.useInitCallIndex]=t,s.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return V(()=>new g.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return V(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return V(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:s=>{t.setMaxChildren(s)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:s=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let c=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:s});return this.current.state[this.current.useStateCallIndex]=c,this.current.useStateCallIndex++,c}useShouldRefresh(t){let s=this.current;if(!s)throw new Error("useShouldRefresh must be called inside a component");s.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),s.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let u=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=u,this.current.useRefCallIndex++,u}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,s){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=s}useGlobalPointer(t,s){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");s??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:s},this.current.useGlobalClickCallIndex++}usePointer(t,s){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");s??={};let u=this.current;De((c,y,v)=>{let R=u.entity;if(!R)return;let P=R.getRawRect(),j=_.createRawRect({x:c.x,y:c.y,width:3,height:3});_.rawCollision(P,j)&&t(c,y,v)},s)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,s,u,...c)=>{let y=t?.fc?.name||"anonymous",v=t?.key?` key=${t.key}`:"";this.logger[s](`${u} <${y}${v}>`,...c)}}}g.GlobalKayla=n;class i{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}g.KaylaEvent=i;class a{#e;#t;#n;alwaysRecall;constructor(t,s,{alwaysRecall:u=!1}={}){this.#t=t,this.#e=s??void 0,this.#n=Date.now(),this.alwaysRecall=u}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
2
2
  You probably wrote: const [value, setValue] = useState(...)
3
3
 
4
4
  \u2192 In Kayla write: const value = useState(...);
5
- \u2192 Then: value.get() / value.set(v) / value.add(n)`)}refreshBased(){return[this.set.bind(this),this.get()]}add(t,{recall:a}={}){this.set(this.get()+t,{recall:a})}multiply(t,{recall:a}={}){this.set(this.get()*t,{recall:a})}set(t,{recall:a=!1}={}){let u=this.#e;if(t===u)return;this.#e=t;let y=Date.now()-this.#n;a&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(a||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}b.KaylaInternalState=s;class o{#e;constructor(t){this.#e=t??void 0}#t;setSetter(t){this.#t=t}get current(){return this.#e}set current(t){this.#e=t,this.#t&&this.#t(this.#e)}}b.KaylaInternalRef=o;function d(x){return new o(x)}b.createReassignableRef=d;class p{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,a,u){if(!u)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=a,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=u.type,this.callProps=u.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalClick=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+se(),this.onViewportEffect=[]}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,a,u){try{for(let{handler:c,config:y}of this.onGlobalClick)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==u||y.type!=="any"&&y.type!==a)&&c(t,a,u)}catch(c){this.global.logger.error(c)}}resizeHook({width:t,height:a}){try{for(let u of this.onViewportEffect)u(this.getAttachedRenderer(),t,a)}catch(u){this.global.logger.error(u)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalClick;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let a=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${a} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let u=this.lastChildren.slice(0,this.maxSafeChildren),c=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=u;for(let y of c)y.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],a=this.detectedParent;for(;a;)t.push(a),a=a?.detectedParent;return t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(a=>a.instance===t)?.value}getEntityChain(){return this.getFiberChain().map(t=>t.entity)}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let t=0;t<this.watchedDeps.length;t++){let a=this.watchedDeps[t],u=this.lastDepStamps[t]??0;if(a.lastChanged>u)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let a;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let u=[];try{let c=this.fc(this.callProps)??[];if(c&&!Array.isArray(c)&&(c=[c]),!Array.isArray(c))throw new Error("Non array or non undefined children received.");for(let y of c)if(y.type===this.fc)throw new Error("Circular Component.");u=c}catch(c){a=c}if(this.global.restore(),this.updateChildren(u,!0),a)throw a}updateChildren(t,a){try{let u=[...t,...this.dynamicChildren],c=[],y=[];for(let v of u){let K=v.props?.key,S;K!=null&&(S=this.lastChildren.find(j=>j.key===K)),S||(S=new p(this.global,this.scene,v)),S.detectedParent=this,y.push(S),c.push(S)}for(let v of this.lastChildren)c.includes(v)||v.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let v of this.lastChildren)try{v.refresh()}catch(K){console.error(K)}}catch(u){console.error(u)}}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=this.onEffectDeps.some((a,u)=>{let c=this.lastStateDeps.at(u);if(c){let y=a.lastChanged,v=c.stamp;return y>v}})),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let a=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(c=>({stamp:c.lastChanged,stateRef:c}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new l(this,this.key);for(let c of this.refs)c.current===xe&&(c.current=this.entity);if(this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),a){this.onUnInits=[];for(let c of this.onInits){this.bindEvents();try{let y=c();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let c of this.onUnEffect??[])c()}catch(c){console.error(c)}let u=this.onEffect.map(c=>c()).filter(c=>c!==void 0);this.onUnEffect=u}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}b.KaylaFiber=p;class l extends W{#e;flags;getRawRect(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,a){super(a,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,a){return this.flags.set(t,a)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let a=new i;if(this.#e&&this.#e.onTick)for(let u of this.#e.onTick)u(t,a);a.isPrevented()}draw(t){let a=new i;if(this.#e&&this.#e.onPaint)for(let u of this.#e.onPaint)u(t,a);a.isPrevented()||super.draw(t)}getRect(){return new h(this.getFiber())}}b.KaylaRectEntity=l;class h{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}get entity(){return this.#e.entity??null}#t(){if(!this.#e)throw new Error("No fibers found.");if(!this.entity)throw new Error("The entity does NOT exist yet.")}isCollidingWith(t){return this.#t(),this.entity.isCollidingWith(t.entity)}get setFlag(){return this.#t(),this.entity.setFlag.bind(this.entity)}get getFlag(){return this.#t(),this.entity.getFlag.bind(this.entity)}get removeFlag(){return this.#t(),this.entity.removeFlag.bind(this.entity)}isHovered(){let t=this.getRaw(),a=this.#e.getAttachedRenderer().getMousePos(),u=_.createRawRect({x:a.x,y:a.y,width:3,height:3});return _.rawCollision(t,u)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}b.KaylaInternalRect=h;class f{constructor(t){this.#t=t,this.#e=null,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#t}getGame(){return this.#e}drawHandler(t){return this.#t.handleDraw(t)}attachTo(t){t.addScene(this.#t),this.#e=t}async spawn(t){let a=this.createFiber(t);await this.#e.delay(0),a.refresh()}createFiber(t){return new p(b.singleGlobalInstance,this,t)}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}b.KaylaScene=f,b.singleGlobalInstance=new b.GlobalKayla})(D||={});var ae=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let i=He();return oe(()=>{i.contextInfo={instance:this,value:e}}),he(this.Provider,()=>({value:e})),n}Provider;Consumer};function at(r){return new ae(r)}var m=D.singleGlobalInstance,ot=m.useState.bind(m),be=m.useRef.bind(m),lt=m.useShouldRefresh.bind(m),ve=m.useEffect.bind(m),ut=m.useViewportEffect.bind(m),Ge=m.useGlobalClick.bind(m),ht=m.useClick.bind(m),oe=m.useInitialization.bind(m),le=m.useRect.bind(m),ct=m.useTick.bind(m),ue=m.usePaint.bind(m),he=m.useExports.bind(m),V=m.useSelf.bind(m),we=m.useFiberControl.bind(m),He=m.useFiber.bind(m),dt=m.useEntity.bind(m),pt=m.useCurrentGame.bind(m),ft=m.useCurrentRenderer.bind(m),mt=m.useCurrentScene.bind(m),yt=m.useCurrentTicker.bind(m),gt=m.useContext.bind(m),xe=Symbol("self_ref");var Ce=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},bt=({children:r})=>Array.isArray(r)?[...r]:r;function xt(r){return D.createReassignableRef(r)}function vt(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(i,s,o){return s==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,s,o)},set(i,s,o,d){return Reflect.set(e.current,s,o,d)},has(i,s){return Reflect.has(e.current,s)},ownKeys(i){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(i,s){return Reflect.getOwnPropertyDescriptor(e.current,s)},deleteProperty(i,s){return Reflect.deleteProperty(e.current,s)}})}function wt(r){m.logLevel=r}function Ct(r){let e=r.name||"anonymous-custom-hook";return function(i){let s=m.current;if(!s)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let o=i??{};return r.memoize!==!1?V(()=>(s.global.logLevel==="debug"&&s.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${s.fc?.name||"anonymous"} key=${s.key||"no-key"}>`),r.onUse(s,m,o))):(s.global.logLevel==="debug"&&s.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${s.fc?.name||"anonymous"} key=${s.key||"no-key"}>`),r.onUse(s,m,o))}}var ze;(e=>e.id="kayla")(ze||={});Reflect.set(globalThis,"Kayla",N);var Et;(n=>(n.Flex=({align:i="stretch",children:s,direction:o="row",gap:d=0,justify:p="start",wrap:l="nowrap",getHeight:h,getWidth:f,getCenterX:g,getCenterY:b,color:x})=>{let t=we(),a=le(),u=V(()=>({recalc(){let c=Number(d)||0,y=g(),v=b(),K=f(),S=h();a.x=y,a.y=v,a.width=K,a.height=S;let Ue=t.getChildrenEntities().filter(Boolean).map(w=>w.getRect()).filter(w=>w.getFlag("flex-ignored")!==!0),I=o==="row",F=I?a.width:a.height,Rt=I?a.height:a.width,ce=0,O=0,de=[],Q=[];Ue.forEach(w=>{let J=I?w.width:w.height;ce+J>F&&l==="wrap"?(de.push({height:O,items:Q}),Q=[w],ce=J,O=I?w.height:w.width):(Q.push(w),ce+=J+c,O=Math.max(O,I?w.height:w.width))}),de.push({height:O,items:Q});let pe=0;de.forEach((w,J)=>{let P=w.items,L=P.reduce((E,Z)=>E+(I?Z.width:Z.height),0)+c*(P.length-1),R=0;p==="center"&&(R=(F-L)/2),p==="end"&&(R=F-L),p==="space-between"&&(R=0),p==="space-around"&&(R=(F-L)/(P.length*2)),p==="space-evenly"&&(R=(F-L)/(P.length+1)),P.forEach((E,Z)=>{E.z=a.z+1;let G=I?E.width:E.height,ee=I?E.height:E.width,te=0;i==="center"&&(te=(w.height-ee)/2),i==="end"&&(te=w.height-ee),i==="stretch"&&(I?E.height=w.height:E.width=w.height),I?(E.x=R+G/2,E.y=pe+te+ee/2):(E.x=pe+te+ee/2,E.y=R+G/2),p==="space-between"&&Z<P.length-1?R+=G+c+(F-L)/(P.length-1):p==="space-around"?R+=G+c+(F-L)/P.length:p==="space-evenly"?R+=G+c+(F-L)/(P.length+1):R+=G+c}),pe+=w.height+c})}}));return ue((c,y)=>{y.preventDefault(),c.fillStyle=x,c.fillRect(a.left,a.top,a.width,a.height)}),ve(()=>{Ce(()=>{u.recalc()})}),he(n.Flex,()=>({controls:u})),s},n.GenericBox=({color:i,width:s=20,height:o=20,x:d=0,y:p=0})=>{let l=le();oe(()=>{l.width=s,l.height=o,l.x=d,l.y=p}),ue((h,f)=>{f.preventDefault(),h.fillStyle=i,h.fillRect(l.left,l.top,l.width,l.height)})}))(Et||={});var kt={LEA:$,Kayla:N};0&&(module.exports={Kayla,LEA});
5
+ \u2192 Then: value.get() / value.set(v) / value.add(n)`)}refreshBased(){return[this.set.bind(this),this.get()]}add(t,{recall:s}={}){this.set(this.get()+t,{recall:s})}multiply(t,{recall:s}={}){this.set(this.get()*t,{recall:s})}set(t,{recall:s=!1}={}){let u=this.#e;if(t===u)return;this.#e=t;let y=Date.now()-this.#n;s&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(s||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}g.KaylaInternalState=a;class o{#e;constructor(t){this.#e=t??void 0}#t;setSetter(t){this.#t=t}get current(){return this.#e}set current(t){this.#e=t,this.#t&&this.#t(this.#e)}}g.KaylaInternalRef=o;function d(x){return new o(x)}g.createReassignableRef=d;class p{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,s,u){if(!u)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=s,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=u.type,this.callProps=u.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalPointer=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+se(),this.onViewportEffect=[]}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,s,u){try{for(let{handler:c,config:y}of this.onGlobalPointer)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==u||y.type!=="any"&&y.type!==s)&&c(t,s,u)}catch(c){this.global.logger.error(c)}}resizeHook({width:t,height:s}){try{for(let u of this.onViewportEffect)u(this.getAttachedRenderer(),t,s)}catch(u){this.global.logger.error(u)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalPointer;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let s=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${s} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let u=this.lastChildren.slice(0,this.maxSafeChildren),c=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=u;for(let y of c)y.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],s=this.detectedParent;for(;s;)t.push(s),s=s?.detectedParent;return t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(s=>s.instance===t)?.value}getEntityChain(){return this.getFiberChain().map(t=>t.entity)}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let t=0;t<this.watchedDeps.length;t++){let s=this.watchedDeps[t],u=this.lastDepStamps[t]??0;if(s.lastChanged>u)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let s;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let u=[];try{let c=this.fc(this.callProps)??[];if(c&&!Array.isArray(c)&&(c=[c]),!Array.isArray(c))throw new Error("Non array or non undefined children received.");for(let y of c)if(y.type===this.fc)throw new Error("Circular Component.");u=c}catch(c){s=c}if(this.global.restore(),this.updateChildren(u,!0),s)throw s}updateChildren(t,s){try{let u=[...t,...this.dynamicChildren],c=[],y=[];for(let v of u){let R=v.props?.key,P;R!=null&&(P=this.lastChildren.find(j=>j.key===R)),P||(P=new p(this.global,this.scene,v)),P.detectedParent=this,y.push(P),c.push(P)}for(let v of this.lastChildren)c.includes(v)||v.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let v of this.lastChildren)try{v.refresh()}catch(R){console.error(R)}}catch(u){console.error(u)}}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=this.onEffectDeps.some((s,u)=>{let c=this.lastStateDeps.at(u);if(c){let y=s.lastChanged,v=c.stamp;return y>v}})),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let s=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(c=>({stamp:c.lastChanged,stateRef:c}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new l(this,this.key);for(let c of this.refs)c.current===xe&&(c.current=this.entity);if(this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),s){this.onUnInits=[];for(let c of this.onInits){this.bindEvents();try{let y=c();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let c of this.onUnEffect??[])c()}catch(c){console.error(c)}let u=this.onEffect.map(c=>c()).filter(c=>c!==void 0);this.onUnEffect=u}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}g.KaylaFiber=p;class l extends W{#e;flags;getRawRect(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,s){super(s,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,s){return this.flags.set(t,s)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let s=new i;if(this.#e&&this.#e.onTick)for(let u of this.#e.onTick)u(t,s);s.isPrevented()}draw(t){let s=new i;if(this.#e&&this.#e.onPaint)for(let u of this.#e.onPaint)u(t,s);s.isPrevented()||super.draw(t)}getRect(){return new h(this.getFiber())}}g.KaylaRectEntity=l;class h{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}get entity(){return this.#e.entity??null}#t(){if(!this.#e)throw new Error("No fibers found.");if(!this.entity)throw new Error("The entity does NOT exist yet.")}isCollidingWith(t){return this.#t(),this.entity.isCollidingWith(t.entity)}get setFlag(){return this.#t(),this.entity.setFlag.bind(this.entity)}get getFlag(){return this.#t(),this.entity.getFlag.bind(this.entity)}get removeFlag(){return this.#t(),this.entity.removeFlag.bind(this.entity)}isHovered(){let t=this.getRaw(),s=this.#e.getAttachedRenderer().getMousePos(),u=_.createRawRect({x:s.x,y:s.y,width:3,height:3});return _.rawCollision(t,u)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}g.KaylaInternalRect=h;class f{constructor(t){this.#t=t,this.#e=null,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#t}getGame(){return this.#e}drawHandler(t){return this.#t.handleDraw(t)}attachTo(t){t.addScene(this.#t),this.#e=t}async spawn(t){let s=this.createFiber(t);await this.#e.delay(0),s.refresh()}createFiber(t){return new p(g.singleGlobalInstance,this,t)}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}g.KaylaScene=f,g.singleGlobalInstance=new g.GlobalKayla})(G||={});var ae=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let i=He();return oe(()=>{i.contextInfo={instance:this,value:e}}),he(this.Provider,()=>({value:e})),n}Provider;Consumer};function at(r){return new ae(r)}var m=G.singleGlobalInstance,ot=m.useState.bind(m),ge=m.useRef.bind(m),lt=m.useShouldRefresh.bind(m),ve=m.useEffect.bind(m),ut=m.useViewportEffect.bind(m),De=m.useGlobalPointer.bind(m),ht=m.useGlobalPointer.bind(m),ct=m.usePointer.bind(m),dt=m.usePointer.bind(m),oe=m.useInitialization.bind(m),le=m.useRect.bind(m),pt=m.useTick.bind(m),ue=m.usePaint.bind(m),he=m.useExports.bind(m),V=m.useSelf.bind(m),we=m.useFiberControl.bind(m),He=m.useFiber.bind(m),ft=m.useEntity.bind(m),mt=m.useCurrentGame.bind(m),yt=m.useCurrentRenderer.bind(m),bt=m.useCurrentScene.bind(m),gt=m.useCurrentTicker.bind(m),xt=m.useContext.bind(m),xe=Symbol("self_ref");var Ce=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},vt=({children:r})=>Array.isArray(r)?[...r]:r;function wt(r){return G.createReassignableRef(r)}function Ct(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(i,a,o){return a==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,a,o)},set(i,a,o,d){return Reflect.set(e.current,a,o,d)},has(i,a){return Reflect.has(e.current,a)},ownKeys(i){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(i,a){return Reflect.getOwnPropertyDescriptor(e.current,a)},deleteProperty(i,a){return Reflect.deleteProperty(e.current,a)}})}function Et(r){m.logLevel=r}function Kt(r){let e=r.name||"anonymous-custom-hook";return function(i){let a=m.current;if(!a)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let o=i??{};return r.memoize!==!1?V(()=>(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,o))):(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,o))}}var ze;(e=>e.id="kayla")(ze||={});Reflect.set(globalThis,"Kayla",N);var Rt;(n=>(n.Flex=({align:i="stretch",children:a,direction:o="row",gap:d=0,justify:p="start",wrap:l="nowrap",getHeight:h,getWidth:f,getCenterX:b,getCenterY:g,color:x})=>{let t=we(),s=le(),u=V(()=>({recalc(){let c=Number(d)||0,y=b(),v=g(),R=f(),P=h();s.x=y,s.y=v,s.width=R,s.height=P;let Ue=t.getChildrenEntities().filter(Boolean).map(w=>w.getRect()).filter(w=>w.getFlag("flex-ignored")!==!0),S=o==="row",F=S?s.width:s.height,Pt=S?s.height:s.width,ce=0,O=0,de=[],Q=[];Ue.forEach(w=>{let J=S?w.width:w.height;ce+J>F&&l==="wrap"?(de.push({height:O,items:Q}),Q=[w],ce=J,O=S?w.height:w.width):(Q.push(w),ce+=J+c,O=Math.max(O,S?w.height:w.width))}),de.push({height:O,items:Q});let pe=0;de.forEach((w,J)=>{let I=w.items,L=I.reduce((E,Z)=>E+(S?Z.width:Z.height),0)+c*(I.length-1),k=0;p==="center"&&(k=(F-L)/2),p==="end"&&(k=F-L),p==="space-between"&&(k=0),p==="space-around"&&(k=(F-L)/(I.length*2)),p==="space-evenly"&&(k=(F-L)/(I.length+1)),I.forEach((E,Z)=>{E.z=s.z+1;let D=S?E.width:E.height,ee=S?E.height:E.width,te=0;i==="center"&&(te=(w.height-ee)/2),i==="end"&&(te=w.height-ee),i==="stretch"&&(S?E.height=w.height:E.width=w.height),S?(E.x=k+D/2,E.y=pe+te+ee/2):(E.x=pe+te+ee/2,E.y=k+D/2),p==="space-between"&&Z<I.length-1?k+=D+c+(F-L)/(I.length-1):p==="space-around"?k+=D+c+(F-L)/I.length:p==="space-evenly"?k+=D+c+(F-L)/(I.length+1):k+=D+c}),pe+=w.height+c})}}));return ue((c,y)=>{y.preventDefault(),c.fillStyle=x,c.fillRect(s.left,s.top,s.width,s.height)}),ve(()=>{Ce(()=>{u.recalc()})}),he(n.Flex,()=>({controls:u})),a},n.GenericBox=({color:i,width:a=20,height:o=20,x:d=0,y:p=0})=>{let l=le();oe(()=>{l.width=a,l.height=o,l.x=d,l.y=p}),ue((h,f)=>{f.preventDefault(),h.fillStyle=i,h.fillRect(l.left,l.top,l.width,l.height)})}))(Rt||={});var kt={LEA:$,Kayla:N};0&&(module.exports={Kayla,LEA});
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { L as LEA } from './lea-B1DIEiLR.cjs';
2
- import { K as Kayla } from './kayla-internals-BnnDnUVI.cjs';
2
+ import { K as Kayla } from './kayla-internals-yPNDC4nT.cjs';
3
3
 
4
4
  declare const _default: {
5
5
  LEA: typeof LEA;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { L as LEA } from './lea-B1DIEiLR.js';
2
- import { K as Kayla } from './kayla-internals-uYrgURKn.js';
2
+ import { K as Kayla } from './kayla-internals-DR1hPIET.js';
3
3
 
4
4
  declare const _default: {
5
5
  LEA: typeof LEA;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- var Ue=Object.defineProperty;var we=(r,e)=>{for(var n in e)Ue(r,n,{get:e[n],enumerable:!0})};var W={};we(W,{DeltaTweenII:()=>re,ENVIRONMENT:()=>me,GEmitterMemory:()=>fe,LeaEntityII:()=>z,LeaEventEmitter:()=>T,LeaGameII:()=>X,LeaRendererII:()=>N,LeaSceneII:()=>O,LeaSerializers:()=>Ce,LeaTickerII:()=>ne,LeaTimeout:()=>ie,LeaUtilsII:()=>k,LiaAudio:()=>U,LiaAudioSrc:()=>H,LiaOscSFX:()=>M,LiaSFXMap:()=>Be,NOTE_NAMES:()=>Ke,RectLeaEntity:()=>q,Vector2:()=>A,colToRGBA:()=>Ne,defaultSFXConfig:()=>Re,editRGBA:()=>Oe,generateUUID:()=>Ae,getAvoidAngle:()=>Le,getEnvironment:()=>ke,getNormalizedColor:()=>$e,getRayHit:()=>_e,isInitiallyMobile:()=>je,isMobile:()=>Ve,isNode:()=>B,isNote:()=>qe,isWeb:()=>C,parseFillStyle:()=>Ee,raycastAvoid:()=>Ye,scaleCoord:()=>Xe,setAnimInterval:()=>Me,sfxHit:()=>Fe,sfxJump:()=>Ie,sfxLaser:()=>Pe,sfxUIClick:()=>Te,sfxUIHover:()=>Se,shortUID:()=>We,tinyUID:()=>se});var T=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let i=this.#e.get(e)||[];return i.push(n),this.#e.set(e,i),this}once(e,n){let i=(...a)=>{this.off(e,i),n(...a)};return this.on(e,i),this}off(e,n){let i=this.#e.get(e);if(!i)return this;let a=i.indexOf(n);return a>=0&&i.splice(a,1),this}emit(e,...n){let i=this.#e.get(e);if(!i||i.length===0){if(e==="error")throw n[0];return!1}return i.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},N=class extends T{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:i,cameraWidth:a,cameraHeight:o}={}){if(!C)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=i??e.height,this.#n=a??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,n=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,n),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!C)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!C||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!C||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},ne=class extends T{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(C&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new ie(e,this)}createTween(e,n=()=>{}){let i=new re(e),a=(o=0)=>{if(i.finished){this.off("tick",a);return}i.update(o)};return i.on("finish",()=>{this.off("tick",a)}),i.on("delta",o=>{n(o)}),this.on("tick",a),i}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=C&&!isFinite(this.tickInterval)?Me(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ce;(t=>{function r(s){return s===!0?1:0}t.booleanExport=r;function e(s){return s===0?!1:s===1}t.booleanImport=e;function n(s){return`${s.x}|${s.y}`}t.vec2Export=n;function i(s){let[u,c]=s.split("|"),y=parseFloat(u),v=parseFloat(c);if(isNaN(y)||isNaN(v))throw new Error(`Invalid Vector2 string: ${s}`);return new A(y,v)}t.vec2Import=i,t.booleanMap={mapExport:r,mapImport:e};function o(s){return u=>Number(u.toFixed(s))}t.createRounder=o;function d(s=10){return{mapExport(u){return Math.round(u/s)},mapImport(u){return u*s}}}t.createLowPrecision=d;function p(s){return Math.round(s)}t.lightWeightRounder=p;function l(s=100){return{mapExport(u){return Math.round(u*s)},mapImport(u){return u/s}}}t.createPercent=l;function h(s){let u=new Map(Object.entries(s));return{mapExport:c=>u.get(c)??null,mapImport:c=>Array.from(u.entries()).find(([y,v])=>v===c)?.[0]??null}}t.createLookup=h;function f(s){let u=s*(180/Math.PI);return Math.round((u%360+360)%360)}t.radToDeg=f;function g(s){return s*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:f,mapImport:g};function x(s=10){let u=d(s);return{mapExport(c){return u.mapExport(f(c))},mapImport(c){return u.mapImport(g(c))}}}t.createLowPrecisionRadToDeg=x})(Ce||={});var z=class r extends T{name="";scaleRotate=0;scale=1;constructor(e,n=0,i=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new A(n,i),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(n){this.emit("error",n)}}handleDraw(e){if(!(B||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:o}])=>{let d=Reflect.get(this,a);return o?o(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),i=Object.fromEntries(n.map(a=>{let o=Reflect.get(this,a);if(B&&typeof o=="number"){let d=o.toString().split("."),l=(d[1]?d[1].length:0)>2?Number(o.toFixed(2)):o;return[a,l]}return[a,o]}));return JSON.parse(JSON.stringify(i))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let i={};for(let a=0;a<n.length;a++){let o=e[a];if(!o)break;let[d,{mapImport:p}]=o,l=n[a];if(p&&(l=p(l)),typeof d!="string")break;try{Reflect.set(i,d,l)}catch(h){console.error(h)}}return i}},O=class extends T{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!B&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((i,a)=>i.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof z))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof z))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},X=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,i=16){this.ticker=new ne(i),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(a)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},k={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=k.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return k.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[k.randomInt(0,r.length-1)]},createBezier(r,e,n,i){function a(p,l,h,f,g){let b=1-p;return b*b*b*l+3*b*b*p*h+3*b*p*p*f+p*p*p*g}function o(p,l,h,f,g){let b=1-p;return 3*b*b*(h-l)+6*b*p*(f-h)+3*p*p*(g-f)}function d(p){let l=p;for(let h=0;h<6;h++){let f=a(l,0,r,n,1),g=o(l,0,r,n,1);if(g===0)break;l-=(f-p)/g}return k.clamp(l,0,1)}return function(l){l=k.clamp(l,0,1);let h=d(l);return a(h,0,e,i,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return k.normalizeRad(-r)},degToRadFlipY(r){return k.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=k.normalizeRad(r),e=k.normalizeRad(e);let n=k.normalizeRad(e-r),i=k.normalizeRad(r-e);return n<=i?1:-1}},re=class extends T{constructor({delta:e,ms:n,easing:i}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=i??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=k.clamp(this.elapsed/this.duration,0,1),i=this.easing(n),a=this.delta*i,o=a-this.lastValue;this.lastValue=a,this.emit("delta",o),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},q=class extends z{constructor(e,n=0,i=0,a=50,o=50){super(e,n,i),this.width=a,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},ie=class extends T{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(i=>this._resolve=i),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},A=class r{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),i=Math.sin(e);return new r(this.x*n-this.y*i,this.x*i+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),i=e.normalized();return n.x*i.x+n.y*i.y}lengthSquaredTo(e){let n=this.x-e.x,i=this.y-e.y;return n*n+i*i}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let n=this.x-e.x,i=this.y-e.y;return n*n+i*i}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function $e(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[i,a,o,d=1]=n[1].split(",").map(p=>parseFloat(p));return{r:Math.max(0,Math.min(255,Math.floor(i))),g:Math.max(0,Math.min(255,Math.floor(a))),b:Math.max(0,Math.min(255,Math.floor(o))),a:Math.max(0,Math.min(1,Math.floor(d*255)/255))}}return Ee(r)}function Ne(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function Ee(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,i,a;if(r.length===7)n=parseInt(r.slice(1,3),16),i=parseInt(r.slice(3,5),16),a=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),i=parseInt(r[2]+r[2],16),a=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:i,b:a,a:1}}let e=r.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function Oe(r,{r:e,g:n,b:i,a}={}){let[o,d,p,l,h]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??d}, ${n??p}, ${i??l}, ${a??(h||1)})`}function Xe(r,e,n){return n+(r-n)*e}function ke(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var me=ke(),B=me==="node",C=me==="web",U=class r{static unlock(){C&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=C?new AudioContext:null;static masterGain=C?this.audioCtx.createGain():null;static musicGain=C?this.audioCtx.createGain():null;static sfxGain=C?this.audioCtx.createGain():null;static{C&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,i,a;if(typeof caches<"u"&&(a=await caches.open(n),i=await a.match(e)),!i){if(i=await fetch(e),!i.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,i.clone())}let o=await i.arrayBuffer(),d=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,i=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let d=new H(o);d.buffer=o;let p=1-.12,l=1+.12;d.playbackRate=i??p+Math.random()*(l-p);let h=this.audioCtx.createGain();h.gain.value=n,d.tempGain=h,d.connect(h),h.connect(this.sfxGain),d.onended=()=>{d.disconnect(),h.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:h})}catch(o){console.error(o)}}static async playLoop(e,n=1,{loopStart:i=0,loopEnd:a=null,exclusive:o=!0,skipMS:d=0}={}){if(o)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let p=this.getCached(e);if(!p)return;let l=new H(p);l.buffer=p,l.loop=!0,typeof i=="number"&&(l.loopStart=i),typeof a=="number"&&(l.loopEnd=a);let h=this.audioCtx.createGain();h.gain.value=n,l.tempGain=h,l.playbackRate=1,l.onended=()=>{l.disconnect(),h.disconnect()},l.connect(h),h.connect(this.musicGain),l.start(0,d/1e3);let f=++this.loopIdCounter;return this.loops.set(f,{source:l,gain:h}),f}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:i=1,loop:a=!1,loopStart:o=0,loopEnd:d=null,isMusic:p=!1,gain:l=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let f=new H(h);f.loop=a,f.loopStart=o,f.loopEnd=typeof d=="number"?d:h.duration,f.playbackRate=i;let g=this.audioCtx.createGain();return g.gain.value=n,f.connect(g),f.tempGain=g,g.connect(l||(p?this.musicGain:this.sfxGain)),f.onended=()=>{f.disconnect(),g.disconnect()},f}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}},Ke=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function qe(r){return Ke.includes(r)}var H=class{numberOfInputs;numberOfOutputs;constructor(e,n=U.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=C?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let i=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-i/this.playbackRate,this.source.start(0,i),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,i){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,i!==void 0?this.source.start(this.context.currentTime+e,n,i):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let i=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%i}if(this.isPlaying=!1,e>0){let i=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,i),this.output.gain.linearRampToValueAtTime(0,i+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,i=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,i),e}disconnect(e,n,i){e===void 0?this.output.disconnect():this.output.disconnect(e,n,i)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Re={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},M=class r{constructor(e={}){this.ctx=U.audioCtx,this.cfg=structuredClone(Re),Object.assign(this.cfg,e)}ctx;cfg;play(e=U.sfxGain){let n=this.ctx,i=n.currentTime,a=this.cfg,o=n.createGain();o.gain.setValueAtTime(1e-4,i);let d=a.ampEnv;o.gain.exponentialRampToValueAtTime(d.volume,i+d.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),i+d.attack+d.decay),o.gain.exponentialRampToValueAtTime(1e-4,i+a.duration+d.release);let p=o,l;a.filter.enabled&&(l=n.createBiquadFilter(),l.type=a.filter.type,l.frequency.value=a.filter.freq,l.Q.value=a.filter.Q,l.connect(o),p=l);let h;if(a.osc.enabled){if(h=n.createOscillator(),h.type=a.osc.type,h.frequency.value=a.osc.freq,h.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let s=Math.pow(2,a.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(a.osc.freq*s,i+a.pitchEnv.decay)}h.connect(p),h.start(i),h.stop(i+a.duration+d.release)}let f;if(a.noise.enabled){let s=n.sampleRate*a.duration,u=n.createBuffer(1,s,n.sampleRate),c=u.getChannelData(0);for(let y=0;y<s;y++)c[y]=(Math.random()*2-1)*a.noise.level;f=n.createBufferSource(),f.buffer=u,f.connect(p),f.start(i),f.stop(i+a.duration+d.release)}let g,b;a.lfo.enabled&&h&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,b=n.createGain(),b.gain.value=a.lfo.depth,g.connect(b),a.lfo.target==="freq"?b.connect(h.frequency):a.lfo.target==="gain"?b.connect(o.gain):a.lfo.target==="filter"&&l&&b.connect(l.frequency),g.start(i),g.stop(i+a.duration)),o.connect(e);let x=[h,f,g,b,l,o],t=i+a.duration+d.release;setTimeout(()=>{x.forEach(s=>s?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,n,i,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:i,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,i){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:i,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,i){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:i,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},Te=new M({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Se=new M({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Ie=new M({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),Pe=new M({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),Fe=new M({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2}),Be=new Map([["ui_click",Te],["ui_hover",Se],["jump",Ie],["laser",Pe],["hit",Fe]]);function We(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),i=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}function se(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),i=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}var fe=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${Ae()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n)}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(i=>i!==n))}_emit(e,n){this.events[e]?.forEach(i=>i(n))}send(e,n){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,n)}_receive(e,n){e?this._emit(e,n):this._emit("message",n)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function Ae(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let r=new Uint8Array(16);return crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128,[...r].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function Me(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function _e(r,e,n,i,a){let o=Math.cos(a),d=Math.sin(a),p=[];if(o!==0){let l=(0-r)/o,h=e+l*d;l>0&&h>=0&&h<=i&&p.push({side:"left",t:l})}if(o!==0){let l=(n-r)/o,h=e+l*d;l>0&&h>=0&&h<=i&&p.push({side:"right",t:l})}if(d!==0){let l=(0-e)/d,h=r+l*o;l>0&&h>=0&&h<=n&&p.push({side:"top",t:l})}if(d!==0){let l=(i-e)/d,h=r+l*o;l>0&&h>=0&&h<=n&&p.push({side:"bottom",t:l})}return p.length===0?null:(p.sort((l,h)=>l.t-h.t),p[0])}function Le(r,e){let n;switch(e){case"left":case"right":n=Math.PI-r;break;case"top":case"bottom":n=2*Math.PI-r;break}return(n%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function Ye(r,e,n,i,a){let o=_e(r,e,n,i,a);return o?{...o,avoidAngle:Le(a,o.side)}:null}function Ve(){return B?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var je=Ve();var Y={};we(Y,{JSX:()=>He,KaylaContext:()=>ae,KaylaFragment:()=>pt,KaylaInternals:()=>D,KaylaRect:()=>_,createContext:()=>tt,createElement:()=>et,createGame:()=>Qe,createReassignableObject:()=>mt,createRenderer:()=>Ze,createScene:()=>Je,createUseHook:()=>gt,self:()=>ge,setLogLevel:()=>yt,useClick:()=>st,useContext:()=>dt,useCurrentGame:()=>lt,useCurrentRenderer:()=>ut,useCurrentScene:()=>ht,useCurrentTicker:()=>ct,useDisposableRef:()=>ft,useEffect:()=>be,useEntity:()=>ot,useExports:()=>he,useFiber:()=>Ge,useFiberControl:()=>xe,useGlobalClick:()=>De,useInitialization:()=>oe,useNextStack:()=>ve,usePaint:()=>ue,useRect:()=>le,useRef:()=>ye,useSelf:()=>V,useShouldRefresh:()=>rt,useState:()=>nt,useTick:()=>at,useViewportEffect:()=>it});function Qe({width:r,height:e,updateHz:n="frames"}){return new D.KaylaGame(r,e,n==="frames"?1/0:n)}function Je(r){let e=new O(r);return new D.KaylaScene(e)}function Ze(r){return new D.KaylaRenderer(r)}function et(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+se(),{type:r,props:n}}var _;(i=>{function r(a,o){return!(a.right<o.left||a.left>o.right||a.bottom<o.top||a.top>o.bottom)}i.rawCollision=r;function e(a,o,d){let p=o*Math.PI/180,l=Math.cos(p),h=Math.sin(p),f=1/0;return l>0&&(f=Math.min(f,(d.right-a.x)/l)),l<0&&(f=Math.min(f,(d.left-a.x)/l)),h>0&&(f=Math.min(f,(d.bottom-a.y)/h)),h<0&&(f=Math.min(f,(d.top-a.y)/h)),A.from(o).scale(f)}i.getCurrToBound=e;function n(a){let{left:o,right:d,top:p,bottom:l,width:h,height:f,x:g=0,y:b=0}=a;if(h===null||f===null)throw new Error("width and height are required");let x,t;if(o!=null&&d!=null){if(Math.abs(d-o-h)>1e-6)throw new Error("left, right, and width mismatch");x=o}else g!=null?x=g-h/2:o!=null?x=o:d!=null?x=d-h:x=0;if(p!=null&&l!=null){if(Math.abs(l-p-f)>1e-6)throw new Error("top, bottom, and height mismatch");t=p}else b!=null?t=b-f/2:p!=null?t=p:l!=null?t=l-f:t=0;return{left:x,right:x+h,top:t,bottom:t+f,width:h,height:f,x:x+h/2,y:t+f/2}}i.createRawRect=n})(_||={});var D;(b=>{class r extends X{#e;#t;constructor(t,s,u){super(t,s,u),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}b.KaylaGame=r;class e extends N{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",s=>{if(this.game)for(let u of this.game.scenes.values())u.handleDraw(s)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new T,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=s=>this.onPointerAll(s,"down"),this.onPointerUp=s=>this.onPointerAll(s,"up"),this.onPointerCancel=s=>this.onPointerAll(s,"cancel"),this.onPointerMove=s=>this.onPointerAll(s,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,s){this.pointerPosUpdater(t);let u=e.getClickType(t);if(u!=="invalid"){t.preventDefault();let c=this.getMousePos();this.pointerEvents.emit("action",c,u,s)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,s){let u=this.canvas.getBoundingClientRect(),c=(t-u.left)/u.width,y=(s-u.top)/u.height,v=c*this.viewportWidth*this.cameraWidth/u.width,K=y*this.viewportHeight*this.cameraHeight/u.height;return new A(v,K)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let s=u=>{t(u,new i)};return this.on("draw",s),()=>{this.off("draw",s)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}b.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return ye(ge)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let s=ye(null);return(s.current===null||s.current===void 0)&&(s.current=t()),s.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let s=this.current;s.onInits[this.current.useInitCallIndex]=t,s.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return V(()=>new b.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return V(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return V(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:s=>{t.setMaxChildren(s)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:s=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let c=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:s});return this.current.state[this.current.useStateCallIndex]=c,this.current.useStateCallIndex++,c}useShouldRefresh(t){let s=this.current;if(!s)throw new Error("useShouldRefresh must be called inside a component");s.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),s.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let u=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=u,this.current.useRefCallIndex++,u}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,s){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=s}useGlobalClick(t,s){if(!this.current)throw new Error("Hook 'useGlobalClick' must be executed in the top level scope of a component.");s??={},this.current.onGlobalClick[this.current.useGlobalClickCallIndex]={handler:t,config:s},this.current.useGlobalClickCallIndex++}useClick(t,s){if(!this.current)throw new Error("Hook 'useClick' must be executed in the top level scope of a component.");s??={};let u=this.current;De((c,y,v)=>{let K=u.entity;if(!K)return;let S=K.getRawRect(),j=_.createRawRect({x:c.x,y:c.y,width:3,height:3});_.rawCollision(S,j)&&t(c,y,v)},s)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,s,u,...c)=>{let y=t?.fc?.name||"anonymous",v=t?.key?` key=${t.key}`:"";this.logger[s](`${u} <${y}${v}>`,...c)}}}b.GlobalKayla=n;class i{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}b.KaylaEvent=i;class a{#e;#t;#n;alwaysRecall;constructor(t,s,{alwaysRecall:u=!1}={}){this.#t=t,this.#e=s??void 0,this.#n=Date.now(),this.alwaysRecall=u}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
1
+ var Ue=Object.defineProperty;var we=(r,e)=>{for(var n in e)Ue(r,n,{get:e[n],enumerable:!0})};var W={};we(W,{DeltaTweenII:()=>re,ENVIRONMENT:()=>me,GEmitterMemory:()=>fe,LeaEntityII:()=>z,LeaEventEmitter:()=>T,LeaGameII:()=>X,LeaRendererII:()=>N,LeaSceneII:()=>O,LeaSerializers:()=>Ce,LeaTickerII:()=>ne,LeaTimeout:()=>ie,LeaUtilsII:()=>K,LiaAudio:()=>U,LiaAudioSrc:()=>H,LiaOscSFX:()=>M,LiaSFXMap:()=>Be,NOTE_NAMES:()=>Re,RectLeaEntity:()=>q,Vector2:()=>A,colToRGBA:()=>Ne,defaultSFXConfig:()=>ke,editRGBA:()=>Oe,generateUUID:()=>Ae,getAvoidAngle:()=>Le,getEnvironment:()=>Ke,getNormalizedColor:()=>$e,getRayHit:()=>_e,isInitiallyMobile:()=>je,isMobile:()=>Ve,isNode:()=>B,isNote:()=>qe,isWeb:()=>C,parseFillStyle:()=>Ee,raycastAvoid:()=>Ye,scaleCoord:()=>Xe,setAnimInterval:()=>Me,sfxHit:()=>Fe,sfxJump:()=>Se,sfxLaser:()=>Ie,sfxUIClick:()=>Te,sfxUIHover:()=>Pe,shortUID:()=>We,tinyUID:()=>se});var T=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},N=class extends T{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:o}={}){if(!C)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=s??e.height,this.#n=a??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,n=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,n),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!C)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!C||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!C||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},ne=class extends T{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(C&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new ie(e,this)}createTween(e,n=()=>{}){let s=new re(e),a=(o=0)=>{if(s.finished){this.off("tick",a);return}s.update(o)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",o=>{n(o)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=C&&!isFinite(this.tickInterval)?Me(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ce;(t=>{function r(i){return i===!0?1:0}t.booleanExport=r;function e(i){return i===0?!1:i===1}t.booleanImport=e;function n(i){return`${i.x}|${i.y}`}t.vec2Export=n;function s(i){let[u,c]=i.split("|"),y=parseFloat(u),v=parseFloat(c);if(isNaN(y)||isNaN(v))throw new Error(`Invalid Vector2 string: ${i}`);return new A(y,v)}t.vec2Import=s,t.booleanMap={mapExport:r,mapImport:e};function o(i){return u=>Number(u.toFixed(i))}t.createRounder=o;function d(i=10){return{mapExport(u){return Math.round(u/i)},mapImport(u){return u*i}}}t.createLowPrecision=d;function p(i){return Math.round(i)}t.lightWeightRounder=p;function l(i=100){return{mapExport(u){return Math.round(u*i)},mapImport(u){return u/i}}}t.createPercent=l;function h(i){let u=new Map(Object.entries(i));return{mapExport:c=>u.get(c)??null,mapImport:c=>Array.from(u.entries()).find(([y,v])=>v===c)?.[0]??null}}t.createLookup=h;function f(i){let u=i*(180/Math.PI);return Math.round((u%360+360)%360)}t.radToDeg=f;function b(i){return i*(Math.PI/180)}t.degToRad=b,t.angleRadToDeg={mapExport:f,mapImport:b};function x(i=10){let u=d(i);return{mapExport(c){return u.mapExport(f(c))},mapImport(c){return u.mapImport(b(c))}}}t.createLowPrecisionRadToDeg=x})(Ce||={});var z=class r extends T{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new A(n,s),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(n){this.emit("error",n)}}handleDraw(e){if(!(B||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:o}])=>{let d=Reflect.get(this,a);return o?o(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let o=Reflect.get(this,a);if(B&&typeof o=="number"){let d=o.toString().split("."),l=(d[1]?d[1].length:0)>2?Number(o.toFixed(2)):o;return[a,l]}return[a,o]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let o=e[a];if(!o)break;let[d,{mapImport:p}]=o,l=n[a];if(p&&(l=p(l)),typeof d!="string")break;try{Reflect.set(s,d,l)}catch(h){console.error(h)}}return s}},O=class extends T{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!B&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof z))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof z))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},X=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,s=16){this.ticker=new ne(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(a)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},K={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=K.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return K.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[K.randomInt(0,r.length-1)]},createBezier(r,e,n,s){function a(p,l,h,f,b){let g=1-p;return g*g*g*l+3*g*g*p*h+3*g*p*p*f+p*p*p*b}function o(p,l,h,f,b){let g=1-p;return 3*g*g*(h-l)+6*g*p*(f-h)+3*p*p*(b-f)}function d(p){let l=p;for(let h=0;h<6;h++){let f=a(l,0,r,n,1),b=o(l,0,r,n,1);if(b===0)break;l-=(f-p)/b}return K.clamp(l,0,1)}return function(l){l=K.clamp(l,0,1);let h=d(l);return a(h,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return K.normalizeRad(-r)},degToRadFlipY(r){return K.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=K.normalizeRad(r),e=K.normalizeRad(e);let n=K.normalizeRad(e-r),s=K.normalizeRad(r-e);return n<=s?1:-1}},re=class extends T{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=K.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,o=a-this.lastValue;this.lastValue=a,this.emit("delta",o),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},q=class extends z{constructor(e,n=0,s=0,a=50,o=50){super(e,n,s),this.width=a,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},ie=class extends T{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},A=class r{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),s=Math.sin(e);return new r(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function $e(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[s,a,o,d=1]=n[1].split(",").map(p=>parseFloat(p));return{r:Math.max(0,Math.min(255,Math.floor(s))),g:Math.max(0,Math.min(255,Math.floor(a))),b:Math.max(0,Math.min(255,Math.floor(o))),a:Math.max(0,Math.min(1,Math.floor(d*255)/255))}}return Ee(r)}function Ne(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function Ee(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,s,a;if(r.length===7)n=parseInt(r.slice(1,3),16),s=parseInt(r.slice(3,5),16),a=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),s=parseInt(r[2]+r[2],16),a=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:s,b:a,a:1}}let e=r.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function Oe(r,{r:e,g:n,b:s,a}={}){let[o,d,p,l,h]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??d}, ${n??p}, ${s??l}, ${a??(h||1)})`}function Xe(r,e,n){return n+(r-n)*e}function Ke(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var me=Ke(),B=me==="node",C=me==="web",U=class r{static unlock(){C&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=C?new AudioContext:null;static masterGain=C?this.audioCtx.createGain():null;static musicGain=C?this.audioCtx.createGain():null;static sfxGain=C?this.audioCtx.createGain():null;static{C&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let o=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let d=new H(o);d.buffer=o;let p=1-.12,l=1+.12;d.playbackRate=s??p+Math.random()*(l-p);let h=this.audioCtx.createGain();h.gain.value=n,d.tempGain=h,d.connect(h),h.connect(this.sfxGain),d.onended=()=>{d.disconnect(),h.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:h})}catch(o){console.error(o)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:o=!0,skipMS:d=0}={}){if(o)for(let b of this.loops.keys())this.stopLoop(b);this.audioBufferCache.has(e)||await this.preLoad(e);let p=this.getCached(e);if(!p)return;let l=new H(p);l.buffer=p,l.loop=!0,typeof s=="number"&&(l.loopStart=s),typeof a=="number"&&(l.loopEnd=a);let h=this.audioCtx.createGain();h.gain.value=n,l.tempGain=h,l.playbackRate=1,l.onended=()=>{l.disconnect(),h.disconnect()},l.connect(h),h.connect(this.musicGain),l.start(0,d/1e3);let f=++this.loopIdCounter;return this.loops.set(f,{source:l,gain:h}),f}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:o=0,loopEnd:d=null,isMusic:p=!1,gain:l=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let f=new H(h);f.loop=a,f.loopStart=o,f.loopEnd=typeof d=="number"?d:h.duration,f.playbackRate=s;let b=this.audioCtx.createGain();return b.gain.value=n,f.connect(b),f.tempGain=b,b.connect(l||(p?this.musicGain:this.sfxGain)),f.onended=()=>{f.disconnect(),b.disconnect()},f}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}},Re=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function qe(r){return Re.includes(r)}var H=class{numberOfInputs;numberOfOutputs;constructor(e,n=U.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=C?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},ke={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},M=class r{constructor(e={}){this.ctx=U.audioCtx,this.cfg=structuredClone(ke),Object.assign(this.cfg,e)}ctx;cfg;play(e=U.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,o=n.createGain();o.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;o.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),o.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let p=o,l;a.filter.enabled&&(l=n.createBiquadFilter(),l.type=a.filter.type,l.frequency.value=a.filter.freq,l.Q.value=a.filter.Q,l.connect(o),p=l);let h;if(a.osc.enabled){if(h=n.createOscillator(),h.type=a.osc.type,h.frequency.value=a.osc.freq,h.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let i=Math.pow(2,a.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(a.osc.freq*i,s+a.pitchEnv.decay)}h.connect(p),h.start(s),h.stop(s+a.duration+d.release)}let f;if(a.noise.enabled){let i=n.sampleRate*a.duration,u=n.createBuffer(1,i,n.sampleRate),c=u.getChannelData(0);for(let y=0;y<i;y++)c[y]=(Math.random()*2-1)*a.noise.level;f=n.createBufferSource(),f.buffer=u,f.connect(p),f.start(s),f.stop(s+a.duration+d.release)}let b,g;a.lfo.enabled&&h&&(b=n.createOscillator(),b.frequency.value=a.lfo.rate,g=n.createGain(),g.gain.value=a.lfo.depth,b.connect(g),a.lfo.target==="freq"?g.connect(h.frequency):a.lfo.target==="gain"?g.connect(o.gain):a.lfo.target==="filter"&&l&&g.connect(l.frequency),b.start(s),b.stop(s+a.duration)),o.connect(e);let x=[h,f,b,g,l,o],t=s+a.duration+d.release;setTimeout(()=>{x.forEach(i=>i?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},Te=new M({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Pe=new M({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Se=new M({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),Ie=new M({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),Fe=new M({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2}),Be=new Map([["ui_click",Te],["ui_hover",Pe],["jump",Se],["laser",Ie],["hit",Fe]]);function We(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function se(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}var fe=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${Ae()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n)}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(s=>s!==n))}_emit(e,n){this.events[e]?.forEach(s=>s(n))}send(e,n){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,n)}_receive(e,n){e?this._emit(e,n):this._emit("message",n)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function Ae(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let r=new Uint8Array(16);return crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128,[...r].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function Me(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function _e(r,e,n,s,a){let o=Math.cos(a),d=Math.sin(a),p=[];if(o!==0){let l=(0-r)/o,h=e+l*d;l>0&&h>=0&&h<=s&&p.push({side:"left",t:l})}if(o!==0){let l=(n-r)/o,h=e+l*d;l>0&&h>=0&&h<=s&&p.push({side:"right",t:l})}if(d!==0){let l=(0-e)/d,h=r+l*o;l>0&&h>=0&&h<=n&&p.push({side:"top",t:l})}if(d!==0){let l=(s-e)/d,h=r+l*o;l>0&&h>=0&&h<=n&&p.push({side:"bottom",t:l})}return p.length===0?null:(p.sort((l,h)=>l.t-h.t),p[0])}function Le(r,e){let n;switch(e){case"left":case"right":n=Math.PI-r;break;case"top":case"bottom":n=2*Math.PI-r;break}return(n%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function Ye(r,e,n,s,a){let o=_e(r,e,n,s,a);return o?{...o,avoidAngle:Le(a,o.side)}:null}function Ve(){return B?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var je=Ve();var Y={};we(Y,{JSX:()=>He,KaylaContext:()=>ae,KaylaFragment:()=>mt,KaylaInternals:()=>G,KaylaRect:()=>_,createContext:()=>tt,createElement:()=>et,createGame:()=>Qe,createReassignableObject:()=>bt,createRenderer:()=>Ze,createScene:()=>Je,createUseHook:()=>xt,self:()=>be,setLogLevel:()=>gt,useClick:()=>at,useContext:()=>ft,useCurrentGame:()=>ht,useCurrentRenderer:()=>ct,useCurrentScene:()=>dt,useCurrentTicker:()=>pt,useDisposableRef:()=>yt,useEffect:()=>ge,useEntity:()=>ut,useExports:()=>he,useFiber:()=>De,useFiberControl:()=>xe,useGlobalClick:()=>Ge,useGlobalPointer:()=>st,useInitialization:()=>oe,useNextStack:()=>ve,usePaint:()=>ue,usePointer:()=>ot,useRect:()=>le,useRef:()=>ye,useSelf:()=>V,useShouldRefresh:()=>rt,useState:()=>nt,useTick:()=>lt,useViewportEffect:()=>it});function Qe({width:r,height:e,updateHz:n="frames"}){return new G.KaylaGame(r,e,n==="frames"?1/0:n)}function Je(r){let e=new O(r);return new G.KaylaScene(e)}function Ze(r){return new G.KaylaRenderer(r)}function et(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+se(),{type:r,props:n}}var _;(s=>{function r(a,o){return!(a.right<o.left||a.left>o.right||a.bottom<o.top||a.top>o.bottom)}s.rawCollision=r;function e(a,o,d){let p=o*Math.PI/180,l=Math.cos(p),h=Math.sin(p),f=1/0;return l>0&&(f=Math.min(f,(d.right-a.x)/l)),l<0&&(f=Math.min(f,(d.left-a.x)/l)),h>0&&(f=Math.min(f,(d.bottom-a.y)/h)),h<0&&(f=Math.min(f,(d.top-a.y)/h)),A.from(o).scale(f)}s.getCurrToBound=e;function n(a){let{left:o,right:d,top:p,bottom:l,width:h,height:f,x:b=0,y:g=0}=a;if(h===null||f===null)throw new Error("width and height are required");let x,t;if(o!=null&&d!=null){if(Math.abs(d-o-h)>1e-6)throw new Error("left, right, and width mismatch");x=o}else b!=null?x=b-h/2:o!=null?x=o:d!=null?x=d-h:x=0;if(p!=null&&l!=null){if(Math.abs(l-p-f)>1e-6)throw new Error("top, bottom, and height mismatch");t=p}else g!=null?t=g-f/2:p!=null?t=p:l!=null?t=l-f:t=0;return{left:x,right:x+h,top:t,bottom:t+f,width:h,height:f,x:x+h/2,y:t+f/2}}s.createRawRect=n})(_||={});var G;(g=>{class r extends X{#e;#t;constructor(t,i,u){super(t,i,u),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}g.KaylaGame=r;class e extends N{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let u of this.game.scenes.values())u.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new T,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let u=e.getClickType(t);if(u!=="invalid"||i==="move"||i==="cancel"){t.preventDefault();let c=this.getMousePos();this.pointerEvents.emit("action",c,u,i)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let u=this.canvas.getBoundingClientRect(),c=(t-u.left)/u.width,y=(i-u.top)/u.height,v=c*this.viewportWidth*this.cameraWidth/u.width,R=y*this.viewportHeight*this.cameraHeight/u.height;return new A(v,R)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=u=>{t(u,new s)};return this.on("draw",i),()=>{this.off("draw",i)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}g.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return ye(be)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=ye(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return V(()=>new g.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return V(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return V(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:i=>{t.setMaxChildren(i)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:i=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let c=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=c,this.current.useStateCallIndex++,c}useShouldRefresh(t){let i=this.current;if(!i)throw new Error("useShouldRefresh must be called inside a component");i.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),i.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let u=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=u,this.current.useRefCallIndex++,u}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalPointer(t,i){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}usePointer(t,i){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");i??={};let u=this.current;Ge((c,y,v)=>{let R=u.entity;if(!R)return;let P=R.getRawRect(),j=_.createRawRect({x:c.x,y:c.y,width:3,height:3});_.rawCollision(P,j)&&t(c,y,v)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,u,...c)=>{let y=t?.fc?.name||"anonymous",v=t?.key?` key=${t.key}`:"";this.logger[i](`${u} <${y}${v}>`,...c)}}}g.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}g.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,i,{alwaysRecall:u=!1}={}){this.#t=t,this.#e=i??void 0,this.#n=Date.now(),this.alwaysRecall=u}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
2
2
  You probably wrote: const [value, setValue] = useState(...)
3
3
 
4
4
  \u2192 In Kayla write: const value = useState(...);
5
- \u2192 Then: value.get() / value.set(v) / value.add(n)`)}refreshBased(){return[this.set.bind(this),this.get()]}add(t,{recall:s}={}){this.set(this.get()+t,{recall:s})}multiply(t,{recall:s}={}){this.set(this.get()*t,{recall:s})}set(t,{recall:s=!1}={}){let u=this.#e;if(t===u)return;this.#e=t;let y=Date.now()-this.#n;s&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(s||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}b.KaylaInternalState=a;class o{#e;constructor(t){this.#e=t??void 0}#t;setSetter(t){this.#t=t}get current(){return this.#e}set current(t){this.#e=t,this.#t&&this.#t(this.#e)}}b.KaylaInternalRef=o;function d(x){return new o(x)}b.createReassignableRef=d;class p{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,s,u){if(!u)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=s,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=u.type,this.callProps=u.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalClick=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+se(),this.onViewportEffect=[]}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,s,u){try{for(let{handler:c,config:y}of this.onGlobalClick)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==u||y.type!=="any"&&y.type!==s)&&c(t,s,u)}catch(c){this.global.logger.error(c)}}resizeHook({width:t,height:s}){try{for(let u of this.onViewportEffect)u(this.getAttachedRenderer(),t,s)}catch(u){this.global.logger.error(u)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalClick;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let s=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${s} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let u=this.lastChildren.slice(0,this.maxSafeChildren),c=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=u;for(let y of c)y.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],s=this.detectedParent;for(;s;)t.push(s),s=s?.detectedParent;return t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(s=>s.instance===t)?.value}getEntityChain(){return this.getFiberChain().map(t=>t.entity)}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let t=0;t<this.watchedDeps.length;t++){let s=this.watchedDeps[t],u=this.lastDepStamps[t]??0;if(s.lastChanged>u)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let s;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let u=[];try{let c=this.fc(this.callProps)??[];if(c&&!Array.isArray(c)&&(c=[c]),!Array.isArray(c))throw new Error("Non array or non undefined children received.");for(let y of c)if(y.type===this.fc)throw new Error("Circular Component.");u=c}catch(c){s=c}if(this.global.restore(),this.updateChildren(u,!0),s)throw s}updateChildren(t,s){try{let u=[...t,...this.dynamicChildren],c=[],y=[];for(let v of u){let K=v.props?.key,S;K!=null&&(S=this.lastChildren.find(j=>j.key===K)),S||(S=new p(this.global,this.scene,v)),S.detectedParent=this,y.push(S),c.push(S)}for(let v of this.lastChildren)c.includes(v)||v.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let v of this.lastChildren)try{v.refresh()}catch(K){console.error(K)}}catch(u){console.error(u)}}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=this.onEffectDeps.some((s,u)=>{let c=this.lastStateDeps.at(u);if(c){let y=s.lastChanged,v=c.stamp;return y>v}})),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let s=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(c=>({stamp:c.lastChanged,stateRef:c}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new l(this,this.key);for(let c of this.refs)c.current===ge&&(c.current=this.entity);if(this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),s){this.onUnInits=[];for(let c of this.onInits){this.bindEvents();try{let y=c();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let c of this.onUnEffect??[])c()}catch(c){console.error(c)}let u=this.onEffect.map(c=>c()).filter(c=>c!==void 0);this.onUnEffect=u}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}b.KaylaFiber=p;class l extends q{#e;flags;getRawRect(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,s){super(s,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,s){return this.flags.set(t,s)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let s=new i;if(this.#e&&this.#e.onTick)for(let u of this.#e.onTick)u(t,s);s.isPrevented()}draw(t){let s=new i;if(this.#e&&this.#e.onPaint)for(let u of this.#e.onPaint)u(t,s);s.isPrevented()||super.draw(t)}getRect(){return new h(this.getFiber())}}b.KaylaRectEntity=l;class h{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}get entity(){return this.#e.entity??null}#t(){if(!this.#e)throw new Error("No fibers found.");if(!this.entity)throw new Error("The entity does NOT exist yet.")}isCollidingWith(t){return this.#t(),this.entity.isCollidingWith(t.entity)}get setFlag(){return this.#t(),this.entity.setFlag.bind(this.entity)}get getFlag(){return this.#t(),this.entity.getFlag.bind(this.entity)}get removeFlag(){return this.#t(),this.entity.removeFlag.bind(this.entity)}isHovered(){let t=this.getRaw(),s=this.#e.getAttachedRenderer().getMousePos(),u=_.createRawRect({x:s.x,y:s.y,width:3,height:3});return _.rawCollision(t,u)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}b.KaylaInternalRect=h;class f{constructor(t){this.#t=t,this.#e=null,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#t}getGame(){return this.#e}drawHandler(t){return this.#t.handleDraw(t)}attachTo(t){t.addScene(this.#t),this.#e=t}async spawn(t){let s=this.createFiber(t);await this.#e.delay(0),s.refresh()}createFiber(t){return new p(b.singleGlobalInstance,this,t)}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}b.KaylaScene=f,b.singleGlobalInstance=new b.GlobalKayla})(D||={});var ae=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let i=Ge();return oe(()=>{i.contextInfo={instance:this,value:e}}),he(this.Provider,()=>({value:e})),n}Provider;Consumer};function tt(r){return new ae(r)}var m=D.singleGlobalInstance,nt=m.useState.bind(m),ye=m.useRef.bind(m),rt=m.useShouldRefresh.bind(m),be=m.useEffect.bind(m),it=m.useViewportEffect.bind(m),De=m.useGlobalClick.bind(m),st=m.useClick.bind(m),oe=m.useInitialization.bind(m),le=m.useRect.bind(m),at=m.useTick.bind(m),ue=m.usePaint.bind(m),he=m.useExports.bind(m),V=m.useSelf.bind(m),xe=m.useFiberControl.bind(m),Ge=m.useFiber.bind(m),ot=m.useEntity.bind(m),lt=m.useCurrentGame.bind(m),ut=m.useCurrentRenderer.bind(m),ht=m.useCurrentScene.bind(m),ct=m.useCurrentTicker.bind(m),dt=m.useContext.bind(m),ge=Symbol("self_ref");var ve=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},pt=({children:r})=>Array.isArray(r)?[...r]:r;function ft(r){return D.createReassignableRef(r)}function mt(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(i,a,o){return a==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,a,o)},set(i,a,o,d){return Reflect.set(e.current,a,o,d)},has(i,a){return Reflect.has(e.current,a)},ownKeys(i){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(i,a){return Reflect.getOwnPropertyDescriptor(e.current,a)},deleteProperty(i,a){return Reflect.deleteProperty(e.current,a)}})}function yt(r){m.logLevel=r}function gt(r){let e=r.name||"anonymous-custom-hook";return function(i){let a=m.current;if(!a)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let o=i??{};return r.memoize!==!1?V(()=>(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,o))):(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,o))}}var He;(e=>e.id="kayla")(He||={});Reflect.set(globalThis,"Kayla",Y);var bt;(n=>(n.Flex=({align:i="stretch",children:a,direction:o="row",gap:d=0,justify:p="start",wrap:l="nowrap",getHeight:h,getWidth:f,getCenterX:g,getCenterY:b,color:x})=>{let t=xe(),s=le(),u=V(()=>({recalc(){let c=Number(d)||0,y=g(),v=b(),K=f(),S=h();s.x=y,s.y=v,s.width=K,s.height=S;let ze=t.getChildrenEntities().filter(Boolean).map(w=>w.getRect()).filter(w=>w.getFlag("flex-ignored")!==!0),I=o==="row",F=I?s.width:s.height,xt=I?s.height:s.width,ce=0,$=0,de=[],Q=[];ze.forEach(w=>{let J=I?w.width:w.height;ce+J>F&&l==="wrap"?(de.push({height:$,items:Q}),Q=[w],ce=J,$=I?w.height:w.width):(Q.push(w),ce+=J+c,$=Math.max($,I?w.height:w.width))}),de.push({height:$,items:Q});let pe=0;de.forEach((w,J)=>{let P=w.items,L=P.reduce((E,Z)=>E+(I?Z.width:Z.height),0)+c*(P.length-1),R=0;p==="center"&&(R=(F-L)/2),p==="end"&&(R=F-L),p==="space-between"&&(R=0),p==="space-around"&&(R=(F-L)/(P.length*2)),p==="space-evenly"&&(R=(F-L)/(P.length+1)),P.forEach((E,Z)=>{E.z=s.z+1;let G=I?E.width:E.height,ee=I?E.height:E.width,te=0;i==="center"&&(te=(w.height-ee)/2),i==="end"&&(te=w.height-ee),i==="stretch"&&(I?E.height=w.height:E.width=w.height),I?(E.x=R+G/2,E.y=pe+te+ee/2):(E.x=pe+te+ee/2,E.y=R+G/2),p==="space-between"&&Z<P.length-1?R+=G+c+(F-L)/(P.length-1):p==="space-around"?R+=G+c+(F-L)/P.length:p==="space-evenly"?R+=G+c+(F-L)/(P.length+1):R+=G+c}),pe+=w.height+c})}}));return ue((c,y)=>{y.preventDefault(),c.fillStyle=x,c.fillRect(s.left,s.top,s.width,s.height)}),be(()=>{ve(()=>{u.recalc()})}),he(n.Flex,()=>({controls:u})),a},n.GenericBox=({color:i,width:a=20,height:o=20,x:d=0,y:p=0})=>{let l=le();oe(()=>{l.width=a,l.height=o,l.x=d,l.y=p}),ue((h,f)=>{f.preventDefault(),h.fillStyle=i,h.fillRect(l.left,l.top,l.width,l.height)})}))(bt||={});var kt={LEA:W,Kayla:Y};export{Y as Kayla,W as LEA,kt as default};
5
+ \u2192 Then: value.get() / value.set(v) / value.add(n)`)}refreshBased(){return[this.set.bind(this),this.get()]}add(t,{recall:i}={}){this.set(this.get()+t,{recall:i})}multiply(t,{recall:i}={}){this.set(this.get()*t,{recall:i})}set(t,{recall:i=!1}={}){let u=this.#e;if(t===u)return;this.#e=t;let y=Date.now()-this.#n;i&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(i||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}g.KaylaInternalState=a;class o{#e;constructor(t){this.#e=t??void 0}#t;setSetter(t){this.#t=t}get current(){return this.#e}set current(t){this.#e=t,this.#t&&this.#t(this.#e)}}g.KaylaInternalRef=o;function d(x){return new o(x)}g.createReassignableRef=d;class p{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,i,u){if(!u)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=i,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=u.type,this.callProps=u.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalPointer=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+se(),this.onViewportEffect=[]}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,i,u){try{for(let{handler:c,config:y}of this.onGlobalPointer)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==u||y.type!=="any"&&y.type!==i)&&c(t,i,u)}catch(c){this.global.logger.error(c)}}resizeHook({width:t,height:i}){try{for(let u of this.onViewportEffect)u(this.getAttachedRenderer(),t,i)}catch(u){this.global.logger.error(u)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalPointer;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let i=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${i} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let u=this.lastChildren.slice(0,this.maxSafeChildren),c=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=u;for(let y of c)y.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],i=this.detectedParent;for(;i;)t.push(i),i=i?.detectedParent;return t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(i=>i.instance===t)?.value}getEntityChain(){return this.getFiberChain().map(t=>t.entity)}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let t=0;t<this.watchedDeps.length;t++){let i=this.watchedDeps[t],u=this.lastDepStamps[t]??0;if(i.lastChanged>u)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let i;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let u=[];try{let c=this.fc(this.callProps)??[];if(c&&!Array.isArray(c)&&(c=[c]),!Array.isArray(c))throw new Error("Non array or non undefined children received.");for(let y of c)if(y.type===this.fc)throw new Error("Circular Component.");u=c}catch(c){i=c}if(this.global.restore(),this.updateChildren(u,!0),i)throw i}updateChildren(t,i){try{let u=[...t,...this.dynamicChildren],c=[],y=[];for(let v of u){let R=v.props?.key,P;R!=null&&(P=this.lastChildren.find(j=>j.key===R)),P||(P=new p(this.global,this.scene,v)),P.detectedParent=this,y.push(P),c.push(P)}for(let v of this.lastChildren)c.includes(v)||v.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let v of this.lastChildren)try{v.refresh()}catch(R){console.error(R)}}catch(u){console.error(u)}}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=this.onEffectDeps.some((i,u)=>{let c=this.lastStateDeps.at(u);if(c){let y=i.lastChanged,v=c.stamp;return y>v}})),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let i=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(c=>({stamp:c.lastChanged,stateRef:c}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new l(this,this.key);for(let c of this.refs)c.current===be&&(c.current=this.entity);if(this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),i){this.onUnInits=[];for(let c of this.onInits){this.bindEvents();try{let y=c();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let c of this.onUnEffect??[])c()}catch(c){console.error(c)}let u=this.onEffect.map(c=>c()).filter(c=>c!==void 0);this.onUnEffect=u}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}g.KaylaFiber=p;class l extends q{#e;flags;getRawRect(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,i){super(i,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,i){return this.flags.set(t,i)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let i=new s;if(this.#e&&this.#e.onTick)for(let u of this.#e.onTick)u(t,i);i.isPrevented()}draw(t){let i=new s;if(this.#e&&this.#e.onPaint)for(let u of this.#e.onPaint)u(t,i);i.isPrevented()||super.draw(t)}getRect(){return new h(this.getFiber())}}g.KaylaRectEntity=l;class h{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}get entity(){return this.#e.entity??null}#t(){if(!this.#e)throw new Error("No fibers found.");if(!this.entity)throw new Error("The entity does NOT exist yet.")}isCollidingWith(t){return this.#t(),this.entity.isCollidingWith(t.entity)}get setFlag(){return this.#t(),this.entity.setFlag.bind(this.entity)}get getFlag(){return this.#t(),this.entity.getFlag.bind(this.entity)}get removeFlag(){return this.#t(),this.entity.removeFlag.bind(this.entity)}isHovered(){let t=this.getRaw(),i=this.#e.getAttachedRenderer().getMousePos(),u=_.createRawRect({x:i.x,y:i.y,width:3,height:3});return _.rawCollision(t,u)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}g.KaylaInternalRect=h;class f{constructor(t){this.#t=t,this.#e=null,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#t}getGame(){return this.#e}drawHandler(t){return this.#t.handleDraw(t)}attachTo(t){t.addScene(this.#t),this.#e=t}async spawn(t){let i=this.createFiber(t);await this.#e.delay(0),i.refresh()}createFiber(t){return new p(g.singleGlobalInstance,this,t)}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}g.KaylaScene=f,g.singleGlobalInstance=new g.GlobalKayla})(G||={});var ae=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let s=De();return oe(()=>{s.contextInfo={instance:this,value:e}}),he(this.Provider,()=>({value:e})),n}Provider;Consumer};function tt(r){return new ae(r)}var m=G.singleGlobalInstance,nt=m.useState.bind(m),ye=m.useRef.bind(m),rt=m.useShouldRefresh.bind(m),ge=m.useEffect.bind(m),it=m.useViewportEffect.bind(m),Ge=m.useGlobalPointer.bind(m),st=m.useGlobalPointer.bind(m),at=m.usePointer.bind(m),ot=m.usePointer.bind(m),oe=m.useInitialization.bind(m),le=m.useRect.bind(m),lt=m.useTick.bind(m),ue=m.usePaint.bind(m),he=m.useExports.bind(m),V=m.useSelf.bind(m),xe=m.useFiberControl.bind(m),De=m.useFiber.bind(m),ut=m.useEntity.bind(m),ht=m.useCurrentGame.bind(m),ct=m.useCurrentRenderer.bind(m),dt=m.useCurrentScene.bind(m),pt=m.useCurrentTicker.bind(m),ft=m.useContext.bind(m),be=Symbol("self_ref");var ve=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},mt=({children:r})=>Array.isArray(r)?[...r]:r;function yt(r){return G.createReassignableRef(r)}function bt(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(s,a,o){return a==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,a,o)},set(s,a,o,d){return Reflect.set(e.current,a,o,d)},has(s,a){return Reflect.has(e.current,a)},ownKeys(s){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(s,a){return Reflect.getOwnPropertyDescriptor(e.current,a)},deleteProperty(s,a){return Reflect.deleteProperty(e.current,a)}})}function gt(r){m.logLevel=r}function xt(r){let e=r.name||"anonymous-custom-hook";return function(s){let a=m.current;if(!a)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let o=s??{};return r.memoize!==!1?V(()=>(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,o))):(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,o))}}var He;(e=>e.id="kayla")(He||={});Reflect.set(globalThis,"Kayla",Y);var vt;(n=>(n.Flex=({align:s="stretch",children:a,direction:o="row",gap:d=0,justify:p="start",wrap:l="nowrap",getHeight:h,getWidth:f,getCenterX:b,getCenterY:g,color:x})=>{let t=xe(),i=le(),u=V(()=>({recalc(){let c=Number(d)||0,y=b(),v=g(),R=f(),P=h();i.x=y,i.y=v,i.width=R,i.height=P;let ze=t.getChildrenEntities().filter(Boolean).map(w=>w.getRect()).filter(w=>w.getFlag("flex-ignored")!==!0),S=o==="row",F=S?i.width:i.height,wt=S?i.height:i.width,ce=0,$=0,de=[],Q=[];ze.forEach(w=>{let J=S?w.width:w.height;ce+J>F&&l==="wrap"?(de.push({height:$,items:Q}),Q=[w],ce=J,$=S?w.height:w.width):(Q.push(w),ce+=J+c,$=Math.max($,S?w.height:w.width))}),de.push({height:$,items:Q});let pe=0;de.forEach((w,J)=>{let I=w.items,L=I.reduce((E,Z)=>E+(S?Z.width:Z.height),0)+c*(I.length-1),k=0;p==="center"&&(k=(F-L)/2),p==="end"&&(k=F-L),p==="space-between"&&(k=0),p==="space-around"&&(k=(F-L)/(I.length*2)),p==="space-evenly"&&(k=(F-L)/(I.length+1)),I.forEach((E,Z)=>{E.z=i.z+1;let D=S?E.width:E.height,ee=S?E.height:E.width,te=0;s==="center"&&(te=(w.height-ee)/2),s==="end"&&(te=w.height-ee),s==="stretch"&&(S?E.height=w.height:E.width=w.height),S?(E.x=k+D/2,E.y=pe+te+ee/2):(E.x=pe+te+ee/2,E.y=k+D/2),p==="space-between"&&Z<I.length-1?k+=D+c+(F-L)/(I.length-1):p==="space-around"?k+=D+c+(F-L)/I.length:p==="space-evenly"?k+=D+c+(F-L)/(I.length+1):k+=D+c}),pe+=w.height+c})}}));return ue((c,y)=>{y.preventDefault(),c.fillStyle=x,c.fillRect(i.left,i.top,i.width,i.height)}),ge(()=>{ve(()=>{u.recalc()})}),he(n.Flex,()=>({controls:u})),a},n.GenericBox=({color:s,width:a=20,height:o=20,x:d=0,y:p=0})=>{let l=le();oe(()=>{l.width=a,l.height=o,l.x=d,l.y=p}),ue((h,f)=>{f.preventDefault(),h.fillStyle=s,h.fillRect(l.left,l.top,l.width,l.height)})}))(vt||={});var kt={LEA:W,Kayla:Y};export{Y as Kayla,W as LEA,kt as default};