@al8b/runtime 0.1.0
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/README.md +87 -0
- package/dist/assets/constructors.d.mts +6 -0
- package/dist/assets/constructors.d.ts +6 -0
- package/dist/assets/constructors.js +40 -0
- package/dist/assets/constructors.js.map +1 -0
- package/dist/assets/constructors.mjs +12 -0
- package/dist/assets/constructors.mjs.map +1 -0
- package/dist/assets/index.d.mts +11 -0
- package/dist/assets/index.d.ts +11 -0
- package/dist/assets/index.js +276 -0
- package/dist/assets/index.js.map +1 -0
- package/dist/assets/index.mjs +247 -0
- package/dist/assets/index.mjs.map +1 -0
- package/dist/assets/loader.d.mts +83 -0
- package/dist/assets/loader.d.ts +83 -0
- package/dist/assets/loader.js +260 -0
- package/dist/assets/loader.js.map +1 -0
- package/dist/assets/loader.mjs +237 -0
- package/dist/assets/loader.mjs.map +1 -0
- package/dist/browser/index.js +16599 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/index.min.js +171 -0
- package/dist/constants.d.mts +16 -0
- package/dist/constants.d.ts +16 -0
- package/dist/constants.js +49 -0
- package/dist/constants.js.map +1 -0
- package/dist/constants.mjs +18 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/core/api-factory.d.mts +63 -0
- package/dist/core/api-factory.d.ts +63 -0
- package/dist/core/api-factory.js +239 -0
- package/dist/core/api-factory.js.map +1 -0
- package/dist/core/api-factory.mjs +214 -0
- package/dist/core/api-factory.mjs.map +1 -0
- package/dist/core/assets-registry.d.mts +14 -0
- package/dist/core/assets-registry.d.ts +14 -0
- package/dist/core/assets-registry.js +64 -0
- package/dist/core/assets-registry.js.map +1 -0
- package/dist/core/assets-registry.mjs +41 -0
- package/dist/core/assets-registry.mjs.map +1 -0
- package/dist/core/controller.d.mts +109 -0
- package/dist/core/controller.d.ts +109 -0
- package/dist/core/controller.js +1782 -0
- package/dist/core/controller.js.map +1 -0
- package/dist/core/controller.mjs +1758 -0
- package/dist/core/controller.mjs.map +1 -0
- package/dist/core/debug-logger.d.mts +35 -0
- package/dist/core/debug-logger.d.ts +35 -0
- package/dist/core/debug-logger.js +177 -0
- package/dist/core/debug-logger.js.map +1 -0
- package/dist/core/debug-logger.mjs +154 -0
- package/dist/core/debug-logger.mjs.map +1 -0
- package/dist/core/error-handler.d.mts +25 -0
- package/dist/core/error-handler.d.ts +25 -0
- package/dist/core/error-handler.js +106 -0
- package/dist/core/error-handler.js.map +1 -0
- package/dist/core/error-handler.mjs +81 -0
- package/dist/core/error-handler.mjs.map +1 -0
- package/dist/core/index.d.mts +14 -0
- package/dist/core/index.d.ts +14 -0
- package/dist/core/index.js +1782 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/index.mjs +1757 -0
- package/dist/core/index.mjs.map +1 -0
- package/dist/hot-reload/index.d.mts +7 -0
- package/dist/hot-reload/index.d.ts +7 -0
- package/dist/hot-reload/index.js +103 -0
- package/dist/hot-reload/index.js.map +1 -0
- package/dist/hot-reload/index.mjs +78 -0
- package/dist/hot-reload/index.mjs.map +1 -0
- package/dist/hot-reload/updater.d.mts +33 -0
- package/dist/hot-reload/updater.d.ts +33 -0
- package/dist/hot-reload/updater.js +101 -0
- package/dist/hot-reload/updater.js.map +1 -0
- package/dist/hot-reload/updater.mjs +78 -0
- package/dist/hot-reload/updater.mjs.map +1 -0
- package/dist/index.d.mts +24 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +1859 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1817 -0
- package/dist/index.mjs.map +1 -0
- package/dist/input/index.d.mts +2 -0
- package/dist/input/index.d.ts +2 -0
- package/dist/input/index.js +79 -0
- package/dist/input/index.js.map +1 -0
- package/dist/input/index.mjs +54 -0
- package/dist/input/index.mjs.map +1 -0
- package/dist/input/manager.d.mts +37 -0
- package/dist/input/manager.d.ts +37 -0
- package/dist/input/manager.js +77 -0
- package/dist/input/manager.js.map +1 -0
- package/dist/input/manager.mjs +54 -0
- package/dist/input/manager.mjs.map +1 -0
- package/dist/loop/game-loop.d.mts +63 -0
- package/dist/loop/game-loop.d.ts +63 -0
- package/dist/loop/game-loop.js +156 -0
- package/dist/loop/game-loop.js.map +1 -0
- package/dist/loop/game-loop.mjs +131 -0
- package/dist/loop/game-loop.mjs.map +1 -0
- package/dist/loop/index.d.mts +1 -0
- package/dist/loop/index.d.ts +1 -0
- package/dist/loop/index.js +156 -0
- package/dist/loop/index.js.map +1 -0
- package/dist/loop/index.mjs +131 -0
- package/dist/loop/index.mjs.map +1 -0
- package/dist/storage/index.d.mts +1 -0
- package/dist/storage/index.d.ts +1 -0
- package/dist/storage/index.js +31 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/index.mjs +6 -0
- package/dist/storage/index.mjs.map +1 -0
- package/dist/system/api.d.mts +28 -0
- package/dist/system/api.d.ts +28 -0
- package/dist/system/api.js +126 -0
- package/dist/system/api.js.map +1 -0
- package/dist/system/api.mjs +101 -0
- package/dist/system/api.mjs.map +1 -0
- package/dist/system/index.d.mts +2 -0
- package/dist/system/index.d.ts +2 -0
- package/dist/system/index.js +126 -0
- package/dist/system/index.js.map +1 -0
- package/dist/system/index.mjs +101 -0
- package/dist/system/index.mjs.map +1 -0
- package/dist/types/assets.d.mts +43 -0
- package/dist/types/assets.d.ts +43 -0
- package/dist/types/assets.js +19 -0
- package/dist/types/assets.js.map +1 -0
- package/dist/types/assets.mjs +1 -0
- package/dist/types/assets.mjs.map +1 -0
- package/dist/types/bridge.d.mts +66 -0
- package/dist/types/bridge.d.ts +66 -0
- package/dist/types/bridge.js +19 -0
- package/dist/types/bridge.js.map +1 -0
- package/dist/types/bridge.mjs +1 -0
- package/dist/types/bridge.mjs.map +1 -0
- package/dist/types/index.d.mts +6 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/index.js +19 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/index.mjs +1 -0
- package/dist/types/index.mjs.map +1 -0
- package/dist/types/runtime.d.mts +71 -0
- package/dist/types/runtime.d.ts +71 -0
- package/dist/types/runtime.js +19 -0
- package/dist/types/runtime.js.map +1 -0
- package/dist/types/runtime.mjs +1 -0
- package/dist/types/runtime.mjs.map +1 -0
- package/dist/types/vm.d.mts +1 -0
- package/dist/types/vm.d.ts +1 -0
- package/dist/types/vm.js +19 -0
- package/dist/types/vm.js.map +1 -0
- package/dist/types/vm.mjs +1 -0
- package/dist/types/vm.mjs.map +1 -0
- package/dist/utils/deep-clone.d.mts +14 -0
- package/dist/utils/deep-clone.d.ts +14 -0
- package/dist/utils/deep-clone.js +42 -0
- package/dist/utils/deep-clone.js.map +1 -0
- package/dist/utils/deep-clone.mjs +19 -0
- package/dist/utils/deep-clone.mjs.map +1 -0
- package/dist/utils/index.d.mts +3 -0
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.js +156 -0
- package/dist/utils/index.js.map +1 -0
- package/dist/utils/index.mjs +129 -0
- package/dist/utils/index.mjs.map +1 -0
- package/dist/utils/object-pool.d.mts +66 -0
- package/dist/utils/object-pool.d.ts +66 -0
- package/dist/utils/object-pool.js +113 -0
- package/dist/utils/object-pool.js.map +1 -0
- package/dist/utils/object-pool.mjs +90 -0
- package/dist/utils/object-pool.mjs.map +1 -0
- package/dist/utils/shallow-equal.d.mts +15 -0
- package/dist/utils/shallow-equal.d.ts +15 -0
- package/dist/utils/shallow-equal.js +53 -0
- package/dist/utils/shallow-equal.js.map +1 -0
- package/dist/utils/shallow-equal.mjs +30 -0
- package/dist/utils/shallow-equal.mjs.map +1 -0
- package/dist/vm/index.d.mts +1 -0
- package/dist/vm/index.d.ts +1 -0
- package/dist/vm/index.js +37 -0
- package/dist/vm/index.js.map +1 -0
- package/dist/vm/index.mjs +9 -0
- package/dist/vm/index.mjs.map +1 -0
- package/package.json +52 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"use strict";var L8BRuntime=(()=>{var St=Object.defineProperty;var Jr=Object.getOwnPropertyDescriptor;var Qr=Object.getOwnPropertyNames;var Xr=Object.prototype.hasOwnProperty;var l=(t,e)=>St(t,"name",{value:e,configurable:!0});var Zr=(t,e)=>{for(var s in e)St(t,s,{get:e[s],enumerable:!0})},en=(t,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qr(e))!Xr.call(t,r)&&r!==s&&St(t,r,{get:()=>e[r],enumerable:!(i=Jr(e,r))||i.enumerable});return t};var tn=t=>en(St({},"__esModule",{value:!0}),t);var Fa={};Zr(Fa,{AssetLoader:()=>it,GameLoop:()=>ot,Image:()=>Se,InputManager:()=>at,L8BVM:()=>Ht,ObjectPool:()=>At,Sound:()=>Me,SourceUpdater:()=>nt,Sprite:()=>st,StorageService:()=>Gt,System:()=>ht,TileMap:()=>Xe,createMetaFunctions:()=>si,createRuntime:()=>Kr,createVMContext:()=>Wt,deepClone:()=>Na,setupArrayExtensions:()=>qt,shallowEqual:()=>Da});var sn=Object.defineProperty,w=l((t,e)=>sn(t,"name",{value:e,configurable:!0}),"__name"),te=(function(t){return t.E1001="E1001",t.E1002="E1002",t.E1003="E1003",t.E1004="E1004",t.E1005="E1005",t.E1006="E1006",t.E1007="E1007",t.E1008="E1008",t.E1009="E1009",t})({}),be=(function(t){return t.E2001="E2001",t.E2002="E2002",t.E2003="E2003",t.E2004="E2004",t.E2005="E2005",t})({}),Ke=(function(t){return t.E3001="E3001",t.E3002="E3002",t.E3003="E3003",t})({}),fe=(function(t){return t.E5001="E5001",t.E5002="E5002",t.E5003="E5003",t.E5004="E5004",t.E5005="E5005",t.E5006="E5006",t.E5007="E5007",t})({}),Je=(function(t){return t.E6001="E6001",t.E6002="E6002",t.E6003="E6003",t})({}),_=(function(t){return t.E7001="E7001",t.E7002="E7002",t.E7003="E7003",t.E7004="E7004",t.E7005="E7005",t.E7006="E7006",t.E7007="E7007",t.E7011="E7011",t.E7012="E7012",t.E7013="E7013",t.E7014="E7014",t.E7015="E7015",t.E7016="E7016",t.E7021="E7021",t.E7022="E7022",t.E7023="E7023",t.E7024="E7024",t.E7031="E7031",t.E7032="E7032",t.E7033="E7033",t.E7034="E7034",t.E7041="E7041",t.E7042="E7042",t.E7043="E7043",t.E7044="E7044",t.E7051="E7051",t.E7052="E7052",t.E7061="E7061",t.E7062="E7062",t.E7063="E7063",t.E7071="E7071",t.E7072="E7072",t.E7073="E7073",t.E7074="E7074",t.E7075="E7075",t.E7081="E7081",t.E7082="E7082",t.E7083="E7083",t.E7084="E7084",t.E7091="E7091",t.E7092="E7092",t.E7093="E7093",t.E7100="E7100",t})({}),pe=(function(t){return t.W1001="W1001",t.W1002="W1002",t.W2001="W2001",t.W5001="W5001",t.W5002="W5002",t.W5003="W5003",t.W5004="W5004",t})({}),P=(function(t){return t.Error="error",t.Warning="warning",t.Info="info",t})({}),x=(function(t){return t.Syntax="syntax",t.Runtime="runtime",t.Compilation="compilation",t.Type="type",t.Scene="scene",t.CLI="cli",t.API="api",t})({}),rn={[_.E7041]:{code:_.E7041,severity:P.Error,category:x.API,message:w(t=>`Asset not found: '${t.assetName}'`,"message"),description:"The requested asset does not exist",suggestions:["Check if the asset name is correct","Verify the asset was loaded","Check asset loading order"]},[_.E7042]:{code:_.E7042,severity:P.Error,category:x.API,message:w(t=>`Asset loading failed: ${t.assetName||"unknown"}`,"message"),description:"The asset could not be loaded",suggestions:["Check if the asset URL is correct","Verify the file exists","Check network connection","Check CORS settings"]},[_.E7043]:{code:_.E7043,severity:P.Error,category:x.API,message:w(t=>`Invalid asset type: '${t.assetType}'`,"message"),description:"The asset type is not supported",suggestions:["Use a supported asset type","Check asset type documentation"]},[_.E7044]:{code:_.E7044,severity:P.Error,category:x.API,message:w(t=>`Asset '${t.assetName}' is not ready`,"message"),description:"The asset exists but has not finished loading",suggestions:["Wait for the asset to finish loading","Check asset.ready before using it"]}},nn={[_.E7011]:{code:_.E7011,severity:P.Error,category:x.API,message:"Audio context creation failed",description:"The browser could not create an AudioContext",suggestions:["Check if the browser supports Web Audio API","Try user interaction to activate audio","Check browser console for more details"]},[_.E7012]:{code:_.E7012,severity:P.Error,category:x.API,message:"Audio worklet failed to start",description:"The audio worklet processor could not be initialized",suggestions:["Check if AudioWorklet is supported","Verify the worklet code is valid","Check browser console for errors"]},[_.E7013]:{code:_.E7013,severity:P.Error,category:x.API,message:w(t=>`Sound not found: '${t.soundName}'`,"message"),description:"The requested sound does not exist in the sound collection",suggestions:["Check if the sound name is spelled correctly","Verify the sound was loaded before use","Check the sound file path"]},[_.E7014]:{code:_.E7014,severity:P.Error,category:x.API,message:w(t=>`Music not found: '${t.musicName}'`,"message"),description:"The requested music does not exist in the music collection",suggestions:["Check if the music name is spelled correctly","Verify the music was loaded before use","Check the music file path"]},[_.E7015]:{code:_.E7015,severity:P.Error,category:x.API,message:"Audio context is suspended",description:"The audio context requires user interaction to resume",suggestions:["Wait for user interaction (click, touch, keypress)","The context will resume automatically","Check if audio autoplay is blocked"]},[_.E7016]:{code:_.E7016,severity:P.Error,category:x.API,message:w(t=>`Invalid audio parameters: ${t.error||"unknown"}`,"message"),description:"Audio playback parameters are invalid",suggestions:["Check volume is between 0 and 1","Check pitch is a positive number","Check pan is between -1 and 1"]}},an={[_.E7091]:{code:_.E7091,severity:P.Error,category:x.API,message:w(t=>`Drawing operation failed: ${t.operation||"unknown"}`,"message"),description:"A drawing operation could not be completed",suggestions:["Check if drawing context is valid","Verify drawing parameters","Check canvas state"]},[_.E7092]:{code:_.E7092,severity:P.Error,category:x.API,message:"Invalid drawing context",description:"The drawing context is invalid or not available",suggestions:["Check if canvas context is initialized","Verify context is not destroyed","Reinitialize drawing context"]},[_.E7093]:{code:_.E7093,severity:P.Error,category:x.API,message:w(t=>`Invalid drawing parameters: ${t.error||"unknown"}`,"message"),description:"Drawing parameters are invalid",suggestions:["Check coordinate values are valid numbers","Verify dimensions are positive","Check color values are valid","Verify all required parameters are provided"]}},on={[_.E7051]:{code:_.E7051,severity:P.Error,category:x.API,message:w(t=>`Input device not available: '${t.device}'`,"message"),description:"The requested input device is not available",suggestions:["Check if the device is connected","Verify browser permissions","Check device support"]},[_.E7052]:{code:_.E7052,severity:P.Error,category:x.API,message:w(t=>`Invalid input state: ${t.error||"unknown"}`,"message"),description:"Input state is invalid or corrupted",suggestions:["Reinitialize input system","Check input device connections"]}},hn={[_.E7031]:{code:_.E7031,severity:P.Error,category:x.API,message:"Map canvas context failed",description:"Could not get 2D context for map rendering canvas",suggestions:["Check if canvas element is valid","Verify browser supports canvas"]},[_.E7032]:{code:_.E7032,severity:P.Error,category:x.API,message:w(t=>`Invalid tile coordinates: (${t.x}, ${t.y})`,"message"),description:"Tile coordinates are out of map bounds",suggestions:["Check coordinates are within map dimensions","Verify map was properly initialized"]},[_.E7033]:{code:_.E7033,severity:P.Error,category:x.API,message:w(t=>`Tile sprite not found: '${t.spriteName}'`,"message"),description:"The sprite for the tile does not exist",suggestions:["Check if the sprite name is correct","Verify the sprite was loaded","Check tile definition"]},[_.E7034]:{code:_.E7034,severity:P.Error,category:x.API,message:w(t=>`Invalid map dimensions: ${t.width||"?"}x${t.height||"?"}`,"message"),description:"Map dimensions are invalid",suggestions:["Ensure width and height are positive numbers","Check map initialization"]}},ln={[_.E7071]:{code:_.E7071,severity:P.Error,category:x.API,message:w(t=>`Palette not found: '${t.paletteName}'`,"message"),description:"The requested palette does not exist",suggestions:["Check if the palette name is correct","Verify the palette was loaded","Check palette loading order"]},[_.E7072]:{code:_.E7072,severity:P.Error,category:x.API,message:w(t=>`Invalid palette format: ${t.format||"unknown"}`,"message"),description:"The palette format is not supported",suggestions:["Use a supported palette format","Check palette format documentation","Verify the palette file format"]},[_.E7073]:{code:_.E7073,severity:P.Error,category:x.API,message:w(t=>`Invalid color index: ${t.index} (valid range: 0-${t.maxIndex||255})`,"message"),description:"The color index is out of palette range",suggestions:["Check color index is within palette range","Verify palette size","Use a valid color index"]},[_.E7074]:{code:_.E7074,severity:P.Error,category:x.API,message:w(t=>`Palette loading failed: ${t.paletteName||"unknown"}`,"message"),description:"The palette could not be loaded",suggestions:["Check if the palette file exists","Verify the palette file format","Check file permissions","Check network connection if loading from URL"]},[_.E7075]:{code:_.E7075,severity:P.Error,category:x.API,message:w(t=>`Invalid palette size: ${t.size||"unknown"} (expected: ${t.expectedSize||"256"})`,"message"),description:"The palette size is invalid",suggestions:["Check palette size matches expected size","Verify palette data is complete","Check palette initialization"]}},cn={[_.E7001]:{code:_.E7001,severity:P.Error,category:x.API,message:"Failed to get 2D canvas context",description:"The browser could not create a 2D rendering context for the canvas",suggestions:["Check if the canvas element is valid","Verify the browser supports canvas 2D rendering","Check for conflicting canvas contexts"]},[_.E7002]:{code:_.E7002,severity:P.Error,category:x.API,message:w(t=>`Invalid canvas dimensions: ${t.width||"?"}x${t.height||"?"}`,"message"),description:"Canvas dimensions are invalid (zero or negative)",suggestions:["Ensure width and height are positive numbers","Check if canvas was properly initialized"]},[_.E7003]:{code:_.E7003,severity:P.Error,category:x.API,message:w(t=>`Invalid color format: ${t.color}`,"message"),description:"The color value provided is not in a valid format",suggestions:["Use hex format: '#RRGGBB' or '#RGB'","Use named colors: 'red', 'blue', etc.","Use numeric format for palette colors"]},[_.E7004]:{code:_.E7004,severity:P.Error,category:x.API,message:w(t=>`Sprite not found: '${t.spriteName}'`,"message"),description:"The requested sprite does not exist in the sprite collection",suggestions:["Check if the sprite name is spelled correctly","Verify the sprite was loaded before use","Check if the sprite is in the correct namespace"]},[_.E7005]:{code:_.E7005,severity:P.Error,category:x.API,message:w(t=>`Sprite '${t.spriteName}' is not ready`,"message"),description:"The sprite exists but has not finished loading",suggestions:["Wait for the sprite to finish loading","Check sprite.ready before using it","Use a callback or promise to wait for loading"]},[_.E7006]:{code:_.E7006,severity:P.Error,category:x.API,message:w(t=>`Invalid font: '${t.font}'`,"message"),description:"The font name is invalid or not available",suggestions:["Use a valid font name","Check if the font is loaded","Use a fallback font"]},[_.E7007]:{code:_.E7007,severity:P.Error,category:x.API,message:w(t=>`Invalid blend mode: '${t.blendMode}'`,"message"),description:"The blend mode is not supported",suggestions:["Use a valid blend mode: 'normal', 'additive', 'multiply', etc.","Check the list of supported blend modes"]}},un={[_.E7021]:{code:_.E7021,severity:P.Error,category:x.API,message:w(t=>`Sprite loading failed: ${t.url||"unknown URL"}`,"message"),description:"The sprite image could not be loaded",suggestions:["Check if the URL is correct","Verify the image file exists","Check CORS settings if loading from different domain","Check browser console for network errors"]},[_.E7022]:{code:_.E7022,severity:P.Error,category:x.API,message:w(t=>`Invalid sprite properties: ${t.error||"unknown"}`,"message"),description:"Sprite properties are invalid",suggestions:["Check frames is a positive number","Check fps is a positive number","Verify all required properties are set"]},[_.E7023]:{code:_.E7023,severity:P.Error,category:x.API,message:w(t=>`Invalid sprite URL: ${t.url}`,"message"),description:"The sprite URL is invalid or malformed",suggestions:["Use a valid URL or relative path","Check if the URL is properly formatted","Verify the file extension is correct"]},[_.E7024]:{code:_.E7024,severity:P.Error,category:x.API,message:w(t=>`Sprite frame out of bounds: frame ${t.frame} of ${t.totalFrames}`,"message"),description:"The requested frame index is out of range",suggestions:["Check frame index is between 0 and totalFrames-1","Verify the sprite has the expected number of frames"]}},fn={[_.E7061]:{code:_.E7061,severity:P.Error,category:x.API,message:"Storage quota exceeded",description:"The storage quota has been exceeded",suggestions:["Clear old storage data","Reduce the amount of data stored","Check storage quota limits"]},[_.E7062]:{code:_.E7062,severity:P.Error,category:x.API,message:w(t=>`Storage operation failed: ${t.error||"unknown"}`,"message"),description:"A storage operation could not be completed",suggestions:["Check storage permissions","Verify storage is available","Check browser console for details"]},[_.E7063]:{code:_.E7063,severity:P.Error,category:x.API,message:w(t=>`Invalid storage key: '${t.key}'`,"message"),description:"The storage key is invalid",suggestions:["Use a valid key format","Check key length and characters"]}},pn={[_.E7081]:{code:_.E7081,severity:P.Error,category:x.API,message:w(t=>`Invalid time value: ${t.value||"unknown"}`,"message"),description:"The time value is invalid or out of range",suggestions:["Check time value is a positive number","Verify time is within valid range","Check time format"]},[_.E7082]:{code:_.E7082,severity:P.Error,category:x.API,message:w(t=>`Time playback failed: ${t.error||"unknown"}`,"message"),description:"Time playback operation could not be completed",suggestions:["Check if time playback is initialized","Verify playback state","Check for conflicting time operations"]},[_.E7083]:{code:_.E7083,severity:P.Error,category:x.API,message:w(t=>`Time recording failed: ${t.error||"unknown"}`,"message"),description:"Time recording operation could not be completed",suggestions:["Check if time recording is initialized","Verify recording state","Check available storage space"]},[_.E7084]:{code:_.E7084,severity:P.Error,category:x.API,message:w(t=>`Invalid time format: ${t.format||"unknown"}`,"message"),description:"The time format is not supported",suggestions:["Use a supported time format","Check time format documentation","Verify time string format"]}},dn={[_.E7100]:{code:_.E7100,severity:P.Error,category:x.API,message:w(t=>{let e=t.suggestion;return e?`Unknown property '${t.propertyName}' on ${t.objectName}. Did you mean '${e}'?`:`Unknown property '${t.propertyName}' on ${t.objectName}.`},"message"),description:"A property or method that does not exist on the API object was accessed",suggestions:["Check if the property name is spelled correctly","Verify the API object supports this property","Check the API documentation for available properties"]}},mn={...cn,...nn,...un,...hn,...rn,...on,...fn,...ln,...pn,...an,...dn},gn={[Je.E6001]:{code:Je.E6001,severity:P.Error,category:x.CLI,message:w(t=>String(t.error||"Configuration error"),"message"),description:"An error occurred while processing configuration",suggestions:["Check the configuration file","Verify all required configuration options are present"]},[Je.E6002]:{code:Je.E6002,severity:P.Error,category:x.CLI,message:w(t=>String(t.error||"Build error"),"message"),description:"An error occurred during the build process",suggestions:["Check the build output for details","Fix the reported errors and try again"]},[Je.E6003]:{code:Je.E6003,severity:P.Error,category:x.CLI,message:w(t=>String(t.error||"Server error"),"message"),description:"An error occurred in the development server",suggestions:["Check the server logs for details","Restart the development server"]}},_n={[Ke.E3001]:{code:Ke.E3001,severity:P.Error,category:x.Compilation,message:w(t=>String(t.error||"Compilation failed"),"message"),description:"The compilation process encountered an error",suggestions:["Check the error messages above for details","Fix the reported errors and try again"]},[Ke.E3002]:{code:Ke.E3002,severity:P.Error,category:x.Compilation,message:w(t=>`File not found: ${t.filePath||t.file||"unknown file"}`,"message"),description:"A required file could not be found",suggestions:["Check if the file path is correct","Verify the file exists at the specified location"]},[Ke.E3003]:{code:Ke.E3003,severity:P.Error,category:x.Compilation,message:w(t=>String(t.error||"Parse error"),"message"),description:"The source code could not be parsed",suggestions:["Check the syntax of the source code","Look for syntax errors in the file"]}},En={[be.E2001]:{code:be.E2001,severity:P.Error,category:x.Runtime,message:w(t=>`Undefined variable '${t.variableName}'`,"message"),description:"A variable was referenced but not defined",suggestions:["Check if the variable name is spelled correctly","Verify the variable is defined before use","Check the variable scope"]},[be.E2002]:{code:be.E2002,severity:P.Error,category:x.Runtime,message:w(t=>`Type mismatch: expected ${t.expectedType}, got ${t.actualType}`,"message"),description:"An operation was performed with incompatible types",suggestions:["Check the types of the operands","Use type conversion if needed"]},[be.E2003]:{code:be.E2003,severity:P.Error,category:x.Runtime,message:"Division by zero",description:"An attempt was made to divide by zero",suggestions:["Check the divisor before division","Add a conditional check to prevent division by zero"]},[be.E2004]:{code:be.E2004,severity:P.Error,category:x.Runtime,message:w(t=>`Function '${t.functionName}' not found`,"message"),description:"A function was called but not defined",suggestions:["Check if the function name is spelled correctly","Verify the function is defined before use","Check if the function is in the correct scope"]},[be.E2005]:{code:be.E2005,severity:P.Error,category:x.Runtime,message:w(t=>String(t.error||"Invalid operation"),"message"),description:"An invalid operation was attempted",suggestions:["Check the operation and its operands","Verify the operation is valid for the given types"]}},yn={[fe.E5001]:{code:fe.E5001,severity:P.Error,category:x.Scene,message:w(t=>`Invalid path: ${t.path}`,"message"),description:"An invalid scene path was provided",suggestions:["Check the path format","Verify the path is valid"]},[fe.E5002]:{code:fe.E5002,severity:P.Error,category:x.Scene,message:w(t=>`Invalid scene name: ${t.name}`,"message"),description:"An invalid scene name was provided",suggestions:["Check the scene name format","Verify the scene name is valid"]},[fe.E5003]:{code:fe.E5003,severity:P.Error,category:x.Scene,message:w(t=>`Invalid scene definition for '${t.name}'`,"message"),description:"A scene was defined with invalid configuration",suggestions:["Check the scene definition syntax","Verify all required properties are provided"]},[fe.E5004]:{code:fe.E5004,severity:P.Error,category:x.Scene,message:w(t=>`Scene not found: ${t.name}`,"message"),description:"A requested scene could not be found",suggestions:["Check if the scene is registered","Verify the scene name is correct"]},[fe.E5005]:{code:fe.E5005,severity:P.Error,category:x.Scene,message:w(t=>`No route matched for path: ${t.path}`,"message"),description:"No scene route matched the provided path",suggestions:["Check if a route exists for this path","Verify the path format matches the route pattern"]},[fe.E5006]:{code:fe.E5006,severity:P.Error,category:x.Scene,message:"No scenes registered",description:"No scenes have been registered in the router",suggestions:["Register at least one scene before using the router","Check if scene registration is called"]},[fe.E5007]:{code:fe.E5007,severity:P.Error,category:x.Scene,message:w(t=>`Scene '${t.name}' has no draw() function`,"message"),description:"A scene is missing the required draw function",suggestions:["Add a draw() function to the scene","Check if the function name is correct"]}},bn={[te.E1001]:{code:te.E1001,severity:P.Error,category:x.Syntax,message:w(t=>t.functionName?`Function '${t.functionName}' started at line ${t.functionStartLine} is not closed`:`Unterminated '${t.blockType||"block"}' ; no matching 'end' found`,"message"),description:"A function or block declaration was started but not properly closed",suggestions:w(t=>t.functionName?[`Add 'end' after the last statement to close function '${t.functionName}'`,"Check if you have an extra 'end' statement somewhere","Verify all nested blocks (if, for, while) are properly closed"]:[`Add 'end' to close the '${t.blockType||"block"}' statement`,"Check if you have nested blocks that need to be closed first"],"suggestions")},[te.E1002]:{code:te.E1002,severity:P.Error,category:x.Syntax,message:"Too many 'end' statements",description:"An 'end' keyword was found without a matching opening statement",suggestions:["Remove the extra 'end' statement","Check if you have a missing opening statement (if, for, while, function)"]},[te.E1003]:{code:te.E1003,severity:P.Error,category:x.Syntax,message:"Missing 'end' statement",description:"A block was opened but not closed with 'end'",suggestions:["Add an 'end' statement to close the block","Check all nested blocks are properly closed"]},[te.E1004]:{code:te.E1004,severity:P.Error,category:x.Syntax,message:w(t=>String(t.error||"Unexpected token"),"message"),description:"An unexpected token was encountered during parsing",suggestions:["Check the syntax around this location","Verify you're using the correct syntax for this statement"]},[te.E1005]:{code:te.E1005,severity:P.Error,category:x.Syntax,message:w(t=>`Missing ${t.expected||"token"}`,"message"),description:"A required token was expected but not found",suggestions:["Check if you're missing a required keyword or symbol","Verify the syntax is complete"]},[te.E1006]:{code:te.E1006,severity:P.Error,category:x.Syntax,message:"Unexpected end of file",description:"The file ended while parsing was incomplete",suggestions:["Check if you're missing a closing statement","Verify all blocks are properly closed"]},[te.E1007]:{code:te.E1007,severity:P.Error,category:x.Syntax,message:w(t=>`Misuse of reserved keyword '${t.keyword}'`,"message"),description:"A reserved keyword was used incorrectly",suggestions:["Use a different identifier name","Check the context where this keyword is used"]},[te.E1008]:{code:te.E1008,severity:P.Error,category:x.Syntax,message:"Unterminated string",description:"A string literal was started but not closed",suggestions:["Add a closing quote to terminate the string","Check for escaped quotes within the string"]},[te.E1009]:{code:te.E1009,severity:P.Error,category:x.Syntax,message:w(t=>`Unterminated ${t.type||"object/array"}`,"message"),description:"An object or array was started but not closed",suggestions:["Add a closing brace or bracket","Check for nested objects/arrays that need to be closed first"]}},Tn={[pe.W1001]:{code:pe.W1001,severity:P.Warning,category:x.Syntax,message:w(t=>`Assigning to API variable '${t.variableName}'`,"message"),description:"You are modifying a read-only API variable",suggestions:["Use a local variable instead","Check if you meant to use a different variable"]},[pe.W1002]:{code:pe.W1002,severity:P.Warning,category:x.Syntax,message:"Assignment used as condition",description:"An assignment operator (=) was used in a condition instead of comparison (==)",suggestions:["Use == for comparison instead of =","Check if you meant to assign before comparing"]},[pe.W2001]:{code:pe.W2001,severity:P.Warning,category:x.Runtime,message:w(t=>`Deprecated API usage: ${t.apiName}`,"message"),description:"A deprecated API is being used",suggestions:["Update to the new API","Check the documentation for migration guide"]},[pe.W5001]:{code:pe.W5001,severity:P.Warning,category:x.Scene,message:w(t=>`Activating first available scene: ${t.sceneName}`,"message"),description:"No route matched, so the first scene was activated",suggestions:["Register a route for the initial path","Check if the route pattern is correct"]},[pe.W5002]:{code:pe.W5002,severity:P.Warning,category:x.Scene,message:w(t=>`No route matched initial path, activating first scene: ${t.sceneName}`,"message"),description:"The initial path didn't match any route",suggestions:["Register a route for the initial path","Check if the route pattern matches the initial path"]},[pe.W5003]:{code:pe.W5003,severity:P.Warning,category:x.Scene,message:"No scenes registered. Game may show blank screen.",description:"No scenes have been registered",suggestions:["Register at least one scene","Check if scene registration is called"]},[pe.W5004]:{code:pe.W5004,severity:P.Warning,category:x.Scene,message:"No scenes registered. Make sure to call scene() before router.init().",description:"Router was initialized before any scenes were registered",suggestions:["Register scenes before calling router.init()","Check the order of initialization"]}},vn={...bn,...En,..._n,...yn,...gn,...mn,...Tn};function hs(t){return vn[t]}l(hs,"getMessageTemplate");w(hs,"getMessageTemplate");function vi(t,e={}){let s=hs(t);return s?typeof s.message=="string"?s.message:s.message(e):e.error||e.message||`Unknown error: ${t}`}l(vi,"formatMessage");w(vi,"formatMessage");function ct(t,e={}){let s=hs(t);return!s||!s.suggestions?[]:typeof s.suggestions=="function"?s.suggestions(e):s.suggestions}l(ct,"getSuggestions");w(ct,"getSuggestions");function An(t){let e=[],s=t.code||"",i=t.severity||P.Error,r=t.message||"Unknown error",n=i===P.Error?"\u2717":"\u26A0";if(e.push(`${n} [${s}] ${r}`),t.file){let o=` at ${t.file}`;t.line!==void 0&&(o+=`:${t.line}`,t.column!==void 0&&(o+=`:${t.column}`)),e.push(o)}t.context&&(e.push(""),e.push(t.context));let a=t.suggestions||ct(s,t.data);if(a.length>0){e.push(""),e.push("Suggestions:");for(let o of a)e.push(` \u2022 ${o}`)}if(t.related&&(e.push(""),e.push(`Related: ${t.related.message} at ${t.related.file}:${t.related.line}:${t.related.column}`)),t.stackTrace&&t.stackTrace.length>0){e.push(""),e.push("Stack trace:");for(let o of t.stackTrace){let u=o.functionName||"<anonymous>";e.push(` at ${u} (${o.file}:${o.line}:${o.column})`)}}return e.join(`
|
|
2
|
+
`)}l(An,"formatForCLI");w(An,"formatForCLI");function Pn(t){let e=Math.max(0,(t.line||1)-1),s=Math.max(0,(t.column||1)-1),i=t.length||1,r=s+i,n;switch(t.severity){case P.Error:n=1;break;case P.Warning:n=2;break;case P.Info:n=3;break;default:n=1}let a={range:{start:{line:e,character:s},end:{line:e,character:r}},severity:n,message:t.message||"Unknown error",source:"l8b"};t.code&&(a.code=t.code);let o=[];t.related&&o.push({location:{uri:t.related.file,range:{start:{line:t.related.line-1,character:t.related.column-1},end:{line:t.related.line-1,character:t.related.column+10}}},message:t.related.message||"Related location"});let u=t.suggestions||ct(t.code||"",t.data);return u.length>0&&o.push({location:{uri:t.file||"",range:{start:{line:e,character:s},end:{line:e,character:r}}},message:`\u{1F4A1} ${u[0]}`}),o.length>0&&(a.relatedInformation=o),a}l(Pn,"formatForLSP");w(Pn,"formatForLSP");function Te(t){let e=t.code||"",s=t.message||"Unknown error",i="";e&&(i+=`[${e}] `),i+=s,t.file&&(i+=`
|
|
3
|
+
at ${t.file}`,t.line!==void 0&&(i+=`:${t.line}`,t.column!==void 0&&(i+=`:${t.column}`))),t.context&&(i+=`
|
|
4
|
+
|
|
5
|
+
${t.context}`);let r=t.suggestions||ct(e,t.data);if(r.length>0){i+=`
|
|
6
|
+
|
|
7
|
+
Suggestions:`;for(let n of r)i+=`
|
|
8
|
+
\u2022 ${n}`}if(t.related&&(i+=`
|
|
9
|
+
|
|
10
|
+
Related: ${t.related.message} at ${t.related.file}:${t.related.line}:${t.related.column}`),t.stackTrace&&t.stackTrace.length>0){i+=`
|
|
11
|
+
|
|
12
|
+
Stack trace:`;for(let n of t.stackTrace){let a=n.functionName||"<anonymous>";i+=`
|
|
13
|
+
at ${a} (${n.file}:${n.line}:${n.column})`}}return i}l(Te,"formatForBrowser");w(Te,"formatForBrowser");function N(t,e,s){let i=ve(e,{data:s}),r=Te(i);t?.reportError?.(r)}l(N,"reportRuntimeError");w(N,"reportRuntimeError");function On(t){let e=t.code||"",s=t.message||"Unknown error",i=t.file?` at ${t.file}${t.line?`:${t.line}`:""}`:"";return`[${e}] ${s}${i}`}l(On,"formatSimple");w(On,"formatSimple");function ve(t,e={}){let s=vi(t,{...e,...e.data}),i=e.suggestions||ct(t,{...e,...e.data});return{code:t,severity:t.startsWith("E")?P.Error:P.Warning,message:s,file:e.file,line:e.line,column:e.column,length:e.length,context:e.context,suggestions:i,related:e.related,stackTrace:e.stackTrace,data:e.data}}l(ve,"createDiagnostic");w(ve,"createDiagnostic");var kn=Object.defineProperty,H=l((t,e)=>kn(t,"name",{value:e,configurable:!0}),"__name"),Qe=440,ls=2**(1/12),cs=69,Sn=class{static{l(this,"Beeper")}static{H(this,"Beeper")}audio;notes={};plainNotes={};currentOctave=5;currentDuration=.5;currentVolume=.5;currentSpan=1;currentWaveform="square";constructor(t){this.audio=t,this.initializeNotes()}initializeNotes(){let t=[["C","DO"],["C#","DO#","Db","REb"],["D","RE"],["D#","RE#","Eb","MIb"],["E","MI"],["F","FA"],["F#","FA#","Gb","SOLb"],["G","SOL"],["G#","SOL#","Ab","LAb"],["A","LA"],["A#","LA#","Bb","SIb"],["B","SI"]];for(let e=0;e<=127;e++){this.notes[e]=e;let s=Math.floor(e/12)-1;for(let i of t[e%12])this.notes[i+s]=e;if(s===-1)for(let i of t[e%12])this.plainNotes[i]=e}}beep(t){let e="normal",s=[],i=[],r,n=t.split(" ");for(let a of n)if(a!=="")switch(e){case"normal":if(this.notes[a]!==void 0)r=this.notes[a],this.currentOctave=Math.floor(r/12),s.push({frequency:Qe*ls**(r-cs),volume:this.currentVolume,span:this.currentSpan,duration:this.currentDuration,waveform:this.currentWaveform});else if(this.plainNotes[a]!==void 0)r=this.plainNotes[a]+this.currentOctave*12,s.push({frequency:Qe*ls**(r-cs),volume:this.currentVolume,span:this.currentSpan,duration:this.currentDuration,waveform:this.currentWaveform});else if(["square","sine","saw","noise"].includes(a))this.currentWaveform=a;else if(["tempo","duration","volume","span","loop","to"].includes(a))e=a;else if(a==="-")s.push({frequency:Qe,volume:0,span:this.currentSpan,duration:this.currentDuration,waveform:this.currentWaveform});else if(a==="end"&&i.length>0&&s.length>0){s.push({frequency:Qe,volume:0,span:this.currentSpan,duration:0,waveform:this.currentWaveform});let o=i.splice(i.length-1,1)[0];s[s.length-1].loopto=o.start,s[s.length-1].repeats=o.repeats}break;case"tempo":{e="normal";let o=Number.parseFloat(a);!Number.isNaN(o)&&o>0&&(this.currentDuration=60/o);break}case"duration":{e="normal";let o=Number.parseFloat(a);!Number.isNaN(o)&&o>0&&(this.currentDuration=o/1e3);break}case"volume":{e="normal";let o=Number.parseFloat(a);Number.isNaN(o)||(this.currentVolume=o/100);break}case"span":{e="normal";let o=Number.parseFloat(a);Number.isNaN(o)||(this.currentSpan=o/100);break}case"loop":{e="normal",i.push({start:s.length});let o=Number.parseFloat(a);Number.isNaN(o)||(i[i.length-1].repeats=o);break}case"to":if(e="normal",r!==void 0){let o;if(this.notes[a]!==void 0?o=this.notes[a]:this.plainNotes[a]!==void 0&&(o=this.plainNotes[a]+this.currentOctave*12),o!==void 0&&o!==r){let u=o>r?1:-1;for(let g=r+u;u>0?g<=o:g>=o;g+=u)s.push({frequency:Qe*ls**(g-cs),volume:this.currentVolume,span:this.currentSpan,duration:this.currentDuration,waveform:this.currentWaveform});r=o}}break}if(i.length>0&&s.length>0){let a=i.splice(i.length-1,1)[0];s.push({frequency:Qe,volume:0,span:this.currentSpan,duration:0,waveform:this.currentWaveform}),s[s.length-1].loopto=a.start,s[s.length-1].repeats=a.repeats}this.audio.addBeeps(s)}},xn=`
|
|
14
|
+
class L8bAudioProcessor extends AudioWorkletProcessor {
|
|
15
|
+
constructor() {
|
|
16
|
+
super();
|
|
17
|
+
this.beeps = [];
|
|
18
|
+
this.last = 0;
|
|
19
|
+
this.port.onmessage = (event) => {
|
|
20
|
+
const data = JSON.parse(event.data);
|
|
21
|
+
if (data.name === "cancel_beeps") {
|
|
22
|
+
this.beeps = [];
|
|
23
|
+
} else if (data.name === "beep") {
|
|
24
|
+
const seq = data.sequence;
|
|
25
|
+
// Link sequence notes together
|
|
26
|
+
for (let i = 0; i < seq.length; i++) {
|
|
27
|
+
const note = seq[i];
|
|
28
|
+
if (i > 0) {
|
|
29
|
+
seq[i - 1].next = note;
|
|
30
|
+
}
|
|
31
|
+
// Resolve loopto index to actual note reference
|
|
32
|
+
if (note.loopto != null) {
|
|
33
|
+
note.loopto = seq[note.loopto];
|
|
34
|
+
}
|
|
35
|
+
// Initialize phase and time
|
|
36
|
+
note.phase = 0;
|
|
37
|
+
note.time = 0;
|
|
38
|
+
}
|
|
39
|
+
// Add first note to beeps queue
|
|
40
|
+
if (seq.length > 0) {
|
|
41
|
+
this.beeps.push(seq[0]);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
process(inputs, outputs, parameters) {
|
|
48
|
+
const output = outputs[0];
|
|
49
|
+
|
|
50
|
+
for (let i = 0; i < output.length; i++) {
|
|
51
|
+
const channel = output[i];
|
|
52
|
+
|
|
53
|
+
if (i > 0) {
|
|
54
|
+
// Copy first channel to other channels
|
|
55
|
+
for (let j = 0; j < channel.length; j++) {
|
|
56
|
+
channel[j] = output[0][j];
|
|
57
|
+
}
|
|
58
|
+
} else {
|
|
59
|
+
// Generate audio for first channel
|
|
60
|
+
for (let j = 0; j < channel.length; j++) {
|
|
61
|
+
let sig = 0;
|
|
62
|
+
|
|
63
|
+
for (let k = this.beeps.length - 1; k >= 0; k--) {
|
|
64
|
+
const b = this.beeps[k];
|
|
65
|
+
let volume = b.volume;
|
|
66
|
+
|
|
67
|
+
if (b.time / b.duration > b.span) {
|
|
68
|
+
volume = 0;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Generate waveform
|
|
72
|
+
switch (b.waveform) {
|
|
73
|
+
case "square":
|
|
74
|
+
sig += b.phase > 0.5 ? volume : -volume;
|
|
75
|
+
break;
|
|
76
|
+
case "saw":
|
|
77
|
+
sig += (b.phase * 2 - 1) * volume;
|
|
78
|
+
break;
|
|
79
|
+
case "noise":
|
|
80
|
+
sig += (Math.random() * 2 - 1) * volume;
|
|
81
|
+
break;
|
|
82
|
+
default: // sine
|
|
83
|
+
sig += Math.sin(b.phase * Math.PI * 2) * volume;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
b.phase = (b.phase + b.increment) % 1;
|
|
87
|
+
b.time += 1;
|
|
88
|
+
|
|
89
|
+
if (b.time >= b.duration) {
|
|
90
|
+
b.time = 0;
|
|
91
|
+
|
|
92
|
+
if (b.loopto != null) {
|
|
93
|
+
if (b.repeats != null && b.repeats > 0) {
|
|
94
|
+
if (b.loopcount == null) {
|
|
95
|
+
b.loopcount = 0;
|
|
96
|
+
}
|
|
97
|
+
b.loopcount++;
|
|
98
|
+
|
|
99
|
+
if (b.loopcount >= b.repeats) {
|
|
100
|
+
b.loopcount = 0;
|
|
101
|
+
if (b.next != null) {
|
|
102
|
+
b.next.phase = b.phase;
|
|
103
|
+
this.beeps[k] = b.next;
|
|
104
|
+
} else {
|
|
105
|
+
this.beeps.splice(k, 1);
|
|
106
|
+
}
|
|
107
|
+
} else {
|
|
108
|
+
b.loopto.phase = b.phase;
|
|
109
|
+
this.beeps[k] = b.loopto;
|
|
110
|
+
}
|
|
111
|
+
} else {
|
|
112
|
+
b.loopto.phase = b.phase;
|
|
113
|
+
this.beeps[k] = b.loopto;
|
|
114
|
+
}
|
|
115
|
+
} else if (b.next != null) {
|
|
116
|
+
b.next.phase = b.phase;
|
|
117
|
+
this.beeps[k] = b.next;
|
|
118
|
+
} else {
|
|
119
|
+
this.beeps.splice(k, 1);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
this.last = this.last * 0.9 + sig * 0.1;
|
|
125
|
+
channel[j] = this.last;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
registerProcessor("l8b-audio-processor", L8bAudioProcessor);
|
|
135
|
+
`,Ai=class{static{l(this,"AudioCore")}static{H(this,"AudioCore")}context;buffer=[];playing=[];wakeupList=[];workletNode;beeper;runtime;masterVolume=1;constructor(t){this.runtime=t,this.getContext()}isStarted(){return this.context.state==="running"}addToWakeUpList(t){this.wakeupList.push(t)}interfaceCache=null;setVolume(t){this.masterVolume=Math.max(0,Math.min(1,t))}getVolume(){return this.masterVolume}getInterface(){return this.interfaceCache?this.interfaceCache:(this.interfaceCache={beep:H(t=>this.beep(t),"beep"),cancelBeeps:H(()=>this.cancelBeeps(),"cancelBeeps"),playSound:H((t,e,s,i,r)=>this.playSound(t,e,s,i,r),"playSound"),playMusic:H((t,e,s)=>this.playMusic(t,e,s),"playMusic"),setVolume:H(t=>this.setVolume(t),"setVolume"),getVolume:H(()=>this.getVolume(),"getVolume"),stopAll:H(()=>this.stopAll(),"stopAll")},this.interfaceCache)}playSound(t,e=1,s=1,i=0,r=!1){if(typeof t=="string"){let n=t.replace(/\//g,"-"),a=this.runtime.sounds[n];return a?a.play(e*this.masterVolume,s,i,r):(N(this.runtime?.listener,_.E7013,{soundName:n}),0)}return 0}playMusic(t,e=1,s=!1){if(typeof t=="string"){let i=t.replace(/\//g,"-"),r=this.runtime.music[i];return r?r.play(e*this.masterVolume,s):(N(this.runtime?.listener,_.E7014,{musicName:i}),0)}return 0}getContext(){if(!this.context){let t=window.AudioContext||window.webkitAudioContext;if(this.context=new t,this.context.state!=="running"){let e=H(()=>{if(this.context&&this.context.state!=="running"){this.context.resume(),this.beeper&&this.start();for(let s of this.wakeupList)s.wakeUp();document.body.removeEventListener("touchend",e),document.body.removeEventListener("mouseup",e),document.body.removeEventListener("click",e),document.body.removeEventListener("keydown",e)}},"activate");document.body.addEventListener("touchend",e,{once:!0}),document.body.addEventListener("mouseup",e,{once:!0}),document.body.addEventListener("click",e,{once:!0}),document.body.addEventListener("keydown",e,{once:!0})}else this.beeper&&this.start()}return this.context}async start(){if(!this.workletNode)try{let t=new Blob([xn],{type:"application/javascript"}),e=URL.createObjectURL(t);await this.context.audioWorklet.addModule(e),this.workletNode=new AudioWorkletNode(this.context,"l8b-audio-processor"),this.workletNode.connect(this.context.destination),this.flushBuffer()}catch(t){N(this.runtime?.listener,_.E7012,{error:String(t)})}}flushBuffer(){if(this.workletNode)for(;this.buffer.length>0;)this.workletNode.port.postMessage(this.buffer.splice(0,1)[0])}getBeeper(){return this.beeper||(this.beeper=new Sn(this),this.context.state==="running"&&this.start()),this.beeper}beep(t){this.getBeeper().beep(t)}addBeeps(t){for(let e of t)e.duration*=this.context.sampleRate,e.increment=e.frequency/this.context.sampleRate;this.workletNode?this.workletNode.port.postMessage(JSON.stringify({name:"beep",sequence:t})):this.buffer.push(JSON.stringify({name:"beep",sequence:t}))}cancelBeeps(){this.workletNode?this.workletNode.port.postMessage(JSON.stringify({name:"cancel_beeps"})):this.buffer.push(JSON.stringify({name:"cancel_beeps"})),this.stopAll()}addPlaying(t){this.playing.push(t)}removePlaying(t){let e=this.playing.indexOf(t);e>=0&&this.playing.splice(e,1)}stopAll(){for(let t of this.playing)try{t.stop()}catch(e){N(this.runtime?.listener,_.E7016,{error:String(e)})}this.playing=[]}},us=class{static{l(this,"Music")}static{H(this,"Music")}ready=1;name="";url;tag;playing=!1;audio;constructor(t,e){this.audio=t,this.url=e,this.tag=new Audio(this.url),this.ready=1}play(t=1,e=!1){return this.playing=!0,this.tag.loop=!!e,this.tag.volume=Math.max(0,Math.min(1,t)),this.audio.isStarted()?this.tag.play():this.audio.addToWakeUpList(this),this.audio.addPlaying(this),{play:H(()=>this.tag.play(),"play"),stop:H(()=>{this.playing=!1,this.tag.pause(),this.audio.removePlaying(this)},"stop"),setVolume:H(s=>{this.tag.volume=Math.max(0,Math.min(1,s))},"setVolume"),getPosition:H(()=>this.tag.currentTime,"getPosition"),getDuration:H(()=>this.tag.duration,"getDuration"),setPosition:H(s=>{this.tag.pause(),this.tag.currentTime=Math.max(0,Math.min(this.tag.duration,s)),this.playing&&this.tag.play()},"setPosition")}}wakeUp(){this.playing&&this.tag.play()}stop(){this.playing=!1,this.tag.pause(),this.audio.removePlaying(this)}},Me=class Pi{static{l(this,"_Sound")}static{H(this,"Sound")}ready=0;buffer;name="";url;audio;constructor(e,s){this.audio=e,s instanceof AudioBuffer?(this.buffer=s,this.url="",this.ready=1):(this.url=s,this.loadSound(s))}loadSound(e){let s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=()=>{this.audio.context.decodeAudioData(s.response,i=>{this.buffer=i,this.ready=1},i=>{N(this.audio?.runtime?.listener,_.E7016,{error:`Audio decoding failed: ${String(i)}`})})},s.onerror=()=>{N(this.audio?.runtime?.listener,_.E7016,{error:`Failed to load sound: ${e}`})},s.send()}play(e=1,s=1,i=0,r=!1){if(!this.buffer)return{stop:H(()=>{},"stop"),finished:!0};let n=this.audio.context,a=n.createBufferSource();a.playbackRate.value=s,a.buffer=this.buffer,r&&(a.loop=!0);let o=n.createGain();o.gain.value=e;let u=n.createPanner();u.panningModel="equalpower",u.setPan=O=>{u.setPosition(O,0,1-Math.abs(O))},u.setPan(i),a.connect(o),o.connect(u),u.connect(n.destination),a.start();let g=null;r&&(g={stop:H(()=>{a.stop()},"stop")},this.audio.addPlaying(g));let y={stop:H(()=>(a.stop(),g&&this.audio.removePlaying(g),1),"stop"),setVolume:H(O=>{o.gain.value=Math.max(0,Math.min(1,O))},"setVolume"),setPitch:H(O=>{a.playbackRate.value=Math.max(.001,Math.min(1e3,O))},"setPitch"),setPan:H(O=>{u.setPan(Math.max(-1,Math.min(1,O)))},"setPan"),getDuration:H(()=>a.buffer?a.buffer.duration:0,"getDuration"),finished:!1};return a.onended=()=>{y.finished=!0},y}static createSoundClass(e){return class{static{l(this,"MicroSound")}static{H(this,"MicroSound")}static classname="Sound";channels;length;sampleRate;sound;buffer;constructor(i,r,n=44100){i=i===1?1:2,r>1&&r<44100*1e3||(r=44100),n>=8e3&&n<=96e3||(n=44100),this.channels=i,this.length=r,this.sampleRate=n,this.buffer=e.context.createBuffer(i,r,n),this.sound=new Pi(e,this.buffer)}play(i,r,n,a){return this.sound.play(i,r,n,a)}write(i,r,n){if(i===0){let a=this.buffer.getChannelData(0);a[r]=n}else if(this.channels===2){let a=this.buffer.getChannelData(1);a[r]=n}}read(i,r){return i===0?this.buffer.getChannelData(0)[r]:this.channels===2?this.buffer.getChannelData(1)[r]:0}}}};var Ln=Object.defineProperty,ge=l((t,e)=>Ln(t,"name",{value:e,configurable:!0}),"__name"),wn=ge((t,e,s,i,r)=>{t.canvas||(t.canvas=document.createElement("canvas"));let n=e*i,a=s*r;(t.canvas.width!==n||t.canvas.height!==a)&&(t.canvas.width=n,t.canvas.height=a);let o=t.canvas.getContext("2d");if(!o){let u=ve(_.E7031),g=Te(u);throw new Error(g)}return o.clearRect(0,0,t.canvas.width,t.canvas.height),t.animated=[],o},"ensureCanvas"),Rn=ge((t,e,s,i,r,n,a)=>{let o=e.frames[0].canvas;if(!o||o.width===0||o.height===0)return!1;if(a.subX!=null){let u=a.subX*s,g=(a.subY??0)*i;t.drawImage(o,u,g,s,i,s*r,i*n,s,i)}else t.drawImage(o,s*r,i*n);return!0},"drawTile"),Cn=ge((t,e,s,i,r,n,a)=>{let o={x:s*r,y:i*n,w:s,h:i,sprite:e};a.subX!=null&&(o.tx=a.subX*s,o.ty=(a.subY??0)*i),t.animated.push(o)},"queueAnimatedTile"),In=ge((t,e,s)=>{let i=performance.now();(!t.buffer||t.buffer.width!==e*(t.canvas.width/e)||t.buffer.height!==s*(t.canvas.height/s))&&(t.buffer=document.createElement("canvas"),t.buffer.width=t.canvas.width,t.buffer.height=t.canvas.height);let r=t.buffer.getContext("2d");r.clearRect(0,0,t.buffer.width,t.buffer.height),r.drawImage(t.canvas,0,0);for(let n of t.animated){let a=n.sprite.frames.length,o=n.sprite.frames[Math.floor(i/1e3*n.sprite.fps)%a]?.canvas;o&&(n.tx!=null&&n.ty!=null?r.drawImage(o,n.tx,n.ty,e,s,n.x,n.y,e,s):r.drawImage(o,n.x,n.y,e,s))}return t.buffer},"renderAnimatedTiles"),Mn=ge(t=>t.replace(/\//g,"-"),"normalizeRefForStorage"),Oi=ge(t=>t.replace(/-/g,"/"),"normalizeRefForUsage");function fs(t){let e=t.indexOf(":");if(e===-1)return{spriteName:t};let s=t.substring(0,e),i=t.substring(e+1),r=i.indexOf(",");return r===-1?{spriteName:s,subX:Number.parseInt(i,10)}:{spriteName:s,subX:Number.parseInt(i.substring(0,r),10),subY:Number.parseInt(i.substring(r+1),10)}}l(fs,"parseTileRef");ge(fs,"parseTileRef");var Xe=class ki{static{l(this,"_TileMap")}static{ge(this,"TileMap")}width;height;block_width;block_height;sprites;map=[];ready=!0;needs_update=!1;name="";parsedMap=[];renderState={canvas:null,buffer:null,animated:[]};constructor(e,s,i,r,n){if(e<=0||s<=0||!isFinite(e)||!isFinite(s)){let a=ve(_.E7034,{data:{width:e,height:s}}),o=Te(a);throw new Error(o)}this.width=e,this.height=s,this.block_width=i,this.block_height=r,this.sprites=n??{},this.clear()}clear(){for(let e=0;e<this.height;e++)for(let s=0;s<this.width;s++){let i=s+e*this.width;this.map[i]=null,this.parsedMap[i]=null}}set(e,s,i){if(e<0||s<0||e>=this.width||s>=this.height||!isFinite(e)||!isFinite(s))return;let r=i;typeof r=="string"&&(r=Mn(r));let n=e+s*this.width;this.map[n]=r,this.parsedMap[n]=r?fs(r):null,this.needs_update=!0}get(e,s){if(e<0||s<0||e>=this.width||s>=this.height||!isFinite(e)||!isFinite(s))return 0;let i=this.map[e+s*this.width];return typeof i=="string"&&(i=Oi(i)),i||0}getCanvas(){return(this.renderState.canvas==null||this.needs_update)&&this.update(),this.renderState.canvas}draw(e,s,i,r,n){if(this.renderState.animated.length>0){let a=In(this.renderState,this.block_width,this.block_height);e.drawImage(a,s,i,r,n)}else e.drawImage(this.getCanvas(),s,i,r,n)}update(){this.needs_update=!1;let e=wn(this.renderState,this.width,this.height,this.block_width,this.block_height);for(let s=0;s<this.height;s++)for(let i=0;i<this.width;i++){let r=i+(this.height-1-s)*this.width,n=this.parsedMap[r];if(!n)continue;let a=this.sprites[n.spriteName]||this.sprites[Oi(n.spriteName)];!a||!a.frames[0]||(a.frames.length>1?Cn(this.renderState,a,this.block_width,this.block_height,i,s,n):Rn(e,a,this.block_width,this.block_height,i,s,n))}}loadFile(e,s){let i=new XMLHttpRequest;i.onreadystatechange=()=>{i.readyState===XMLHttpRequest.DONE&&i.status===200&&(this.load(i.responseText,this.sprites),this.update(),s?.())},i.open("GET",e),i.send()}load(e,s){let i=JSON.parse(e);this.width=i.width,this.height=i.height,this.block_width=i.block_width,this.block_height=i.block_height,this.sprites=s??this.sprites;for(let r=0;r<i.height;r++)for(let n=0;n<i.width;n++){let a=n+r*i.width,o=i.data[a];if(o>0){let u=i.sprites[o];this.map[a]=u,this.parsedMap[a]=fs(u)}else this.map[a]=null,this.parsedMap[a]=null}this.needs_update=!0}clone(){let e=new ki(this.width,this.height,this.block_width,this.block_height,this.sprites);for(let s=0;s<this.height;s++)for(let i=0;i<this.width;i++){let r=i+s*this.width;e.map[r]=this.map[r],e.parsedMap[r]=this.parsedMap[r]}return e.needs_update=!0,e}copyFrom(e){this.width=e.width,this.height=e.height,this.block_width=e.block_width,this.block_height=e.block_height;for(let s=0;s<this.height;s++)for(let i=0;i<this.width;i++){let r=i+s*this.width;this.map[r]=e.map[r],this.parsedMap[r]=e.parsedMap[r]}return this.update(),this}};function ps(t,e,s){let i=new Xe(1,1,1,1,e);i.ready=!1;let r=new XMLHttpRequest;return r.onreadystatechange=()=>{r.readyState===XMLHttpRequest.DONE&&(i.ready=!0,r.status===200&&Si(i,r.responseText,e),i.needs_update=!0,s?.())},r.open("GET",t),r.send(),i}l(ps,"LoadMap");ge(ps,"LoadMap");function Si(t,e,s){return t.load(e,s??t.sprites),t}l(Si,"UpdateMap");ge(Si,"UpdateMap");function Nn(t){let e=1,s=[0],i={};for(let a=0;a<t.height;a++)for(let o=0;o<t.width;o++){let u=t.map[o+a*t.width];u&&u.length>0&&i[u]==null&&(s.push(u),i[u]=e++)}let r=[];for(let a=0;a<t.height;a++)for(let o=0;o<t.width;o++){let u=t.map[o+a*t.width];r[o+a*t.width]=u&&u.length>0?i[u]:0}let n={width:t.width,height:t.height,block_width:t.block_width,block_height:t.block_height,sprites:s,data:r};return JSON.stringify(n)}l(Nn,"SaveMap");ge(Nn,"SaveMap");var xi=Object.defineProperty,U=l((t,e)=>xi(t,"name",{value:e,configurable:!0}),"__name"),Ue=l((t,e)=>{for(var s in e)xi(t,s,{get:e[s],enumerable:!0})},"__export"),Li={normal:"source-over",additive:"lighter"},Dn=["source-over","source-in","source-out","source-atop","destination-over","destination-in","destination-out","destination-atop","lighter","copy","xor","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"];for(let t of Dn)Li[t]=t;var Fn={};Ue(Fn,{setColor:l(()=>ds,"setColor"),setLinearGradient:l(()=>ms,"setLinearGradient"),setRadialGradient:l(()=>gs,"setRadialGradient")});function ds(t,e){e!=null&&typeof e=="string"&&(t.fillStyle=e,t.strokeStyle=e)}l(ds,"setColor");U(ds,"setColor");function ms(t,e,s,i,r,n,a){let o=t.createLinearGradient(e,s,i,r);o.addColorStop(0,n),o.addColorStop(1,a),t.fillStyle=o,t.strokeStyle=o}l(ms,"setLinearGradient");U(ms,"setLinearGradient");function gs(t,e,s,i,r,n){let a=t.createRadialGradient(e,s,0,e,s,i);a.addColorStop(0,r),a.addColorStop(1,n),t.fillStyle=a,t.strokeStyle=a}l(gs,"setRadialGradient");U(gs,"setRadialGradient");function wi(t){return t?{alpha:1,pixelated:1,line_width:1,translation_x:0,translation_y:0,rotation:0,scale_x:1,scale_y:-1,image_transform:!0,anchor_x:0,anchor_y:0,object_rotation:0,object_scale_x:1,object_scale_y:-1,font:"BitCell"}:{alpha:1,pixelated:1,line_width:1,translation_x:0,translation_y:0,rotation:0,scale_x:1,scale_y:1,image_transform:!1,anchor_x:-1,anchor_y:1,object_rotation:0,object_scale_x:1,object_scale_y:1,font:"BitCell"}}l(wi,"createDefaultContextState");U(wi,"createDefaultContextState");function xt(t){t.image_transform=t.translation_x!==0||t.translation_y!==0||t.scale_x!==1||t.scale_y!==1||t.rotation!==0}l(xt,"updateImageTransform");U(xt,"updateImageTransform");var Un={};Ue(Un,{closeDrawOp:l(()=>ne,"closeDrawOp"),drawLine:l(()=>As,"drawLine"),drawRect:l(()=>bs,"drawRect"),drawRound:l(()=>vs,"drawRound"),drawRoundRect:l(()=>Ts,"drawRoundRect"),fillRect:l(()=>_s,"fillRect"),fillRound:l(()=>ys,"fillRound"),fillRoundRect:l(()=>Es,"fillRoundRect"),initDrawOp:l(()=>re,"initDrawOp")});function re(t,e,s,i,r=!0){let n=!1;return e.image_transform&&(t.save(),n=!0,t.translate(e.translation_x,e.translation_y),t.scale(e.scale_x,e.scale_y),t.rotate(e.rotation/180*Math.PI),t.translate(s,i)),r&&(e.object_rotation!==0||e.object_scale_x!==1||e.object_scale_y!==1)&&(n||(t.save(),n=!0,t.translate(s,i)),e.object_rotation!==0&&t.rotate(e.object_rotation/180*Math.PI),(e.object_scale_x!==1||e.object_scale_y!==1)&&t.scale(e.object_scale_x,e.object_scale_y)),n}l(re,"initDrawOp");U(re,"initDrawOp");function ne(t){t.restore()}l(ne,"closeDrawOp");U(ne,"closeDrawOp");function _s(t,e,s,i,r,n){t.globalAlpha=e.alpha,re(t,e,s,i)?(t.fillRect(-r/2-e.anchor_x*r/2,-n/2+e.anchor_y*n/2,r,n),ne(t)):t.fillRect(s-r/2-e.anchor_x*r/2,i-n/2+e.anchor_y*n/2,r,n)}l(_s,"fillRect");U(_s,"fillRect");function Es(t,e,s,i,r,n,a){t.globalAlpha=e.alpha,re(t,e,s,i)?(t.fillRoundRect(-r/2-e.anchor_x*r/2,-n/2+e.anchor_y*n/2,r,n,a),ne(t)):t.fillRoundRect(s-r/2-e.anchor_x*r/2,i-n/2+e.anchor_y*n/2,r,n,a)}l(Es,"fillRoundRect");U(Es,"fillRoundRect");function ys(t,e,s,i,r,n){t.globalAlpha=e.alpha,r=Math.abs(r),n=Math.abs(n),re(t,e,s,i)?(t.beginPath(),t.ellipse(-e.anchor_x*r/2,0+e.anchor_y*n/2,r/2,n/2,0,0,Math.PI*2,!1),t.fill(),ne(t)):(t.beginPath(),t.ellipse(s-e.anchor_x*r/2,i+e.anchor_y*n/2,r/2,n/2,0,0,Math.PI*2,!1),t.fill())}l(ys,"fillRound");U(ys,"fillRound");function bs(t,e,s,i,r,n){t.globalAlpha=e.alpha,t.lineWidth=e.line_width,re(t,e,s,i)?(t.strokeRect(-r/2-e.anchor_x*r/2,-n/2+e.anchor_y*n/2,r,n),ne(t)):t.strokeRect(s-r/2-e.anchor_x*r/2,i-n/2+e.anchor_y*n/2,r,n)}l(bs,"drawRect");U(bs,"drawRect");function Ts(t,e,s,i,r,n,a){t.globalAlpha=e.alpha,t.lineWidth=e.line_width,re(t,e,s,i)?(t.strokeRoundRect(-r/2-e.anchor_x*r/2,-n/2+e.anchor_y*n/2,r,n,a),ne(t)):t.strokeRoundRect(s-r/2-e.anchor_x*r/2,i-n/2+e.anchor_y*n/2,r,n,a)}l(Ts,"drawRoundRect");U(Ts,"drawRoundRect");function vs(t,e,s,i,r,n){t.globalAlpha=e.alpha,t.lineWidth=e.line_width,r=Math.abs(r),n=Math.abs(n),re(t,e,s,i)?(t.beginPath(),t.ellipse(0-e.anchor_x*r/2,0+e.anchor_y*n/2,r/2,n/2,0,0,Math.PI*2,!1),t.stroke(),ne(t)):(t.beginPath(),t.ellipse(s-e.anchor_x*r/2,i+e.anchor_y*n/2,r/2,n/2,0,0,Math.PI*2,!1),t.stroke())}l(vs,"drawRound");U(vs,"drawRound");function As(t,e,s,i,r,n){t.globalAlpha=e.alpha,t.lineWidth=e.line_width;let a=re(t,e,0,0,!1);t.beginPath(),t.moveTo(s,i),t.lineTo(r,n),t.stroke(),a&&ne(t)}l(As,"drawLine");U(As,"drawLine");var tt=new Set,Ze=new Map;function Ri(t){if(t){if(tt.has(t))return Promise.resolve();if(Ze.has(t))return Ze.get(t);if(typeof document<"u"&&"fonts"in document){let e=document.fonts.load(`12pt ${t}`).then(()=>{tt.add(t),Ze.delete(t)}).catch(()=>{tt.add(t),Ze.delete(t)});return Ze.set(t,e),e}return tt.add(t),Promise.resolve()}}l(Ri,"loadFont");U(Ri,"loadFont");function Ci(t){return!t||tt.has(t)?!0:typeof document<"u"&&"fonts"in document?document.fonts.check(`12pt ${t}`):!0}l(Ci,"isFontReady");U(Ci,"isFontReady");function Yn(){tt.clear(),Ze.clear()}l(Yn,"clearFontCache");U(Yn,"clearFontCache");var Bn={};Ue(Bn,{drawMap:l(()=>Ps,"drawMap")});var jn=U(t=>{let e=globalThis?.player?.runtime;if(!e)return null;let s=e.maps;if(s&&s[t])return s[t];let i=e.screen?.runtime?.maps;return i&&i[t]?i[t]:null},"resolveStringMap");function Ps(t,e,s,i,r,n,a){let o=typeof s=="string"?jn(s):s??null;!o||!o.ready||!o.draw||(t.globalAlpha=e.alpha,t.imageSmoothingEnabled=!e.pixelated,re(t,e,i,r)?(o.draw(t,-n/2-e.anchor_x*n/2,-a/2+e.anchor_y*a/2,n,a),ne(t)):o.draw(t,i-n/2-e.anchor_x*n/2,r-a/2+e.anchor_y*a/2,n,a))}l(Ps,"drawMap");U(Ps,"drawMap");var ie=null;function Ii(t,e,s,i,r,n){ie==null&&(ie=t.createImageData(1,1)),typeof i=="object"?(ie.data[0]=i.R,ie.data[1]=i.G,ie.data[2]=i.B):(ie.data[0]=i,ie.data[1]=r||0,ie.data[2]=n||0),ie.data[3]=255,t.putImageData(ie,e,s)}l(Ii,"setRGB");U(Ii,"setRGB");function Mi(t,e,s,i,r,n,a){ie==null&&(ie=t.createImageData(1,1)),typeof i=="object"?(ie.data[0]=i.R,ie.data[1]=i.G,ie.data[2]=i.B,ie.data[3]=i.A!=null?i.A:255):(ie.data[0]=i,ie.data[1]=r||0,ie.data[2]=n||0,ie.data[3]=a??255),t.putImageData(ie,e,s)}l(Mi,"setRGBA");U(Mi,"setRGBA");function Ni(t,e,s,i={R:0,G:0,B:0}){let r=t.getImageData(e,s,1,1);return i.R=r.data[0],i.G=r.data[1],i.B=r.data[2],i}l(Ni,"getRGB");U(Ni,"getRGB");function Di(t,e,s,i={R:0,G:0,B:0,A:255}){let r=t.getImageData(e,s,1,1);return i.R=r.data[0],i.G=r.data[1],i.B=r.data[2],i.A=r.data[3],i}l(Di,"getRGBA");U(Di,"getRGBA");var Vn={};Ue(Vn,{drawArc:l(()=>ws,"drawArc"),drawBezierCurve:l(()=>Ls,"drawBezierCurve"),drawPolygon:l(()=>ks,"drawPolygon"),drawPolyline:l(()=>Os,"drawPolyline"),drawQuadCurve:l(()=>xs,"drawQuadCurve"),fillArc:l(()=>Rs,"fillArc"),fillPolygon:l(()=>Ss,"fillPolygon")});function Os(t,e,s){if(Array.isArray(s[0])&&(s=s[0]),t.globalAlpha=e.alpha,t.lineWidth=e.line_width,s.length<4)return;let i=Math.floor(s.length/2),r=re(t,e,0,0,!1);t.beginPath(),t.moveTo(s[0],s[1]);for(let n=1;n<=i-1;n++)t.lineTo(s[n*2],s[n*2+1]);t.stroke(),r&&ne(t)}l(Os,"drawPolyline");U(Os,"drawPolyline");function ks(t,e,s){if(Array.isArray(s[0])&&(s=s[0]),t.globalAlpha=e.alpha,t.lineWidth=e.line_width,s.length<4)return;let i=Math.floor(s.length/2),r=re(t,e,0,0,!1);t.beginPath(),t.moveTo(s[0],s[1]);for(let n=1;n<=i-1;n++)t.lineTo(s[n*2],s[n*2+1]);t.closePath(),t.stroke(),r&&ne(t)}l(ks,"drawPolygon");U(ks,"drawPolygon");function Ss(t,e,s){if(Array.isArray(s[0])&&(s=s[0]),t.globalAlpha=e.alpha,s.length<4)return;let i=Math.floor(s.length/2),r=re(t,e,0,0,!1);t.beginPath(),t.moveTo(s[0],s[1]);for(let n=1;n<=i-1;n++)t.lineTo(s[n*2],s[n*2+1]);t.fill(),r&&ne(t)}l(Ss,"fillPolygon");U(Ss,"fillPolygon");function xs(t,e,s){if(Array.isArray(s[0])&&(s=s[0]),t.globalAlpha=e.alpha,t.lineWidth=e.line_width,s.length<4)return;let i=re(t,e,0,0,!1);t.beginPath(),t.moveTo(s[0],s[1]);let r=2;for(;r<=s.length-4;)t.quadraticCurveTo(s[r],s[r+1],s[r+2],s[r+3]),r+=4;t.stroke(),i&&ne(t)}l(xs,"drawQuadCurve");U(xs,"drawQuadCurve");function Ls(t,e,s){if(Array.isArray(s[0])&&(s=s[0]),t.globalAlpha=e.alpha,t.lineWidth=e.line_width,s.length<4)return;let i=re(t,e,0,0,!1);t.beginPath(),t.moveTo(s[0],s[1]);let r=2;for(;r<=s.length-6;)t.bezierCurveTo(s[r],s[r+1],s[r+2],s[r+3],s[r+4],s[r+5]),r+=6;t.stroke(),i&&ne(t)}l(Ls,"drawBezierCurve");U(Ls,"drawBezierCurve");function ws(t,e,s,i,r,n,a,o){t.globalAlpha=e.alpha,t.lineWidth=e.line_width,re(t,e,s,i)?(t.beginPath(),t.arc(0,0,r,n/180*Math.PI,a/180*Math.PI,o),t.stroke(),ne(t)):(t.beginPath(),t.arc(s,i,r,n/180*Math.PI,a/180*Math.PI,o),t.stroke())}l(ws,"drawArc");U(ws,"drawArc");function Rs(t,e,s,i,r,n,a,o){t.globalAlpha=e.alpha,re(t,e,s,i)?(t.beginPath(),t.arc(0,0,r,n/180*Math.PI,a/180*Math.PI,o),t.fill(),ne(t)):(t.beginPath(),t.arc(s,i,r,n/180*Math.PI,a/180*Math.PI,o),t.fill())}l(Rs,"fillArc");U(Rs,"fillArc");var $n={};Ue($n,{drawSprite:l(()=>Cs,"drawSprite"),drawSpritePart:l(()=>Is,"drawSpritePart"),getSpriteFrame:l(()=>Lt,"getSpriteFrame")});function Lt(t){if(typeof t=="object"&&"canvas"in t&&!("frames"in t))return t.canvas||t.image||null;if(typeof t=="object"&&t.frames&&t.frames.length>0){if(!t.ready)return null;if(t.frames.length>1){(!t.animation_start||t.animation_start===0)&&(t.animation_start=Date.now());let e=1e3/(t.fps||5),s=Math.floor((Date.now()-t.animation_start)/e)%t.frames.length;return s>=0&&s<t.frames.length?t.frames[s].canvas:t.frames[0].canvas}return t.frames[0].canvas}return null}l(Lt,"getSpriteFrame");U(Lt,"getSpriteFrame");function Cs(t,e,s,i,r,n,a){let o=Lt(s);o!=null&&(n==null&&(n=o.width),a||(a=n/o.width*o.height),t.globalAlpha=e.alpha,t.imageSmoothingEnabled=!e.pixelated,re(t,e,i,r)?(t.drawImage(o,-n/2-e.anchor_x*n/2,-a/2+e.anchor_y*a/2,n,a),ne(t)):t.drawImage(o,i-n/2-e.anchor_x*n/2,r-a/2+e.anchor_y*a/2,n,a))}l(Cs,"drawSprite");U(Cs,"drawSprite");function Is(t,e,s,i,r,n,a,o,u,g,y){let O=Lt(s);O!=null&&(g==null&&(g=O.width),y||(y=g/n*a),t.globalAlpha=e.alpha,t.imageSmoothingEnabled=!e.pixelated,re(t,e,o,u)?(t.drawImage(O,i,r,n,a,-g/2-e.anchor_x*g/2,-y/2+e.anchor_y*y/2,g,y),ne(t)):t.drawImage(O,i,r,n,a,o-g/2-e.anchor_x*g/2,u-y/2+e.anchor_y*y/2,g,y))}l(Is,"drawSpritePart");U(Is,"drawSpritePart");var Gn={};Ue(Gn,{drawText:l(()=>Ns,"drawText"),drawTextOutline:l(()=>Ds,"drawTextOutline"),textWidth:l(()=>Ms,"textWidth")});function Ms(t,e,s,i){return t.font=`${i}pt ${e.font}`,t.measureText(s).width}l(Ms,"textWidth");U(Ms,"textWidth");function Ns(t,e,s,i,r,n){t.globalAlpha=e.alpha,t.font=`${n}pt ${e.font}`,t.textAlign="center",t.textBaseline="middle";let a=t.measureText(s).width,o=n;re(t,e,i,r)?(t.fillText(s,0-e.anchor_x*a/2,0+e.anchor_y*o/2),ne(t)):t.fillText(s,i-e.anchor_x*a/2,r+e.anchor_y*o/2)}l(Ns,"drawText");U(Ns,"drawText");function Ds(t,e,s,i,r,n){t.globalAlpha=e.alpha,t.font=`${n}pt ${e.font}`,t.lineWidth=e.line_width,t.textAlign="center",t.textBaseline="middle";let a=t.measureText(s).width,o=n;re(t,e,i,r)?(t.strokeText(s,0-e.anchor_x*a/2,0+e.anchor_y*o/2),ne(t)):t.strokeText(s,i-e.anchor_x*a/2,r+e.anchor_y*o/2)}l(Ds,"drawTextOutline");U(Ds,"drawTextOutline");var zn={};Ue(zn,{setDrawAnchor:l(()=>Bs,"setDrawAnchor"),setDrawRotation:l(()=>js,"setDrawRotation"),setDrawScale:l(()=>Vs,"setDrawScale"),setRotation:l(()=>Ys,"setRotation"),setScale:l(()=>Us,"setScale"),setTranslation:l(()=>Fs,"setTranslation")});function Fs(t,e,s){t.translation_x=e,t.translation_y=s,isFinite(t.translation_x)||(t.translation_x=0),isFinite(t.translation_y)||(t.translation_y=0),xt(t)}l(Fs,"setTranslation");U(Fs,"setTranslation");function Us(t,e,s){t.scale_x=e,t.scale_y=s,(!isFinite(t.scale_x)||t.scale_x===0)&&(t.scale_x=1),(!isFinite(t.scale_y)||t.scale_y===0)&&(t.scale_y=1),xt(t)}l(Us,"setScale");U(Us,"setScale");function Ys(t,e){t.rotation=e,isFinite(t.rotation)||(t.rotation=0),xt(t)}l(Ys,"setRotation");U(Ys,"setRotation");function Bs(t,e,s){t.anchor_x=e,t.anchor_y=s,typeof t.anchor_x!="number"&&(t.anchor_x=0),typeof t.anchor_y!="number"&&(t.anchor_y=0)}l(Bs,"setDrawAnchor");U(Bs,"setDrawAnchor");function js(t,e){t.object_rotation=e}l(js,"setDrawRotation");U(js,"setDrawRotation");function Vs(t,e,s){t.object_scale_x=e,t.object_scale_y=s}l(Vs,"setDrawScale");U(Vs,"setDrawScale");function et(t){return t.length>0&&t.length%2===1&&typeof t[t.length-1]=="string"?{points:t.slice(0,-1),color:t[t.length-1]}:{points:t,color:void 0}}l(et,"splitColorArg");U(et,"splitColorArg");var Se=class{static{l(this,"Image")}static{U(this,"Image")}_canvas;_context=null;_image=null;_state;_centered;width;height;constructor(t,e,s=!1){this._centered=s,typeof t=="object"&&"naturalWidth"in t?(this._image=t,this.width=this._image.width,this.height=this._image.height):typeof t=="object"&&"getContext"in t?(this._canvas=t,this.width=this._canvas.width,this.height=this._canvas.height):(this._canvas=document.createElement("canvas"),this.width=Math.round(t),this.height=Math.round(e||t),this._canvas.width=this.width,this._canvas.height=this.height)}initContext(){return this._context?this._context:(!this._canvas&&this._image&&(this._canvas=document.createElement("canvas"),this._canvas.width=this._image.width,this._canvas.height=this._image.height,this._context=this._canvas.getContext("2d"),this._context.drawImage(this._image,0,0),this._image=null),this._context=this._canvas.getContext("2d"),this._context&&(this._context.lineCap="round"),this._state||(this._state=wi(this._centered),this._centered&&(this._state.translation_x=this.width/2,this._state.translation_y=this.height/2)),this._context)}get canvas(){return this.initContext(),this._canvas}get image(){return this._image}get context(){return this._context}setRGB(t,e,s,i,r){this.initContext(),Ii(this._context,t,e,s,i,r)}setRGBA(t,e,s,i,r,n){this.initContext(),Mi(this._context,t,e,s,i,r,n)}getRGB(t,e,s){return this.initContext(),Ni(this._context,t,e,s)}getRGBA(t,e,s){return this.initContext(),Di(this._context,t,e,s)}clear(t){this.initContext();let e=this._context.fillStyle,s=this._context.strokeStyle,i=this._context.globalCompositeOperation;this._context.globalAlpha=1,this._context.globalCompositeOperation="source-over",t!=null?this.setColor(t):this._context.fillStyle="#000",this._context.fillRect(0,0,this.width,this.height),this._context.fillStyle=e,this._context.strokeStyle=s,this._context.globalCompositeOperation=i}setColor(t){this.initContext(),ds(this._context,t)}setAlpha(t){this.initContext(),this._state.alpha=t}setPixelated(t){this.initContext(),this._state.pixelated=t}setBlending(t){this.initContext();let e=Li[t||"normal"]||"source-over";this._context.globalCompositeOperation=e}setLineWidth(t){this.initContext(),this._state.line_width=t}setLineDash(t){this.initContext(),Array.isArray(t)?this._context.setLineDash(t):this._context.setLineDash([])}setLinearGradient(t,e,s,i,r,n){this.initContext(),ms(this._context,t,e,s,i,r,n)}setRadialGradient(t,e,s,i,r){this.initContext(),gs(this._context,t,e,s,i,r)}setFont(t){this.initContext(),this._state.font=t||"Verdana",this.loadFont(this._state.font)}loadFont(t){return Ri(t)}isFontReady(t){return Ci(t||this._state?.font||"Verdana")}setTranslation(t,e){this.initContext(),Fs(this._state,t,e)}setScale(t,e){this.initContext(),Us(this._state,t,e)}setRotation(t){this.initContext(),Ys(this._state,t)}setDrawAnchor(t,e){this.initContext(),Bs(this._state,t,e)}setDrawRotation(t){this.initContext(),js(this._state,t)}setDrawScale(t,e=t){this.initContext(),Vs(this._state,t,e)}fillRect(t,e,s,i,r){this.initContext(),this.setColor(r),_s(this._context,this._state,t,e,s,i)}fillRoundRect(t,e,s,i,r=10,n){this.initContext(),this.setColor(n),Es(this._context,this._state,t,e,s,i,r)}fillRound(t,e,s,i,r){this.initContext(),this.setColor(r),ys(this._context,this._state,t,e,s,i)}drawRect(t,e,s,i,r){this.initContext(),this.setColor(r),bs(this._context,this._state,t,e,s,i)}drawRoundRect(t,e,s,i,r=10,n){this.initContext(),this.setColor(n),Ts(this._context,this._state,t,e,s,i,r)}drawRound(t,e,s,i,r){this.initContext(),this.setColor(r),vs(this._context,this._state,t,e,s,i)}drawLine(t,e,s,i,r){this.initContext(),this.setColor(r),As(this._context,this._state,t,e,s,i)}drawPolyline(...t){this.initContext();let{points:e,color:s}=et(t);this.setColor(s),Os(this._context,this._state,e)}drawPolygon(...t){this.initContext();let{points:e,color:s}=et(t);this.setColor(s),ks(this._context,this._state,e)}fillPolygon(...t){this.initContext();let{points:e,color:s}=et(t);this.setColor(s),Ss(this._context,this._state,e)}drawQuadCurve(...t){this.initContext();let{points:e,color:s}=et(t);this.setColor(s),xs(this._context,this._state,e)}drawBezierCurve(...t){this.initContext();let{points:e,color:s}=et(t);this.setColor(s),Ls(this._context,this._state,e)}drawArc(t,e,s,i,r,n,a){this.initContext(),this.setColor(a),ws(this._context,this._state,t,e,s,i,r,n)}fillArc(t,e,s,i,r,n,a){this.initContext(),this.setColor(a),Rs(this._context,this._state,t,e,s,i,r,n)}textWidth(t,e){return this.initContext(),Ms(this._context,this._state,t,e)}drawText(t,e,s,i,r){this.initContext(),this.setColor(r),Ns(this._context,this._state,t,e,s,i)}drawTextOutline(t,e,s,i,r){this.initContext(),this.setColor(r),Ds(this._context,this._state,t,e,s,i)}drawSprite(t,e,s,i,r){this.initContext(),Cs(this._context,this._state,t,e,s,i,r)}drawImage(t,e,s,i,r){this.drawSprite(t,e,s,i,r)}drawSpritePart(t,e,s,i,r,n,a,o,u){this.initContext(),Is(this._context,this._state,t,e,s,i,r,n,a,o,u)}drawImagePart(t,e,s,i,r,n,a,o,u){this.drawSpritePart(t,e,s,i,r,n,a,o,u)}drawMap(t,e,s,i,r){this.initContext(),Ps(this._context,this._state,t,e,s,i,r)}};var Wn=Object.defineProperty,wt=l((t,e)=>Wn(t,"name",{value:e,configurable:!0}),"__name"),st=class{static{l(this,"Sprite")}static{wt(this,"Sprite")}name="";frames=[];animation_start=0;fps=5;ready=0;width;height;constructor(t,e){this.width=t,this.height=e,this.frames=[],this.animation_start=0,this.fps=5,this.width>0&&this.height>0&&(this.frames.push(new Se(this.width,this.height)),this.ready=1)}setFPS(t){let e=1e3/this.fps,s=(Date.now()-this.animation_start)/e%this.frames.length;this.fps=t;let i=1e3/t;return this.animation_start=Date.now()-s*i,t}setFrame(t){this.animation_start=Date.now()-1e3/this.fps*t}getFrame(){let t=1e3/this.fps;return Math.floor((Date.now()-this.animation_start)/t)%this.frames.length}getCurrentFrameCanvas(){if(!this.ready||this.frames.length===0)return null;if(this.frames.length>1){this.animation_start===0&&(this.animation_start=Date.now());let t=this.getFrame();return t>=0&&t<this.frames.length?this.frames[t].canvas:this.frames[0].canvas}return this.frames[0].canvas}};function $s(t,e,s){if(t>0&&e%t===0){let i=e/t;return Math.min(s,i)}return s}l($s,"resolveFrameCount");wt($s,"resolveFrameCount");function Gs(t,e,s){let i=new st(0,0);i.ready=0;let r=new window.Image;return location.protocol!=="file:"&&(r.crossOrigin="Anonymous"),r.src=t,r.onload=()=>{if(i.ready=1,r.width>0&&r.height>0){e?.fps&&(i.fps=e.fps),i.width=r.width;let n=$s(r.width,r.height,e?.frames??1);i.height=Math.round(r.height/n),i.frames=[];for(let a=0;a<n;a++){let o=new Se(i.width,i.height);o.initContext();let u=o.context;u.setTransform(1,0,0,1,0,0),u.drawImage(r,0,-a*i.height),i.frames.push(o)}i.ready=1}s&&s()},r.onerror=()=>{i.ready=1},i}l(Gs,"LoadSprite");wt(Gs,"LoadSprite");function qn(t,e,s){if(e.width>0&&e.height>0){s?.fps&&(t.fps=s.fps),t.width=e.width;let i=$s(e.width,e.height,s?.frames??1);t.height=Math.round(e.height/i),t.frames=[];for(let r=0;r<i;r++){let n=new Se(t.width,t.height);n.initContext();let a=n.context;a.setTransform(1,0,0,1,0,0),a.drawImage(e,0,-r*t.height),t.frames.push(n)}t.ready=1}}l(qn,"UpdateSprite");wt(qn,"UpdateSprite");var Fi=16.666666666666668,Ui=160,zs=16,Rt=16,Yi=3e4;function Hn(t,e){return Promise.race([t,new Promise((s,i)=>setTimeout(()=>i(new Error(`Asset load timed out after ${e}ms`)),e))])}l(Hn,"withTimeout");var it=class{static{l(this,"AssetLoader")}url;resources;collections;loadingBarTime=null;audioCore;listener;constructor(e,s,i,r){this.url=e,this.resources=s,this.audioCore=i,this.listener=r,this.collections={sprites:{},maps:{},sounds:{},music:{},assets:{}}}async loadAll(){return await Promise.all([this.loadSprites(),this.loadMaps(),this.loadSounds(),this.loadMusic(),this.loadGenericAssets()]),this.collections}async loadCallbackAssets(e,s,i,r,n){if(!e)return;let a=e.map(o=>new Promise(u=>{let g=o.file.split(".")[0].replace(/-/g,"/"),y=`${this.url}${s}/${o.file}?v=${o.version||0}`;try{let O=new Promise(b=>{this.collections[i][g]=r(y,o,b)});Hn(O,Yi).then(u).catch(b=>{this.listener?.log?.(`[AssetLoader] Failed to load ${i.slice(0,-1)} "${g}": ${String(b)}`),this.collections[i][g]=n(g,o),u()})}catch(O){this.listener?.log?.(`[AssetLoader] Failed to load ${i.slice(0,-1)} "${g}": ${String(O)}`),this.collections[i][g]=n(g,o),u()}}));await Promise.all(a)}async loadSprites(){await this.loadCallbackAssets(this.resources.images,"sprites","sprites",(e,s,i)=>Gs(e,s.properties,i),(e,s)=>({name:e,ready:!1,frames:[],fps:s.properties?.fps||5,width:0,height:0}))}async loadMaps(){await this.loadCallbackAssets(this.resources.maps,"maps","maps",(e,s,i)=>ps(e,this.collections.sprites,i),e=>({name:e,ready:!1,width:0,height:0,block_width:zs,block_height:zs,data:[]}))}async loadSounds(){if(!this.resources.sounds)return;let e=this.resources.sounds.map(s=>new Promise(i=>{let r=s.file.split(".")[0],n=`${this.url}sounds/${s.file}?v=${s.version||0}`;try{let a=new Me(this.audioCore,n);this.collections.sounds[r]=a,i()}catch(a){this.listener?.log?.(`[AssetLoader] Failed to load sound "${r}": ${String(a)}`),this.collections.sounds[r]=new Me(this.audioCore,n),i()}}));await Promise.all(e)}async loadMusic(){if(!this.resources.music)return;let e=this.resources.music.map(s=>new Promise(i=>{let r=s.file.split(".")[0],n=`${this.url}music/${s.file}?v=${s.version||0}`;try{let a=new us(this.audioCore,n);this.collections.music[r]=a,i()}catch(a){this.listener?.log?.(`[AssetLoader] Failed to load music "${r}": ${String(a)}`),this.collections.music[r]=new us(this.audioCore,n),i()}}));await Promise.all(e)}async loadGenericAssets(){if(this.resources.assets)for(let e of this.resources.assets){let s=e.file.split(".")[0].replace(/-/g,"/");this.collections.assets[s]={name:s,file:e.file,version:e.version}}}isReady(){return this.countReady()===this.countTotal()}getProgress(){let e=this.countTotal();return e===0?1:this.countReady()/e}countTotal(){let e=0;return e+=Object.keys(this.collections.sprites).length,e+=Object.keys(this.collections.maps).length,e+=Object.keys(this.collections.sounds).length,e+=Object.keys(this.collections.music).length,e}countReady(){let e=0;for(let s of Object.values(this.collections.sprites))s.ready&&e++;for(let s of Object.values(this.collections.maps))s.ready&&e++;for(let s of Object.values(this.collections.sounds))s.ready&&e++;for(let s of Object.values(this.collections.music))s.ready&&e++;return e}showLoadingBar(e){if(this.loadingBarTime&&Date.now()<this.loadingBarTime+Rt)return;this.loadingBarTime=Date.now();let s=this.getProgress();e.clear("#000"),e.drawRect(0,0,100,10,"#DDD"),e.fillRect(-(1-s)*48,0,s*96,6,"#DDD")}getCollections(){return this.collections}};var Kn=Object.defineProperty,Ne=l((t,e)=>Kn(t,"name",{value:e,configurable:!0}),"__name"),Bi=class{static{l(this,"PlayerService")}static{Ne(this,"PlayerService")}delegate;interfaceCache=null;constructor(t){this.delegate=t}getInterface(){if(this.interfaceCache)return this.interfaceCache;let t={pause:Ne(()=>this.delegate.pause(),"pause"),resume:Ne(()=>this.delegate.resume(),"resume"),postMessage:Ne(e=>this.delegate.postMessage(e),"postMessage"),setFps:Ne(e=>{typeof e=="number"&&isFinite(e)&&e>0&&this.delegate.setUpdateRate(e)},"setFps")};return Object.defineProperty(t,"fps",{get:Ne(()=>this.delegate.getFps(),"get"),enumerable:!0}),Object.defineProperty(t,"update_rate",{get:Ne(()=>this.delegate.getUpdateRate(),"get"),set:Ne(e=>{typeof e=="number"&&isFinite(e)&&e>0&&this.delegate.setUpdateRate(e)},"set"),enumerable:!0}),this.interfaceCache=t,this.interfaceCache}};var Jn=Object.defineProperty,Q=l((t,e)=>Jn(t,"name",{value:e,configurable:!0}),"__name"),ji="/",Qn=/:(\w+)/g,Xn="([^/]+)";function ut(){return typeof window<"u"}l(ut,"isBrowser");Q(ut,"isBrowser");function Ye(t,e,s){try{return t()}catch(i){e(i,s);return}}l(Ye,"safeExecute");Q(Ye,"safeExecute");function ft(t){return typeof t=="string"&&t.length>0}l(ft,"isValidString");Q(ft,"isValidString");function Vi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}l(Vi,"isValidObject");Q(Vi,"isValidObject");function Ct(t){let e=t.split("?")[0].split("#")[0];return e.startsWith("/")?e:`/${e}`}l(Ct,"normalizeScenePath");Q(Ct,"normalizeScenePath");var Zn=class{static{l(this,"RouteManager")}static{Q(this,"RouteManager")}routes=[];register(t,e){if(!this.validateRouteInputs(t,e))return;let{regex:s,keys:i}=this.parsePath(t);this.routes.push({path:t,sceneName:e,regex:s,keys:i})}validateRouteInputs(t,e){return!(!ft(t)||!ft(e))}match(t){if(!ft(t))return null;for(let e of this.routes){let s=this.tryMatchRoute(e,t);if(s)return s}return null}tryMatchRoute(t,e){let s=t.regex.exec(e);if(!s)return null;let i=this.extractParams(t.keys,s);return{sceneName:t.sceneName,params:i}}extractParams(t,e){let s={};return t.forEach((i,r)=>{s[i]=e[r+1]}),s}parsePath(t){let e=[],s=t.replace(Qn,(i,r)=>(e.push(r),Xn)).replace(/\//g,"\\/");return{regex:new RegExp(`^${s}$`),keys:e}}clear(){this.routes=[]}},ea=class{static{l(this,"Router")}static{Q(this,"Router")}routeManager;sceneManager;state={path:ji,params:{},sceneName:null};constructor(t,e){this.routeManager=t,this.sceneManager=e,this.setupPopStateListener()}setupPopStateListener(){ut()&&window.addEventListener("popstate",()=>{this.handlePathChange(window.location.pathname)})}push(t){if(!this.validatePath(t))return;let e=Ct(t);e!==this.state.path&&(this.updateBrowserHistory(e,"push"),this.handlePathChange(e))}replace(t){if(!this.validatePath(t))return;let e=Ct(t);this.updateBrowserHistory(e,"replace"),this.handlePathChange(e)}back(){ut()&&window.history.back()}getState(){return{...this.state}}validatePath(t){return!(!t||typeof t!="string")}updateBrowserHistory(t,e){ut()&&(e==="push"?window.history.pushState({},"",t):window.history.replaceState({},"",t))}handlePathChange(t){let e=Ct(t),s=this.routeManager.match(e);if(s){this.updateStateWithMatch(e,s);return}this.handleNoRouteMatch(e)}updateStateWithMatch(t,e){this.state={path:t,params:e.params,sceneName:e.sceneName},this.sceneManager.setActiveScene(e.sceneName,e.params)}handleNoRouteMatch(t){this.sceneManager.hasActiveScene()||this.activateFirstAvailableScene(t)}activateFirstAvailableScene(t){let e=this.sceneManager.registry.getNames();if(e.length===0)return;let s=e[0];this.state={path:t,params:{},sceneName:s},this.sceneManager.setActiveScene(s,{})}init(){let t=ut()?window.location.pathname:ji;this.handlePathChange(t),this.ensureActiveScene()}ensureActiveScene(){if(this.sceneManager.hasActiveScene())return;let t=this.sceneManager.registry.getNames();if(t.length===0)return;let e=t[0];this.state={path:this.state.path,params:{},sceneName:e},this.sceneManager.setActiveScene(e,{})}getInterface(){let t={push:Q(e=>this.push(e),"push"),replace:Q(e=>this.replace(e),"replace"),back:Q(()=>this.back(),"back"),getPath:Q(()=>this.state.path,"getPath"),getParams:Q(()=>this.state.params,"getParams"),getSceneName:Q(()=>this.state.sceneName,"getSceneName")};return Object.defineProperty(t,"path",{get:Q(()=>this.state.path,"get"),enumerable:!0,configurable:!0}),Object.defineProperty(t,"params",{get:Q(()=>this.state.params,"get"),enumerable:!0,configurable:!0}),Object.defineProperty(t,"sceneName",{get:Q(()=>this.state.sceneName,"get"),enumerable:!0,configurable:!0}),t}},ta=class{static{l(this,"SceneRegistry")}static{Q(this,"SceneRegistry")}scenes=new Map;register(t,e){this.scenes.set(t,e)}get(t){return this.scenes.get(t)}has(t){return this.scenes.has(t)}getNames(){return Array.from(this.scenes.keys())}clear(){this.scenes.clear()}},sa=class extends Error{static{l(this,"SceneError")}static{Q(this,"SceneError")}context;constructor(t,e){super(t),this.context=e,this.name="SceneError",Error.captureStackTrace?.(this,this.constructor)}},ia=class extends sa{static{l(this,"SceneNotFoundError")}static{Q(this,"SceneNotFoundError")}constructor(t,e=[]){super(`Scene not found: ${t}`,{sceneName:t,availableScenes:e}),this.name="SceneNotFoundError"}},$i=class{static{l(this,"SceneManager")}static{Q(this,"SceneManager")}registry;routeManager;router;activeSceneName=null;activeScene=null;onError;constructor(t){this.registry=new ta,this.routeManager=new Zn,this.onError=t,this.router=new ea(this.routeManager,this)}registerScene(t,e){this.validateSceneRegistration(t,e)&&this.registry.register(t,e)}validateSceneRegistration(t,e){return!(!ft(t)||!Vi(e))}registerRoute(t,e){this.routeManager.register(t,e)}setActiveScene(t,e={}){let s=this.registry.get(t);if(!s){this.handleSceneNotFound(t);return}if(this.isSameScene(t,s)){this.handleSameSceneActivation(s,t,e);return}this.transitionToScene(t,s,e)}handleSceneNotFound(t){let e=this.registry.getNames(),s=new ia(t,e);this.onError?this.onError(s):console.error(s.message)}isSameScene(t,e){return this.activeSceneName===t&&this.activeScene===e}handleSameSceneActivation(t,e,s){t.onEnter&&Ye(()=>t.onEnter?.(s),i=>{this.onError?this.onError(i):console.error("Scene onEnter error:",i)})}transitionToScene(t,e,s){this.leaveCurrentScene(),this.activateNewScene(t,e,s)}leaveCurrentScene(){this.activeScene?.onLeave&&Ye(()=>this.activeScene?.onLeave?.(),t=>{this.onError?this.onError(t):console.error("Scene onLeave error:",t)})}activateNewScene(t,e,s){this.activeSceneName=t,this.activeScene=e,this.initializeSceneIfNeeded(t,e),this.enterScene(t,e,s)}initializeSceneIfNeeded(t,e){!e.init||e._initialized||Ye(()=>{e.init?.(),e._initialized=!0},s=>{this.onError?this.onError(s):console.error("Scene init error:",s)})}enterScene(t,e,s){e.onEnter&&Ye(()=>e.onEnter?.(s),i=>{this.onError?this.onError(i):console.error("Scene onEnter error:",i)})}update(){this.activeScene?.update&&Ye(()=>this.activeScene?.update?.(),t=>{this.onError?this.onError(t):console.error("Scene update error:",t)})}draw(){this.activeScene&&this.activeScene.draw&&Ye(()=>this.activeScene?.draw?.(),t=>{this.onError?this.onError(t):console.error("Scene draw error:",t)})}hasActiveScene(){return this.activeScene!==null}getCurrentSceneName(){return this.activeSceneName}getCurrentScene(){return this.activeScene}interfaceCache=null;getInterface(){return this.interfaceCache?this.interfaceCache:(this.interfaceCache={register:Q((t,e)=>this.registerScene(t,e),"register"),route:Q((t,e)=>this.registerRoute(t,e),"route"),goto:Q((t,e)=>this.setActiveScene(t,e),"goto"),current:Q(()=>this.activeSceneName,"current")},this.interfaceCache)}};var ra=Object.defineProperty,I=l((t,e)=>ra(t,"name",{value:e,configurable:!0}),"__name"),na=class{static{l(this,"ZBuffer")}static{I(this,"ZBuffer")}buffer;width;height;constructor(t,e){this.width=t,this.height=e,this.buffer=new Float32Array(t*e)}clear(){this.buffer.fill(0)}get(t,e){return this.buffer[e*this.width+t]||0}set(t,e,s){this.buffer[e*this.width+t]=s}resize(t,e){(this.width!==t||this.height!==e)&&(this.width=t,this.height=e,this.buffer=new Float32Array(t*e))}};function pt(t,e,s){return(e.x-t.x)*(s.y-t.y)-(e.y-t.y)*(s.x-t.x)}l(pt,"edgeFn");I(pt,"edgeFn");function Gi(t,e,s,i){let r=null;if(t&&typeof t=="object"&&t.canvas)r=t.canvas;else if(typeof t=="string"&&i?.sprites){let b=i.sprites[t];b?.frames?.[0]?.canvas&&(r=b.frames[0].canvas)}if(!r)return null;let n=r.width,a=r.height,o=Math.floor(e)%n,u=Math.floor(s)%a,g=o<0?o+n:o,y=u<0?u+a:u,O=r.getContext("2d");if(!O)return null;try{let b=O.getImageData(g,y,1,1);return{r:b.data[0],g:b.data[1],b:b.data[2],a:b.data[3]}}catch{return null}}l(Gi,"getSpritePixel");I(Gi,"getSpritePixel");function zi(t,e,s,i){let r=null;if(t&&typeof t=="object"&&t.getCanvas?r=t:typeof t=="string"&&i?.maps&&(r=i.maps[t]),!r)return null;let n=r.getCanvas?r.getCanvas():r.canvas;if(!n)return null;let a=n.width,o=n.height,u=Math.floor(e)%a,g=Math.floor(s)%o,y=u<0?u+a:u,O=g<0?g+o:g,b=n.getContext("2d");if(!b)return null;try{let A=b.getImageData(y,O,1,1);return{r:A.data[0],g:A.data[1],b:A.data[2],a:A.data[3]}}catch{return null}}l(zi,"getMapPixel");I(zi,"getMapPixel");function Wi(t,e,s,i,r,n="tiles",a,o=!1){let{context:u,width:g,height:y,runtime:O,pixelated:b}=t,A=Math.max(0,Math.floor(Math.min(e.x,s.x,i.x))),m=Math.max(0,Math.floor(Math.min(e.y,s.y,i.y))),j=Math.min(g,Math.ceil(Math.max(e.x,s.x,i.x))),J=Math.min(y,Math.ceil(Math.max(e.y,s.y,i.y)));if(A>=j||m>=J)return;let D=pt(e,s,i);if(Math.abs(D)<.001||D<0)return;let C=o&&e.z>0&&s.z>0&&i.z>0,X=1,q=1,V=1,Ee=e.u,Re=s.u,he=i.u,Z=e.v,$e=s.v,Ge=i.v;C&&(X=1/e.z,q=1/s.z,V=1/i.z,Ee*=X,Re*=q,he*=V,Z*=X,$e*=q,Ge*=V);let ze=u.getImageData(A,m,j-A,J-m),Pe=ze.data;for(let Oe=m;Oe<J;Oe++)for(let ee=A;ee<j;ee++){let De={x:ee+.5,y:Oe+.5},$=pt(s,i,De),Y=pt(i,e,De),de=pt(e,s,De);if($>=0&&Y>=0&&de>=0){let ue=$/D,le=Y/D,ye=de/D;if(C&&a){let F=ue*e.z+le*s.z+ye*i.z,me=a.get(ee,Oe);if(me>0&&me>=F)continue;a.set(ee,Oe,F)}let M,ke;if(C){let F=ue*X+le*q+ye*V;M=(ue*Ee+le*Re+ye*he)/F,ke=(ue*Z+le*$e+ye*Ge)/F}else M=ue*e.u+le*s.u+ye*i.u,ke=ue*e.v+le*s.v+ye*i.v;let S=null;if(n==="map"?S=zi(r,M,ke,O):S=Gi(r,M,ke,O),S&&S.a>0){let F=((Oe-m)*(j-A)+(ee-A))*4;Pe[F]=S.r,Pe[F+1]=S.g,Pe[F+2]=S.b,Pe[F+3]=S.a}}}u.imageSmoothingEnabled=!b,u.putImageData(ze,A,m)}l(Wi,"drawTexturedTriangle");I(Wi,"drawTexturedTriangle");function qi(t,e,s,i,r){t.fillStyle=r,t.beginPath(),t.moveTo(e.x,e.y),t.lineTo(s.x,s.y),t.lineTo(i.x,i.y),t.closePath(),t.fill()}l(qi,"drawTriangle");I(qi,"drawTriangle");function Hi(t,e,s,i,r,n=1){t.strokeStyle=r,t.lineWidth=n,t.beginPath(),t.moveTo(e.x,e.y),t.lineTo(s.x,s.y),t.lineTo(i.x,i.y),t.closePath(),t.stroke()}l(Hi,"drawTriangleOutline");I(Hi,"drawTriangleOutline");var aa=class{static{l(this,"BaseScreen")}static{I(this,"BaseScreen")}canvas;context;runtime;width;height;alpha=1;pixelated=1;line_width=1;font="BitCell";translation_x=0;translation_y=0;rotation=0;scale_x=1;scale_y=1;screen_transform=!1;object_rotation=0;object_scale_x=1;object_scale_y=1;anchor_x=0;anchor_y=0;blending={};font_load_requested={};font_loaded={};interfaceCache=null;cursor="default";cursor_visibility="auto";last_mouse_move=Date.now();zBuffer;constructor(t={}){this.runtime=t.runtime,t.canvas?(this.canvas=t.canvas,(this.canvas.width===0||this.canvas.height===0)&&(this.canvas.width=t.width||1080,this.canvas.height=t.height||1920)):(this.canvas=document.createElement("canvas"),this.canvas.width=t.width||1080,this.canvas.height=t.height||1920),this.initContext(),this.blending={normal:"source-over",additive:"lighter"};let e=["source-over","source-in","source-out","source-atop","destination-over","destination-in","destination-out","destination-atop","lighter","copy","xor","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"];for(let s of e)this.blending[s]=s;this.loadFont(this.font),this.zBuffer=new na(this.canvas.width,this.canvas.height),this.cursor="default",this.canvas.addEventListener("mousemove",()=>{this.last_mouse_move=Date.now(),this.cursor!=="default"&&this.cursor_visibility==="auto"&&(this.cursor="default",this.canvas.style.cursor="default")}),this.canvas.addEventListener("contextrestored",()=>{this.initContext()}),setInterval(()=>this.checkMouseCursor(),1e3),this.cursor_visibility="auto"}initContext(){let t=this.canvas.getContext("2d",{alpha:!1});if(!t){let s=ve(_.E7001),i=Te(s);throw N(this.runtime?.listener,_.E7001,{}),new Error(i)}t!==this.context?this.context=t:this.context.restore(),this.context.save(),this.context.translate(this.canvas.width/2,this.canvas.height/2);let e=Math.min(this.canvas.width/200,this.canvas.height/200);this.context.scale(e,e),this.width=this.canvas.width/e,this.height=this.canvas.height/e,this.context.lineCap="round"}initDraw(){this.alpha=1,this.line_width=1}updateInterface(){this.interfaceCache&&(this.interfaceCache.width=this.width,this.interfaceCache.height=this.height)}clear(t){this.context.globalAlpha=1,this.context.globalCompositeOperation="source-over",this.context.fillStyle=t||"#000",this.context.strokeStyle=t||"#000",this.context.fillRect(-this.width/2,-this.height/2,this.width,this.height),this.zBuffer.clear()}setColor(t){if(t)if(Number.isNaN(Number.parseInt(String(t)))){if(typeof t=="string"){if(!(/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(t)||/^rgb\(|^rgba\(|^hsl\(|^hsla\(/.test(t)||/^(red|green|blue|yellow|cyan|magenta|black|white|gray|grey|orange|pink|purple|brown|transparent)$/i.test(t))){N(this.runtime?.listener,_.E7003,{color:t});return}this.context.fillStyle=t,this.context.strokeStyle=t}}else{let e=Number.parseInt(String(t)),s=Math.floor(e/100)%10/9*255,i=Math.floor(e/10)%10/9*255,r=e%10/9*255,a="#"+(4278190080+(s<<16)+(i<<8)+r).toString(16).substring(2,8);this.context.fillStyle=a,this.context.strokeStyle=a}}setAlpha(t){this.alpha=t}setPixelated(t){this.pixelated=t}setBlending(t){let e=this.blending[t||"normal"];if(!e){N(this.runtime?.listener,_.E7007,{blendMode:t}),this.context.globalCompositeOperation="source-over";return}this.context.globalCompositeOperation=e}setLineWidth(t){this.line_width=t}setLineDash(t){Array.isArray(t)?this.context.setLineDash(t):this.context.setLineDash([])}setLinearGradient(t,e,s,i,r,n){let a=this.context.createLinearGradient(t,-e,s,-i);a.addColorStop(0,r),a.addColorStop(1,n),this.context.fillStyle=a,this.context.strokeStyle=a}setRadialGradient(t,e,s,i,r){let n=this.context.createRadialGradient(t,-e,0,t,-e,s);n.addColorStop(0,i),n.addColorStop(1,r),this.context.fillStyle=n,this.context.strokeStyle=n}setFont(t){this.font=t||"Verdana",this.loadFont(this.font)}loadFont(t="BitCell"){if(!this.font_load_requested[t]){this.font_load_requested[t]=!0;try{document.fonts?.load?.(`16pt ${t}`).catch(()=>{N(this.runtime?.listener,_.E7006,{font:t})})}catch{N(this.runtime?.listener,_.E7006,{font:t})}}}isFontReady(t=this.font){if(this.font_loaded[t])return 1;try{let e=document.fonts?.check?.(`16pt ${t}`)??!0;return e&&(this.font_loaded[t]=!0),e?1:0}catch{return 1}}setTranslation(t,e){this.translation_x=isFinite(t)?t:0,this.translation_y=isFinite(e)?e:0,this.updateScreenTransform()}setScale(t,e){this.scale_x=isFinite(t)&&t!==0?t:1,this.scale_y=isFinite(e)&&e!==0?e:1,this.updateScreenTransform()}setRotation(t){this.rotation=isFinite(t)?t:0,this.updateScreenTransform()}updateScreenTransform(){this.screen_transform=this.translation_x!==0||this.translation_y!==0||this.scale_x!==1||this.scale_y!==1||this.rotation!==0}setDrawAnchor(t,e){this.anchor_x=typeof t=="number"?t:0,this.anchor_y=typeof e=="number"?e:0}setDrawRotation(t){this.object_rotation=t}setDrawScale(t,e=t){this.object_scale_x=t,this.object_scale_y=e}initDrawOp(t,e,s=!0){let i=!1;return this.screen_transform&&(this.context.save(),i=!0,this.context.translate(this.translation_x,-this.translation_y),this.context.scale(this.scale_x,this.scale_y),this.context.rotate(-this.rotation/180*Math.PI),this.context.translate(t,e)),s&&(this.object_rotation!==0||this.object_scale_x!==1||this.object_scale_y!==1)&&(i||(this.context.save(),i=!0,this.context.translate(t,e)),this.object_rotation!==0&&this.context.rotate(-this.object_rotation/180*Math.PI),(this.object_scale_x!==1||this.object_scale_y!==1)&&this.context.scale(this.object_scale_x,this.object_scale_y)),i}closeDrawOp(){this.context.restore()}checkMouseCursor(){Date.now()>this.last_mouse_move+4e3&&this.cursor_visibility==="auto"&&this.cursor!=="none"&&(this.cursor="none",this.canvas.style.cursor="none")}setCursorVisible(t){this.cursor_visibility=t?"default":"none",t?(this.cursor="default",this.canvas.style.cursor="default"):(this.cursor="none",this.canvas.style.cursor="none")}getCanvas(){return this.canvas}getContext(){return this.context}resize(t,e){if(t&&e){if(t<=0||e<=0||!isFinite(t)||!isFinite(e)){N(this.runtime?.listener,_.E7002,{width:t,height:e});return}this.canvas.width=t,this.canvas.height=e,this.initContext(),this.zBuffer.resize(t,e),this.updateInterface()}}},oa=class extends aa{static{l(this,"PrimitiveScreen")}static{I(this,"PrimitiveScreen")}fillRect(t,e,s,i,r){if(!this.context){N(this.runtime?.listener,_.E7092,{});return}if(!isFinite(t)||!isFinite(e)||!isFinite(s)||!isFinite(i)||s<=0||i<=0){N(this.runtime?.listener,_.E7093,{error:`Invalid parameters: x=${t}, y=${e}, w=${s}, h=${i}`});return}r&&this.setColor(r),this.context.globalAlpha=this.alpha,this.initDrawOp(t,-e)?(this.context.fillRect(-s/2-this.anchor_x*s/2,-i/2+this.anchor_y*i/2,s,i),this.closeDrawOp()):this.context.fillRect(t-s/2-this.anchor_x*s/2,-e-i/2+this.anchor_y*i/2,s,i)}fillRoundRect(t,e,s,i,r=10,n){n&&this.setColor(n),this.context.globalAlpha=this.alpha;let a=this.initDrawOp(t,-e),o=(a?-s/2:t-s/2)-this.anchor_x*s/2,u=(a?-i/2:-e-i/2)+this.anchor_y*i/2;if(this.context.beginPath(),this.context.roundRect)this.context.roundRect(o,u,s,i,r);else{let g=Math.min(r,s/2,i/2);this.context.moveTo(o+g,u),this.context.lineTo(o+s-g,u),this.context.quadraticCurveTo(o+s,u,o+s,u+g),this.context.lineTo(o+s,u+i-g),this.context.quadraticCurveTo(o+s,u+i,o+s-g,u+i),this.context.lineTo(o+g,u+i),this.context.quadraticCurveTo(o,u+i,o,u+i-g),this.context.lineTo(o,u+g),this.context.quadraticCurveTo(o,u,o+g,u),this.context.closePath()}this.context.fill(),a&&this.closeDrawOp()}fillRound(t,e,s,i,r){r&&this.setColor(r),this.context.globalAlpha=this.alpha,s=Math.abs(s),i=Math.abs(i),this.initDrawOp(t,-e)?(this.context.beginPath(),this.context.ellipse(-this.anchor_x*s/2,this.anchor_y*i/2,s/2,i/2,0,0,Math.PI*2,!1),this.context.fill(),this.closeDrawOp()):(this.context.beginPath(),this.context.ellipse(t-this.anchor_x*s/2,-e+this.anchor_y*i/2,s/2,i/2,0,0,Math.PI*2,!1),this.context.fill())}drawRect(t,e,s,i,r){r&&this.setColor(r),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width,this.initDrawOp(t,-e)?(this.context.strokeRect(-s/2-this.anchor_x*s/2,-i/2+this.anchor_y*i/2,s,i),this.closeDrawOp()):this.context.strokeRect(t-s/2-this.anchor_x*s/2,-e-i/2+this.anchor_y*i/2,s,i)}drawRoundRect(t,e,s,i,r=10,n){n&&this.setColor(n),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width;let a=this.initDrawOp(t,-e),o=(a?-s/2:t-s/2)-this.anchor_x*s/2,u=(a?-i/2:-e-i/2)+this.anchor_y*i/2;if(this.context.beginPath(),this.context.roundRect)this.context.roundRect(o,u,s,i,r);else{let g=Math.min(r,s/2,i/2);this.context.moveTo(o+g,u),this.context.lineTo(o+s-g,u),this.context.quadraticCurveTo(o+s,u,o+s,u+g),this.context.lineTo(o+s,u+i-g),this.context.quadraticCurveTo(o+s,u+i,o+s-g,u+i),this.context.lineTo(o+g,u+i),this.context.quadraticCurveTo(o,u+i,o,u+i-g),this.context.lineTo(o,u+g),this.context.quadraticCurveTo(o,u,o+g,u),this.context.closePath()}this.context.stroke(),a&&this.closeDrawOp()}drawRound(t,e,s,i,r){r&&this.setColor(r),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width,s=Math.abs(s),i=Math.abs(i),this.initDrawOp(t,-e)?(this.context.beginPath(),this.context.ellipse(-this.anchor_x*s/2,this.anchor_y*i/2,s/2,i/2,0,0,Math.PI*2,!1),this.context.stroke(),this.closeDrawOp()):(this.context.beginPath(),this.context.ellipse(t-this.anchor_x*s/2,-e+this.anchor_y*i/2,s/2,i/2,0,0,Math.PI*2,!1),this.context.stroke())}drawLine(t,e,s,i,r){r&&this.setColor(r),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width;let n=this.initDrawOp(0,0,!1);this.context.beginPath(),this.context.moveTo(t,-e),this.context.lineTo(s,-i),this.context.stroke(),n&&this.closeDrawOp()}drawPolygon(t){let{color:e,points:s}=this.extractPoints(t);if(!s||s.length<4)return;e&&this.setColor(e),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width;let i=Math.floor(s.length/2),r=this.initDrawOp(0,0,!1);this.context.beginPath(),this.context.moveTo(s[0],-s[1]);for(let n=1;n<i;n++)this.context.lineTo(s[n*2],-s[n*2+1]);this.context.closePath(),this.context.stroke(),r&&this.closeDrawOp()}drawPolyline(t){let{color:e,points:s}=this.extractPoints(t);if(!s||s.length<4)return;e&&this.setColor(e),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width;let i=Math.floor(s.length/2),r=this.initDrawOp(0,0,!1);this.context.beginPath(),this.context.moveTo(s[0],-s[1]);for(let n=1;n<i;n++)this.context.lineTo(s[n*2],-s[n*2+1]);this.context.stroke(),r&&this.closeDrawOp()}fillPolygon(t){let{color:e,points:s}=this.extractPoints(t);if(!s||s.length<4)return;e&&this.setColor(e),this.context.globalAlpha=this.alpha;let i=Math.floor(s.length/2),r=this.initDrawOp(0,0,!1);this.context.beginPath(),this.context.moveTo(s[0],-s[1]);for(let n=1;n<i;n++)this.context.lineTo(s[n*2],-s[n*2+1]);this.context.fill(),r&&this.closeDrawOp()}drawQuadCurve(t){let{color:e,points:s}=this.extractPoints(t);if(!s||s.length<4)return;e&&this.setColor(e),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width;let i=this.initDrawOp(0,0,!1);this.context.beginPath(),this.context.moveTo(s[0],-s[1]);let r=2;for(;r<=s.length-4;)this.context.quadraticCurveTo(s[r],-s[r+1],s[r+2],-s[r+3]),r+=4;this.context.stroke(),i&&this.closeDrawOp()}drawBezierCurve(t){let{color:e,points:s}=this.extractPoints(t);if(!s||s.length<4)return;e&&this.setColor(e),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width;let i=this.initDrawOp(0,0,!1);this.context.beginPath(),this.context.moveTo(s[0],-s[1]);let r=2;for(;r<=s.length-6;)this.context.bezierCurveTo(s[r],-s[r+1],s[r+2],-s[r+3],s[r+4],-s[r+5]),r+=6;this.context.stroke(),i&&this.closeDrawOp()}drawArc(t,e,s,i,r,n,a){a&&this.setColor(a),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width,this.initDrawOp(t,-e)?(this.context.beginPath(),this.context.arc(0,0,s,-i/180*Math.PI,-r/180*Math.PI,n),this.context.stroke(),this.closeDrawOp()):(this.context.beginPath(),this.context.arc(t,-e,s,-i/180*Math.PI,-r/180*Math.PI,n),this.context.stroke())}fillArc(t,e,s,i,r,n,a){a&&this.setColor(a),this.context.globalAlpha=this.alpha,this.initDrawOp(t,-e)?(this.context.beginPath(),this.context.arc(0,0,s,-i/180*Math.PI,-r/180*Math.PI,n),this.context.fill(),this.closeDrawOp()):(this.context.beginPath(),this.context.arc(t,-e,s,-i/180*Math.PI,-r/180*Math.PI,n),this.context.fill())}extractPoints(t){let e,s;return t.length>0&&t.length%2===1&&typeof t[t.length-1]=="string"?(e=t[t.length-1],s=t.slice(0,-1)):Array.isArray(t[0])?(t[1]&&typeof t[1]=="string"&&(e=t[1]),s=t[0]):s=t,{color:e,points:s}}},ha=class extends oa{static{l(this,"SpriteScreen")}static{I(this,"SpriteScreen")}_lastImageSmoothing=!0;_frameTime=0;initDraw(){super.initDraw(),this._frameTime=performance.now()}setImageSmoothing(){let t=!this.pixelated;t!==this._lastImageSmoothing&&(this.context.imageSmoothingEnabled=t,this._lastImageSmoothing=t)}getSpriteFrame(t){let e=null;if(typeof t=="string"){let i=t,r=null;if(this.runtime&&this.runtime.sprites&&(r=this.runtime.sprites[t]),!r){let n=t.split(".");n.length>1&&this.runtime&&this.runtime.sprites&&(r=this.runtime.sprites[n[0]],e=Number.parseInt(n[1])||0)}if(!r)return N(this.runtime?.listener,_.E7004,{spriteName:i}),null;t=r}else if(t&&typeof t=="object"&&t.canvas&&!t.frames)return t.canvas||t.image||null;if(!t||!t.ready){let i=typeof t=="string"?t:"unknown";return N(this.runtime?.listener,_.E7005,{spriteName:i}),null}let s=t;if(s.frames&&s.frames.length>1){if(e===null){s.animation_start===0&&(s.animation_start=this._frameTime);let i=1e3/s.fps;e=Math.floor((this._frameTime-s.animation_start)/i)%s.frames.length}return e>=0&&e<s.frames.length?s.frames[e].canvas:s.frames[0].canvas}else if(s.frames&&s.frames[0])return s.frames[0].canvas;return null}drawSprite(t,e,s,i,r){let n=this.getSpriteFrame(t);if(n){if(i==null&&(i=n.width),r||(r=i/n.width*n.height),!this.screen_transform&&this.object_rotation===0&&this.object_scale_x===1&&this.object_scale_y===1){let a=e-i/2-this.anchor_x*i/2,o=-s-r/2+this.anchor_y*r/2,u=this.width/2,g=this.height/2;if(a>u||a+i<-u||o>g||o+r<-g)return}this.context.globalAlpha=this.alpha,this.setImageSmoothing(),this.initDrawOp(e,-s)?(this.context.drawImage(n,-i/2-this.anchor_x*i/2,-r/2+this.anchor_y*r/2,i,r),this.closeDrawOp()):this.context.drawImage(n,e-i/2-this.anchor_x*i/2,-s-r/2+this.anchor_y*r/2,i,r)}}drawSpritePart(t,e,s,i,r,n,a,o,u){let g=this.getSpriteFrame(t);if(g){if(o==null&&(o=i),u||(u=o/i*r),!this.screen_transform&&this.object_rotation===0&&this.object_scale_x===1&&this.object_scale_y===1){let y=n-o/2-this.anchor_x*o/2,O=-a-u/2+this.anchor_y*u/2,b=this.width/2,A=this.height/2;if(y>b||y+o<-b||O>A||O+u<-A)return}this.context.globalAlpha=this.alpha,this.setImageSmoothing(),this.initDrawOp(n,-a)?(this.context.drawImage(g,e,s,i,r,-o/2-this.anchor_x*o/2,-u/2+this.anchor_y*u/2,o,u),this.closeDrawOp()):this.context.drawImage(g,e,s,i,r,n-o/2-this.anchor_x*o/2,-a-u/2+this.anchor_y*u/2,o,u)}}drawMap(t,e,s,i,r){let n=null;typeof t=="string"?this.runtime&&this.runtime.maps&&(n=this.runtime.maps[t]):n=t,n&&n.ready&&(this.context.globalAlpha=this.alpha,this.setImageSmoothing(),this.initDrawOp(e,-s)?(n.draw(this.context,-i/2-this.anchor_x*i/2,-r/2+this.anchor_y*r/2,i,r),this.closeDrawOp()):n.draw(this.context,e-i/2-this.anchor_x*i/2,-s-r/2+this.anchor_y*r/2,i,r))}},la=class extends ha{static{l(this,"TextScreen")}static{I(this,"TextScreen")}_cachedFontSize=-1;_cachedFontName="";_cachedFontString="";getFontString(t){return(t!==this._cachedFontSize||this.font!==this._cachedFontName)&&(this._cachedFontSize=t,this._cachedFontName=this.font,this._cachedFontString=`${t}pt ${this.font}`),this._cachedFontString}textWidth(t,e){return this.context.font=this.getFontString(e),this.context.measureText(t).width}drawText(t,e,s,i,r){r&&this.setColor(r),this.context.globalAlpha=this.alpha,this.context.font=this.getFontString(i),this.context.textAlign="center",this.context.textBaseline="middle";let n=this.context.measureText(t).width,a=i;this.initDrawOp(e,-s)?(this.context.fillText(t,0-this.anchor_x*n/2,0+this.anchor_y*a/2),this.closeDrawOp()):this.context.fillText(t,e-this.anchor_x*n/2,-s+this.anchor_y*a/2)}drawTextOutline(t,e,s,i,r){r&&this.setColor(r),this.context.globalAlpha=this.alpha,this.context.font=this.getFontString(i),this.context.lineWidth=this.line_width,this.context.textAlign="center",this.context.textBaseline="middle";let n=this.context.measureText(t).width,a=i;this.initDrawOp(e,-s)?(this.context.strokeText(t,0-this.anchor_x*n/2,0+this.anchor_y*a/2),this.closeDrawOp()):this.context.strokeText(t,e-this.anchor_x*n/2,-s+this.anchor_y*a/2)}},ca=class extends la{static{l(this,"TriangleScreen")}static{I(this,"TriangleScreen")}tri(t,e,s,i,r,n,a){a&&this.setColor(a),this.context.globalAlpha=this.alpha;let o={x:t,y:-e},u={x:s,y:-i},g={x:r,y:-n};qi(this.context,o,u,g,this.context.fillStyle)}trib(t,e,s,i,r,n,a){a&&this.setColor(a),this.context.globalAlpha=this.alpha;let o={x:t,y:-e},u={x:s,y:-i},g={x:r,y:-n};Hi(this.context,o,u,g,this.context.strokeStyle,this.line_width)}ttri(t,e,s,i,r,n,a,o,u,g,y,O,b,A="tiles",m=1,j=1,J=1,D=!1){this.context.globalAlpha=this.alpha;let C=this.canvas.width,X=this.canvas.height,q=Math.min(C/200,X/200),V=I(he=>C/2+he*q,"toCanvasX"),Ee=I(he=>X/2-he*q,"toCanvasY"),Re={context:this.context,width:C,height:X,runtime:this.runtime,pixelated:this.pixelated===1};Wi(Re,{x:V(t),y:Ee(e),u:a,v:o,z:m},{x:V(s),y:Ee(i),u,v:g,z:j},{x:V(r),y:Ee(n),u:y,v:O,z:J},b,A,this.zBuffer,D)}},Ki=class extends ca{static{l(this,"Screen")}static{I(this,"Screen")}getInterface(){if(this.interfaceCache)return this.interfaceCache;let t=this;return this.interfaceCache={width:t.width,height:t.height,clear:I(e=>t.clear(e),"clear"),setColor:I(e=>t.setColor(e),"setColor"),setAlpha:I(e=>t.setAlpha(e),"setAlpha"),setPixelated:I(e=>t.setPixelated(e),"setPixelated"),setBlending:I(e=>t.setBlending(e),"setBlending"),setLinearGradient:I((e,s,i,r,n,a)=>t.setLinearGradient(e,s,i,r,n,a),"setLinearGradient"),setRadialGradient:I((e,s,i,r,n)=>t.setRadialGradient(e,s,i,r,n),"setRadialGradient"),setFont:I(e=>t.setFont(e),"setFont"),setTranslation:I((e,s)=>t.setTranslation(e,s),"setTranslation"),setScale:I((e,s)=>t.setScale(e,s),"setScale"),setRotation:I(e=>t.setRotation(e),"setRotation"),setDrawAnchor:I((e,s)=>t.setDrawAnchor(e,s),"setDrawAnchor"),setDrawRotation:I(e=>t.setDrawRotation(e),"setDrawRotation"),setDrawScale:I((e,s)=>t.setDrawScale(e,s),"setDrawScale"),fillRect:I((e,s,i,r,n)=>t.fillRect(e,s,i,r,n),"fillRect"),fillRoundRect:I((e,s,i,r,n,a)=>t.fillRoundRect(e,s,i,r,n,a),"fillRoundRect"),fillRound:I((e,s,i,r,n)=>t.fillRound(e,s,i,r,n),"fillRound"),drawRect:I((e,s,i,r,n)=>t.drawRect(e,s,i,r,n),"drawRect"),drawRoundRect:I((e,s,i,r,n,a)=>t.drawRoundRect(e,s,i,r,n,a),"drawRoundRect"),drawRound:I((e,s,i,r,n)=>t.drawRound(e,s,i,r,n),"drawRound"),drawSprite:I((e,s,i,r,n)=>t.drawSprite(e,s,i,r,n),"drawSprite"),drawSpritePart:I((e,s,i,r,n,a,o,u,g)=>t.drawSpritePart(e,s,i,r,n,a,o,u,g),"drawSpritePart"),drawMap:I((e,s,i,r,n)=>t.drawMap(e,s,i,r,n),"drawMap"),drawText:I((e,s,i,r,n)=>t.drawText(e,s,i,r,n),"drawText"),drawTextOutline:I((e,s,i,r,n)=>t.drawTextOutline(e,s,i,r,n),"drawTextOutline"),textWidth:I((e,s)=>t.textWidth(e,s),"textWidth"),setLineWidth:I(e=>t.setLineWidth(e),"setLineWidth"),setLineDash:I(e=>t.setLineDash(e),"setLineDash"),drawLine:I((e,s,i,r,n)=>t.drawLine(e,s,i,r,n),"drawLine"),drawPolygon:I((...e)=>t.drawPolygon(e),"drawPolygon"),drawPolyline:I((...e)=>t.drawPolyline(e),"drawPolyline"),fillPolygon:I((...e)=>t.fillPolygon(e),"fillPolygon"),drawQuadCurve:I((...e)=>t.drawQuadCurve(e),"drawQuadCurve"),drawBezierCurve:I((...e)=>t.drawBezierCurve(e),"drawBezierCurve"),drawArc:I((e,s,i,r,n,a,o)=>t.drawArc(e,s,i,r,n,a,o),"drawArc"),fillArc:I((e,s,i,r,n,a,o)=>t.fillArc(e,s,i,r,n,a,o),"fillArc"),setCursorVisible:I(e=>t.setCursorVisible(e),"setCursorVisible"),loadFont:I(e=>t.loadFont(e),"loadFont"),isFontReady:I(e=>t.isFontReady(e),"isFontReady"),tri:I((e,s,i,r,n,a,o)=>t.tri(e,s,i,r,n,a,o),"tri"),trib:I((e,s,i,r,n,a,o)=>t.trib(e,s,i,r,n,a,o),"trib"),ttri:I((e,s,i,r,n,a,o,u,g,y,O,b,A,m,j,J,D,C)=>t.ttri(e,s,i,r,n,a,o,u,g,y,O,b,A,m,j,J,D,C),"ttri")},this.interfaceCache}};var ua=Object.defineProperty,It=l((t,e)=>ua(t,"name",{value:e,configurable:!0}),"__name"),Ji=1800,Qi=240;function dt(t,e){if(t==null)return t;if(e&&e.includes(t))return null;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t)){let s=[];for(let i=0;i<t.length;i++)s[i]=dt(t[i],e);return s}if(typeof t=="object"){let s={};for(let i in t)Object.hasOwn(t,i)&&(s[i]=dt(t[i],e));return s}return e?null:t}l(dt,"deepCopy");It(dt,"deepCopy");var Ws=class{static{l(this,"StatePlayer")}static{It(this,"StatePlayer")}looping=!1;loopStart=0;loopIndex=0;loopLength;loopCallback=null;constructor(t=Qi){this.loopLength=t}isLooping(){return this.looping}startLoop(t,e){this.looping=!0,this.loopStart=Math.max(t,1),this.loopIndex=0,this.loopCallback=e}stopLoop(){return this.looping=!1,this.loopCallback=null,this.loopStart}updateLoop(){return this.looping?this.loopIndex===0?(this.loopIndex++,this.loopStart):(this.loopIndex++,this.loopIndex>this.loopLength&&(this.loopIndex=0),this.loopStart-this.loopIndex):null}executeCallback(){this.loopCallback&&this.loopCallback()}restoreState(t,e){if(!(!e||!t)){for(let s in t)Object.hasOwn(t,s)&&!this.isProtectedKey(s)&&delete t[s];for(let s in e)Object.hasOwn(e,s)&&(t[s]=dt(e[s]))}}isProtectedKey(t){return["screen","audio","keyboard","mouse","touch","gamepad","system","storage","sprites","maps","sounds","music","assets","host","session","memory"].includes(t)}},fa=class{static{l(this,"StateRecorder")}static{It(this,"StateRecorder")}history=[];recordIndex=0;recordLength=0;maxLength;excluded=[];constructor(t=Ji){this.maxLength=t}setExcluded(t){this.excluded=t}record(t){let e=this.makeStorableState(t);this.history[this.recordIndex++]=e,this.recordLength=Math.min(this.recordLength+1,this.maxLength),this.recordIndex>=this.maxLength&&(this.recordIndex=0)}getState(t){if(t>=this.recordLength)return null;let e=(this.recordIndex-t-1+this.maxLength)%this.maxLength;return this.history[e]}getLength(){return this.recordLength}getMaxLength(){return this.maxLength}clear(){this.history=[],this.recordIndex=0,this.recordLength=0}trimTo(t){if(t>=this.recordLength)return;let e=[],s=this.recordLength,i=t+1;for(let r=s;r>=i;r--){let n=(this.recordIndex-r+this.maxLength)%this.maxLength;e.push(this.history[n])}this.history=e,this.recordIndex=this.history.length,this.recordLength=this.history.length}makeStorableState(t){return dt(t,this.excluded)}},Xi=class{static{l(this,"TimeMachine")}static{It(this,"TimeMachine")}runtime;recorder;player;recording=!1;replayPosition=0;statusCallback;constructor(t){this.runtime=t,this.recorder=new fa(Ji),this.player=new Ws(Qi),this.setupExclusions()}setupExclusions(){let t=[];if(this.runtime.vm?.context?.global){let e=this.runtime.vm.context.global;e.random&&t.push(e.random),e.screen&&t.push(e.screen),e.audio&&t.push(e.audio),e.keyboard&&t.push(e.keyboard),e.mouse&&t.push(e.mouse),e.touch&&t.push(e.touch),e.gamepad&&t.push(e.gamepad),e.system&&t.push(e.system),e.storage&&t.push(e.storage),e.host&&t.push(e.host),e.session&&t.push(e.session),e.memory&&t.push(e.memory)}this.recorder.setExcluded(t)}step(){if(this.recording)try{this.replayPosition!==0&&(this.recorder.trimTo(this.replayPosition),this.player.isLooping()&&this.player.startLoop(this.recorder.getLength(),()=>this.loopCallback()),this.replayPosition=0),this.runtime.vm?.context?.global&&this.recorder.record(this.runtime.vm.context.global),this.sendStatus()}catch(t){N(this.runtime?.listener,_.E7082,{error:String(t)})}}messageReceived(t){switch(t.command){case"start_recording":this.startRecording();break;case"stop_recording":this.stopRecording();break;case"step_backward":this.stepBackward();break;case"step_forward":this.stepForward();break;case"replay_position":t.position!=null&&this.setReplayPosition(t.position);break;case"start_looping":this.startLooping();break;case"stop_looping":this.stopLooping();break}}startRecording(){if(!this.recording)try{this.recording=!0,this.recorder.clear(),this.replayPosition=0,this.sendStatus()}catch(t){this.recording=!1,N(this.runtime?.listener,_.E7083,{error:String(t)})}}stopRecording(){if(this.recording)try{this.recording=!1,this.sendStatus()}catch(t){N(this.runtime?.listener,_.E7083,{error:String(t)})}}stepBackward(){this.replayPosition+1>=this.recorder.getLength()||(this.stopLooping(),this.replayPosition++,this.replay(),this.sendStatus())}stepForward(){this.replayPosition<=1||(this.stopLooping(),this.replayPosition--,this.replay(),this.sendStatus())}setReplayPosition(t){if(!isFinite(t)||t<0){N(this.runtime?.listener,_.E7081,{value:String(t)});return}let e=Math.round(t);this.replayPosition=Math.max(2,Math.min(this.recorder.getLength()-1,e)),this.player.isLooping()&&this.player.startLoop(this.replayPosition,()=>this.loopCallback()),this.replay(),this.sendStatus()}startLooping(){if(this.recorder.getLength()===0)return;this.recording=!1;let t=Math.max(this.replayPosition,1);this.player.startLoop(t,()=>this.loopCallback())}stopLooping(){this.player.isLooping()&&(this.replayPosition=this.player.stopLoop(),this.sendStatus())}replay(t=!1){if(this.replayPosition>=this.recorder.getLength())return;let e=this.recorder.getState(this.replayPosition);e&&this.runtime.vm?.context?.global&&this.player.restoreState(this.runtime.vm.context.global,e),t||this.runtime.drawCall?.()}loopCallback(){let t=this.player.updateLoop();t!==null&&(this.replayPosition=t,this.replay(!0),this.runtime.updateCall?.(),this.runtime.drawCall?.()),this.sendStatus()}sendStatus(){this.statusCallback&&this.statusCallback({recording:this.recording,looping:this.player.isLooping(),position:this.replayPosition,length:this.recorder.getLength(),max:this.recorder.getMaxLength()})}loopStep(){this.player.isLooping()&&this.player.executeCallback()}onStatus(t){this.statusCallback=t}isRecording(){return this.recording}isLooping(){return this.player.isLooping()}};var pa=Object.defineProperty,T=l((t,e)=>pa(t,"name",{value:e,configurable:!0}),"__name"),Zi={encode:T(t=>{try{return JSON.stringify(t)}catch{return""}},"encode"),decode:T(t=>{try{return JSON.parse(t)}catch{return null}},"decode"),pretty:T((t,e=2)=>{try{return JSON.stringify(t,null,e)}catch{return""}},"pretty")},er={map:T((t,e)=>t.map(e),"map"),filter:T((t,e)=>t.filter(e),"filter"),reduce:T((t,e,s)=>t.reduce(e,s),"reduce"),find:T((t,e)=>t.find(e)??null,"find"),findIndex:T((t,e)=>t.findIndex(e),"findIndex"),some:T((t,e)=>t.some(e),"some"),every:T((t,e)=>t.every(e),"every"),reverse:T(t=>t.slice().reverse(),"reverse"),sort:T((t,e)=>t.slice().sort(e),"sort"),slice:T((t,e,s)=>t.slice(e,s),"slice"),concat:T((...t)=>[].concat(...t),"concat"),flat:T((t,e=1)=>t.flat(e),"flat"),flatMap:T((t,e)=>t.flatMap(e),"flatMap"),indexOf:T((t,e,s)=>t.indexOf(e,s),"indexOf"),lastIndexOf:T((t,e,s)=>t.lastIndexOf(e,s),"lastIndexOf"),includes:T((t,e,s)=>t.includes(e,s),"includes"),length:T(t=>t.length,"length"),first:T(t=>t[0]??null,"first"),last:T(t=>t[t.length-1]??null,"last"),at:T((t,e)=>{let s=e<0?t.length+e:e;return t[s]??null},"at"),push:T((t,...e)=>(t.push(...e),t),"push"),pop:T(t=>t.pop()??null,"pop"),shift:T(t=>t.shift()??null,"shift"),unshift:T((t,...e)=>(t.unshift(...e),t),"unshift"),splice:T((t,e,s,...i)=>t.splice(e,s??t.length-e,...i),"splice"),fill:T((t,e,s,i)=>t.fill(e,s,i),"fill"),join:T((t,e=",")=>t.join(e),"join"),unique:T(t=>[...new Set(t)],"unique"),shuffle:T(t=>{let e=[...t];for(let s=e.length-1;s>0;s--){let i=Math.floor(Math.random()*(s+1));[e[s],e[i]]=[e[i],e[s]]}return e},"shuffle"),chunk:T((t,e)=>{let s=[];for(let i=0;i<t.length;i+=e)s.push(t.slice(i,i+e));return s},"chunk"),sum:T(t=>{let e=0;for(let s=0;s<t.length;s++)e+=t[s];return e},"sum"),average:T(t=>{if(t.length===0)return 0;let e=0;for(let s=0;s<t.length;s++)e+=t[s];return e/t.length},"average"),min:T(t=>{if(t.length===0)return 0;let e=t[0];for(let s=1;s<t.length;s++)t[s]<e&&(e=t[s]);return e},"min"),max:T(t=>{if(t.length===0)return 0;let e=t[0];for(let s=1;s<t.length;s++)t[s]>e&&(e=t[s]);return e},"max")},tr={abs:T(t=>Math.abs(t),"abs"),sqrt:T(t=>Math.sqrt(t),"sqrt"),floor:T(t=>Math.floor(t),"floor"),ceil:T(t=>Math.ceil(t),"ceil"),round:T(t=>Math.round(t),"round"),min:T((...t)=>Math.min(...t),"min"),max:T((...t)=>Math.max(...t),"max"),pow:T((t,e)=>t**e,"pow"),exp:T(t=>Math.exp(t),"exp"),log:T(t=>Math.log(t),"log"),log10:T(t=>Math.log10(t),"log10"),sin:T(t=>Math.sin(t),"sin"),cos:T(t=>Math.cos(t),"cos"),tan:T(t=>Math.tan(t),"tan"),asin:T(t=>Math.asin(t),"asin"),acos:T(t=>Math.acos(t),"acos"),atan:T(t=>Math.atan(t),"atan"),atan2:T((t,e)=>Math.atan2(t,e),"atan2"),random:T(()=>Math.random(),"random"),randomInt:T((t,e)=>Math.floor(Math.random()*(e-t+1))+t,"randomInt"),randomFloat:T((t,e)=>Math.random()*(e-t)+t,"randomFloat"),PI:Math.PI,E:Math.E,clamp:T((t,e,s)=>Math.min(Math.max(t,e),s),"clamp"),lerp:T((t,e,s)=>t+(e-t)*s,"lerp"),distance:T((t,e,s,i)=>Math.sqrt((s-t)**2+(i-e)**2),"distance"),distance3D:T((t,e,s,i,r,n)=>Math.sqrt((i-t)**2+(r-e)**2+(n-s)**2),"distance3D"),angleBetween:T((t,e,s,i)=>Math.atan2(i-e,s-t),"angleBetween"),degToRad:T(t=>t*(Math.PI/180),"degToRad"),radToDeg:T(t=>t*(180/Math.PI),"radToDeg"),sign:T(t=>Math.sign(t),"sign"),mod:T((t,e)=>(t%e+e)%e,"mod")},sr={split:T((t,e="")=>t.split(e),"split"),join:T((t,e="")=>t.join(e),"join"),trim:T(t=>t.trim(),"trim"),trimStart:T(t=>t.trimStart(),"trimStart"),trimEnd:T(t=>t.trimEnd(),"trimEnd"),replace:T((t,e,s)=>t.replace(e,s),"replace"),replaceAll:T((t,e,s)=>t.split(e).join(s),"replaceAll"),startsWith:T((t,e)=>t.startsWith(e),"startsWith"),endsWith:T((t,e)=>t.endsWith(e),"endsWith"),contains:T((t,e)=>t.includes(e),"contains"),toLowerCase:T(t=>t.toLowerCase(),"toLowerCase"),toUpperCase:T(t=>t.toUpperCase(),"toUpperCase"),charAt:T((t,e)=>t.charAt(e),"charAt"),charCodeAt:T((t,e)=>t.charCodeAt(e),"charCodeAt"),fromCharCode:T((...t)=>String.fromCharCode(...t),"fromCharCode"),substring:T((t,e,s)=>t.substring(e,s),"substring"),slice:T((t,e,s)=>t.slice(e,s),"slice"),indexOf:T((t,e,s)=>t.indexOf(e,s),"indexOf"),lastIndexOf:T((t,e,s)=>t.lastIndexOf(e,s),"lastIndexOf"),repeat:T((t,e)=>t.repeat(e),"repeat"),padStart:T((t,e,s=" ")=>t.padStart(e,s),"padStart"),padEnd:T((t,e,s=" ")=>t.padEnd(e,s),"padEnd"),length:T(t=>t.length,"length"),parseInt:T((t,e)=>{let s=Number.parseInt(t,e);return isNaN(s)?0:s},"parseInt"),parseFloat:T(t=>{let e=Number.parseFloat(t);return isNaN(e)?0:e},"parseFloat"),format:T((t,...e)=>t.replace(/{(\d+)}/g,(s,i)=>{let r=Number.parseInt(i);return typeof e[r]<"u"?String(e[r]):s}),"format")};var da=Object.defineProperty,v=l((t,e)=>da(t,"name",{value:e,configurable:!0}),"__name"),rt=class qs{static{l(this,"_Random")}static{v(this,"Random")}_seed;a=13971;b=12345;size=1<<30;mask;norm;constructor(e,s=!0){this._seed=e??Math.random(),this._seed===0&&(this._seed=Math.random()),this._seed<1&&(this._seed*=1<<30),this.mask=this.size-1,this.norm=1/this.size,s&&(this.nextSeed(),this.nextSeed(),this.nextSeed())}next(){return this._seed=this._seed*this.a+this.b&this.mask,this._seed*this.norm}nextInt(e){return Math.floor(this.next()*e)}nextSeed(){return this._seed=this._seed*this.a+this.b&this.mask}seed(e){return this._seed=e??Math.random(),this._seed<1&&(this._seed*=1<<30),this.nextSeed(),this.nextSeed(),this.nextSeed()}clone(e){return e!=null?new qs(e):new qs(this._seed,!1)}},d=class G{static{l(this,"_Token")}static{v(this,"Token")}tokenizer;type;value;string_value;line;column;start;length;index;reserved_keyword;is_binary_operator;constructor(e,s,i,r){this.tokenizer=e,this.type=s,this.value=i,this.string_value=r,this.line=e.line,this.column=e.column,this.start=e.token_start,this.length=e.index-this.start,this.index=e.index,this.type===G.TYPE_IDENTIFIER&&Object.hasOwn(G.predefined,String(this.value))&&(this.type=G.predefined[String(this.value)],this.reserved_keyword=!0),this.is_binary_operator=this.type>=30&&this.type<=39||this.type>=200&&this.type<=201||this.type>=2&&this.type<=7}toString(){return String(this.value)+" : "+this.type}static TYPE_EQUALS=1;static TYPE_DOUBLE_EQUALS=2;static TYPE_GREATER=3;static TYPE_GREATER_OR_EQUALS=4;static TYPE_LOWER=5;static TYPE_LOWER_OR_EQUALS=6;static TYPE_UNEQUALS=7;static TYPE_IDENTIFIER=10;static TYPE_NUMBER=11;static TYPE_STRING=12;static TYPE_OPEN_BRACE=20;static TYPE_CLOSED_BRACE=21;static TYPE_OPEN_BRACKET=24;static TYPE_CLOSED_BRACKET=25;static TYPE_COMMA=26;static TYPE_DOT=27;static TYPE_COLON=28;static TYPE_PLUS=30;static TYPE_MINUS=31;static TYPE_MULTIPLY=32;static TYPE_DIVIDE=33;static TYPE_POWER=34;static TYPE_MODULO=35;static TYPE_BINARY_AND=36;static TYPE_BINARY_OR=37;static TYPE_SHIFT_LEFT=38;static TYPE_SHIFT_RIGHT=39;static TYPE_PLUS_EQUALS=40;static TYPE_MINUS_EQUALS=41;static TYPE_MULTIPLY_EQUALS=42;static TYPE_DIVIDE_EQUALS=43;static TYPE_MODULO_EQUALS=44;static TYPE_AND_EQUALS=45;static TYPE_OR_EQUALS=46;static TYPE_RETURN=100;static TYPE_BREAK=101;static TYPE_CONTINUE=102;static TYPE_FUNCTION=103;static TYPE_IF=104;static TYPE_THEN=105;static TYPE_ELSE=106;static TYPE_ELSIF=107;static TYPE_END=108;static TYPE_FOR=109;static TYPE_TO=110;static TYPE_BY=111;static TYPE_IN=112;static TYPE_WHILE=113;static TYPE_OBJECT=114;static TYPE_CLASS=115;static TYPE_EXTENDS=116;static TYPE_NEW=117;static TYPE_ARROW=118;static TYPE_TEMPLATE=119;static TYPE_AFTER=61;static TYPE_EVERY=62;static TYPE_DO=63;static TYPE_SLEEP=64;static TYPE_LOCAL=70;static TYPE_AND=200;static TYPE_OR=201;static TYPE_NOT=202;static TYPE_ERROR=404;static TYPE_DELETE=403;static predefined={return:G.TYPE_RETURN,break:G.TYPE_BREAK,continue:G.TYPE_CONTINUE,function:G.TYPE_FUNCTION,for:G.TYPE_FOR,to:G.TYPE_TO,by:G.TYPE_BY,in:G.TYPE_IN,while:G.TYPE_WHILE,if:G.TYPE_IF,then:G.TYPE_THEN,else:G.TYPE_ELSE,elsif:G.TYPE_ELSIF,end:G.TYPE_END,object:G.TYPE_OBJECT,class:G.TYPE_CLASS,extends:G.TYPE_EXTENDS,new:G.TYPE_NEW,and:G.TYPE_AND,or:G.TYPE_OR,not:G.TYPE_NOT,after:G.TYPE_AFTER,every:G.TYPE_EVERY,do:G.TYPE_DO,sleep:G.TYPE_SLEEP,delete:G.TYPE_DELETE,local:G.TYPE_LOCAL,var:G.TYPE_LOCAL,let:G.TYPE_LOCAL}},ma=class{static{l(this,"Tokenizer")}static{v(this,"Tokenizer")}input;filename;index=0;line=1;column=0;last_column=0;buffer=[];token_start=0;chars={};doubles={};shifts={};letter_regex=/^\p{L}/u;constructor(t,e){this.input=t,this.filename=e,this.chars["("]=d.TYPE_OPEN_BRACE,this.chars[")"]=d.TYPE_CLOSED_BRACE,this.chars["["]=d.TYPE_OPEN_BRACKET,this.chars["]"]=d.TYPE_CLOSED_BRACKET,this.chars["{"]=22,this.chars["}"]=23,this.chars["^"]=d.TYPE_POWER,this.chars[","]=d.TYPE_COMMA,this.chars["."]=d.TYPE_DOT,this.chars[":"]=d.TYPE_COLON,this.doubles[">"]=[d.TYPE_GREATER,d.TYPE_GREATER_OR_EQUALS],this.doubles["<"]=[d.TYPE_LOWER,d.TYPE_LOWER_OR_EQUALS],this.doubles["="]=[d.TYPE_EQUALS,d.TYPE_DOUBLE_EQUALS],this.doubles["+"]=[d.TYPE_PLUS,d.TYPE_PLUS_EQUALS],this.doubles["-"]=[d.TYPE_MINUS,d.TYPE_MINUS_EQUALS],this.doubles["*"]=[d.TYPE_MULTIPLY,d.TYPE_MULTIPLY_EQUALS],this.doubles["/"]=[d.TYPE_DIVIDE,d.TYPE_DIVIDE_EQUALS],this.doubles["%"]=[d.TYPE_MODULO,d.TYPE_MODULO_EQUALS],this.doubles["&"]=[d.TYPE_BINARY_AND,d.TYPE_AND_EQUALS],this.doubles["|"]=[d.TYPE_BINARY_OR,d.TYPE_OR_EQUALS],this.shifts["<"]=d.TYPE_SHIFT_LEFT,this.shifts[">"]=d.TYPE_SHIFT_RIGHT}pushBack(t){return this.buffer.splice(0,0,t),t}peek(){if(this.buffer.length>0)return this.buffer[0];let t=this.next();return t&&this.pushBack(t),t}finished(){return this.index>=this.input.length&&this.buffer.length===0}nextChar(t=!1){let e,s;if(e=this.input.charAt(this.index++),e===`
|
|
136
|
+
`)this.line+=1,this.last_column=this.column,this.column=0;else if(e==="/"&&!t){if(this.input.charAt(this.index)==="/"){for(;e=this.input.charAt(this.index++),!(e===`
|
|
137
|
+
`||this.index>=this.input.length););return this.line+=1,this.last_column=this.column,this.column=0,this.nextChar()}else if(this.input.charAt(this.index)==="*"){for(s=0;;){if(e=this.input.charAt(this.index++),e===`
|
|
138
|
+
`)this.line+=1,this.last_column=this.column,this.column=0,s=0;else if(e==="*")s=1;else{if(e==="/"&&s===1)break;s=0}if(this.index>=this.input.length)break}return this.nextChar()}}else this.column+=1;return e}rewind(){this.index-=1,this.column-=1,this.input.charAt(this.index)===`
|
|
139
|
+
`&&(this.line-=1,this.column=this.last_column)}next(){let t,e;if(this.buffer.length>0)return this.buffer.splice(0,1)[0];for(;;){if(this.index>=this.input.length)return null;if(t=this.nextChar(),e=t.charCodeAt(0),e>32&&e!==160)break}return this.token_start=this.index-1,this.doubles[t]!=null?this.parseDouble(t,this.doubles[t]):this.chars[t]!=null?new d(this,this.chars[t],t):t==="!"?this.parseUnequals(t):e>=48&&e<=57?this.parseNumber(t):e>=65&&e<=90||e>=97&&e<=122||e===95||this.letter_regex.test(t)?this.parseIdentifier(t):t==='"'?this.parseString(t,'"'):t==="'"?this.parseString(t,"'"):t==="`"?this.parseString(t,"`"):this.error("Syntax Error")}changeNumberToIdentifier(){let t,e,s,i=[];if(e=this.next(),e!=null&&e.type===d.TYPE_NUMBER){for(s=(e.string_value||String(e.value)).split("."),t=s.length-1;t>=0;t--)s[t].length>0&&this.pushBack(new d(this,d.TYPE_IDENTIFIER,s[t])),t>0&&i.push(this.pushBack(new d(this,d.TYPE_DOT,".")));return i}else return e!=null&&e.type===d.TYPE_STRING?this.pushBack(new d(this,d.TYPE_IDENTIFIER,e.value)):e?this.pushBack(e):void 0}parseDouble(t,e){let s=this.input.charAt(this.index);return t==="="&&s===">"?(this.nextChar(),new d(this,d.TYPE_ARROW,"=>")):this.shifts[t]!=null&&this.index<this.input.length&&s===t?(this.nextChar(),new d(this,this.shifts[t],t+t)):e&&this.index<this.input.length&&s==="="?(this.nextChar(),new d(this,e[1],t+"=")):new d(this,e?e[0]:this.chars[t],t)}parseUnequals(t){return this.index<this.input.length&&this.input.charAt(this.index)==="="?(this.nextChar(),new d(this,d.TYPE_UNEQUALS,"!=")):this.error("Expected inequality !=")}parseIdentifier(t){let e,s;for(;;){if(this.index>=this.input.length)return new d(this,d.TYPE_IDENTIFIER,t);if(e=this.nextChar(),s=e.charCodeAt(0),s>=65&&s<=90||s>=97&&s<=122||s===95||s>=48&&s<=57||this.letter_regex.test(e))t+=e;else return this.rewind(),new d(this,d.TYPE_IDENTIFIER,t)}}parseNumber(t){let e,s,i=!1,r=!1;for(;;){if(this.index>=this.input.length)return new d(this,d.TYPE_NUMBER,Number.parseFloat(t),t);if(e=this.nextChar(),s=e.charCodeAt(0),e==="."&&!r&&!i)r=!0,t+=e;else if(s>=48&&s<=57)t+=e;else if((e==="e"||e==="E")&&!i&&this.index<this.input.length)i=!0,t+=e,e=this.nextChar(),e==="+"||e==="-"?t+=e:this.rewind();else return(e==="x"||e==="X")&&t==="0"?this.parseHexNumber("0x"):(this.rewind(),new d(this,d.TYPE_NUMBER,Number.parseFloat(t),t))}}parseHexNumber(t){let e;for(;;){if(this.index>=this.input.length)return new d(this,d.TYPE_NUMBER,Number.parseInt(t),t);if(e=this.nextChar(),/[a-fA-F0-9]/.test(e))t+=e;else return this.rewind(),new d(this,d.TYPE_NUMBER,Number.parseInt(t),t)}}parseString(t,e){let s,i=0,r;for(e==null&&(e='"'),e==='"'&&this.input.charAt(this.index)==='"'&&this.input.charAt(this.index+1)==='"'&&this.input.charAt(this.index+2)!=='"'&&(e='"""',this.nextChar(!0),this.nextChar(!0));;){if(this.index>=this.input.length)return this.error("Unclosed string value");if(s=this.nextChar(!0),s==="\\")switch(r=this.nextChar(!0),r){case"n":t+=`
|
|
140
|
+
`;break;case"\\":t+="\\";break;case e:t+=e;break;default:t+="\\"+r}else if(s===e)if(r=this.nextChar(!0),r===e)t+=s;else return this.rewind(),t+=s,new d(this,e==="`"?d.TYPE_TEMPLATE:d.TYPE_STRING,t.substring(1,t.length-1));else{if(e==='"""'&&s==='"'){if(i+=1,i===3)return new d(this,d.TYPE_STRING,t.substring(1,t.length-2))}else i=0;t+=s}}}error(t){throw new Error(t)}},ga=class{static{l(this,"OPCODES_CLASS2")}static{v(this,"OPCODES_CLASS")}table={};set(e,s){return this[e]=s,this[s]=e,this.table[e]=s,this.table[s]=e,s}TYPE=1;VARIABLE_TYPE=2;PROPERTY_TYPE=3;LOAD_IMPORT=4;LOAD_THIS=5;LOAD_GLOBAL=6;LOAD_VALUE=10;LOAD_LOCAL=11;LOAD_VARIABLE=12;LOAD_LOCAL_OBJECT=13;LOAD_VARIABLE_OBJECT=14;POP=15;LOAD_PROPERTY=16;LOAD_PROPERTY_OBJECT=17;CREATE_OBJECT=18;MAKE_OBJECT=19;CREATE_ARRAY=20;STORE_LOCAL=21;STORE_VARIABLE=23;CREATE_PROPERTY=24;STORE_PROPERTY=25;DELETE=26;UPDATE_CLASS=27;CREATE_CLASS=28;NEW_CALL=29;ADD=30;SUB=31;MUL=32;DIV=33;MODULO=34;BINARY_AND=35;BINARY_OR=36;SHIFT_LEFT=37;SHIFT_RIGHT=38;NEGATE=39;EQ=40;NEQ=41;LT=42;GT=43;LTE=44;GTE=45;NOT=50;LOAD_PROPERTY_ATOP=68;JUMP=80;JUMPY=81;JUMPN=82;JUMPY_NOPOP=83;JUMPN_NOPOP=84;LOAD_ROUTINE=89;FUNCTION_CALL=90;FUNCTION_APPLY_VARIABLE=91;FUNCTION_APPLY_PROPERTY=92;SUPER_CALL=93;RETURN=94;FORLOOP_INIT=95;FORLOOP_CONTROL=96;FORIN_INIT=97;FORIN_CONTROL=98;UNARY_OP=100;BINARY_OP=101;COMPILED=200;AFTER=110;EVERY=111;DO=112;SLEEP=113;LOAD_VAR_CALL=120;LOAD_PROP_CALL=121;LOAD_CONST_ADD=122;LOAD_CONST_SUB=123;LOAD_CONST_MUL=124;LOAD_LOCAL_ADD=125;LOAD_LOCAL_SUB=126;LOAD_LOCAL_MUL=127;LOAD_CONST_DIV=128;LOAD_LOCAL_LT=129;LOAD_LOCAL_GT=130;LOAD_LOCAL_EQ=131;constructor(){this.set("TYPE",1),this.set("VARIABLE_TYPE",2),this.set("PROPERTY_TYPE",3),this.set("LOAD_IMPORT",4),this.set("LOAD_THIS",5),this.set("LOAD_GLOBAL",6),this.set("LOAD_VALUE",10),this.set("LOAD_LOCAL",11),this.set("LOAD_VARIABLE",12),this.set("LOAD_LOCAL_OBJECT",13),this.set("LOAD_VARIABLE_OBJECT",14),this.set("POP",15),this.set("LOAD_PROPERTY",16),this.set("LOAD_PROPERTY_OBJECT",17),this.set("CREATE_OBJECT",18),this.set("MAKE_OBJECT",19),this.set("CREATE_ARRAY",20),this.set("STORE_LOCAL",21),this.set("STORE_VARIABLE",23),this.set("CREATE_PROPERTY",24),this.set("STORE_PROPERTY",25),this.set("DELETE",26),this.set("UPDATE_CLASS",27),this.set("CREATE_CLASS",28),this.set("NEW_CALL",29),this.set("ADD",30),this.set("SUB",31),this.set("MUL",32),this.set("DIV",33),this.set("MODULO",34),this.set("BINARY_AND",35),this.set("BINARY_OR",36),this.set("SHIFT_LEFT",37),this.set("SHIFT_RIGHT",38),this.set("NEGATE",39),this.set("EQ",40),this.set("NEQ",41),this.set("LT",42),this.set("GT",43),this.set("LTE",44),this.set("GTE",45),this.set("NOT",50),this.set("LOAD_PROPERTY_ATOP",68),this.set("JUMP",80),this.set("JUMPY",81),this.set("JUMPN",82),this.set("JUMPY_NOPOP",83),this.set("JUMPN_NOPOP",84),this.set("LOAD_ROUTINE",89),this.set("FUNCTION_CALL",90),this.set("FUNCTION_APPLY_VARIABLE",91),this.set("FUNCTION_APPLY_PROPERTY",92),this.set("SUPER_CALL",93),this.set("RETURN",94),this.set("FORLOOP_INIT",95),this.set("FORLOOP_CONTROL",96),this.set("FORIN_INIT",97),this.set("FORIN_CONTROL",98),this.set("UNARY_OP",100),this.set("BINARY_OP",101),this.set("COMPILED",200),this.set("AFTER",110),this.set("EVERY",111),this.set("DO",112),this.set("SLEEP",113),this.set("LOAD_VAR_CALL",120),this.set("LOAD_PROP_CALL",121),this.set("LOAD_CONST_ADD",122),this.set("LOAD_CONST_SUB",123),this.set("LOAD_CONST_MUL",124),this.set("LOAD_LOCAL_ADD",125),this.set("LOAD_LOCAL_SUB",126),this.set("LOAD_LOCAL_MUL",127),this.set("LOAD_CONST_DIV",128),this.set("LOAD_LOCAL_LT",129),this.set("LOAD_LOCAL_GT",130),this.set("LOAD_LOCAL_EQ",131)}},E=new ga,K=class Mt{static{l(this,"_Routine")}static{v(this,"Routine")}num_args;ops;opcodes;arg1;ref;label_count;labels;transpile;import_refs;import_values;import_self;locals_size;uses_arguments;as_function;object;callback;ics;constructor(e=0){this.num_args=e,this.ops=[],this.opcodes=[],this.arg1=[],this.ref=[],this.label_count=0,this.labels={},this.transpile=!1,this.import_refs=[],this.import_values=[],this.import_self=-1,this.ics={}}clone(){let e=new Mt(this.num_args);return e.opcodes=this.opcodes,e.arg1=this.arg1,e.ref=this.ref,e.locals_size=this.locals_size,e.uses_arguments=this.uses_arguments,e}createLabel(e="label"){return":"+e+"_"+this.label_count++}setLabel(e){return this.labels[e]=this.opcodes.length}optimize(){this.transpile&&new Transpiler().transpile(this)}removeable(e){let s=this.labels;for(let i in s)if(s[i]===e)return!1;return!0}remove(e){let s=this.labels;for(let i in s){let r=s[i];if(r===e)return!1;r>e&&(this.labels[i]-=1)}return this.opcodes.splice(e,1),this.arg1.splice(e,1),this.ref.splice(e,1),!0}resolveLabels(){for(let e=0;e<this.opcodes.length;e++){let s=this.opcodes[e];if(s===E.JUMP||s===E.JUMPY||s===E.JUMPN||s===E.JUMPY_NOPOP||s===E.JUMPN_NOPOP)this.labels[this.arg1[e]]&&(this.arg1[e]=this.labels[this.arg1[e]]);else if(s===E.FORLOOP_CONTROL||s===E.FORLOOP_INIT||s===E.FORIN_CONTROL||s===E.FORIN_INIT){let i=this.arg1[e];i&&this.labels[i[1]]&&(i[1]=this.labels[i[1]])}}}OP(e,s,i=0){return this.opcodes.push(e),this.arg1.push(i),this.ref.push(s)}OP_INSERT(e,s,i=0,r){this.opcodes.splice(r,0,e),this.arg1.splice(r,0,i),this.ref.splice(r,0,s);let n=this.labels;for(let a in n)n[a]>=r&&(this.labels[a]+=1)}TYPE(e){return this.OP(E.TYPE,e)}VARIABLE_TYPE(e,s){return this.OP(E.VARIABLE_TYPE,s,e)}PROPERTY_TYPE(e){return this.OP(E.PROPERTY_TYPE,e)}LOAD_THIS(e){return this.OP(E.LOAD_THIS,e)}LOAD_GLOBAL(e){return this.OP(E.LOAD_GLOBAL,e)}LOAD_VALUE(e,s){return this.OP(E.LOAD_VALUE,s,e)}LOAD_LOCAL(e,s){return this.OP(E.LOAD_LOCAL,s,e)}LOAD_VARIABLE(e,s){return this.OP(E.LOAD_VARIABLE,s,e)}LOAD_LOCAL_OBJECT(e,s){return this.OP(E.LOAD_LOCAL_OBJECT,s,e)}LOAD_VARIABLE_OBJECT(e,s){return this.OP(E.LOAD_VARIABLE_OBJECT,s,e)}POP(e){return this.OP(E.POP,e)}LOAD_PROPERTY(e){return this.OP(E.LOAD_PROPERTY,e)}LOAD_PROPERTY_OBJECT(e){return this.OP(E.LOAD_PROPERTY_OBJECT,e)}CREATE_OBJECT(e){return this.OP(E.CREATE_OBJECT,e)}MAKE_OBJECT(e){return this.OP(E.MAKE_OBJECT,e)}CREATE_ARRAY(e){return this.OP(E.CREATE_ARRAY,e)}CREATE_CLASS(e,s){return this.OP(E.CREATE_CLASS,s,e)}UPDATE_CLASS(e,s){return this.OP(E.UPDATE_CLASS,s,e)}NEW_CALL(e,s){return this.OP(E.NEW_CALL,s,e)}ADD(e,s=0){return this.OP(E.ADD,e,s)}SUB(e,s=0){return this.OP(E.SUB,e,s)}MUL(e){return this.OP(E.MUL,e)}DIV(e){return this.OP(E.DIV,e)}MODULO(e){return this.OP(E.MODULO,e)}BINARY_AND(e){return this.OP(E.BINARY_AND,e)}BINARY_OR(e){return this.OP(E.BINARY_OR,e)}SHIFT_LEFT(e){return this.OP(E.SHIFT_LEFT,e)}SHIFT_RIGHT(e){return this.OP(E.SHIFT_RIGHT,e)}NEGATE(e){return this.OP(E.NEGATE,e)}LOAD_PROPERTY_ATOP(e){return this.OP(E.LOAD_PROPERTY_ATOP,e)}EQ(e){return this.OP(E.EQ,e)}NEQ(e){return this.OP(E.NEQ,e)}LT(e){return this.OP(E.LT,e)}GT(e){return this.OP(E.GT,e)}LTE(e){return this.OP(E.LTE,e)}GTE(e){return this.OP(E.GTE,e)}NOT(e){return this.OP(E.NOT,e)}FORLOOP_INIT(e,s){return this.OP(E.FORLOOP_INIT,s,e)}FORLOOP_CONTROL(e,s){return this.OP(E.FORLOOP_CONTROL,s,e)}FORIN_INIT(e,s){return this.OP(E.FORIN_INIT,s,e)}FORIN_CONTROL(e,s){return this.OP(E.FORIN_CONTROL,s,e)}JUMP(e,s){return this.OP(E.JUMP,s,e)}JUMPY(e,s){return this.OP(E.JUMPY,s,e)}JUMPN(e,s){return this.OP(E.JUMPN,s,e)}JUMPY_NOPOP(e,s){return this.OP(E.JUMPY_NOPOP,s,e)}JUMPN_NOPOP(e,s){return this.OP(E.JUMPN_NOPOP,s,e)}STORE_LOCAL(e,s){return this.OP(E.STORE_LOCAL,s,e)}STORE_VARIABLE(e,s){return this.OP(E.STORE_VARIABLE,s,e)}CREATE_PROPERTY(e){return this.OP(E.CREATE_PROPERTY,e)}STORE_PROPERTY(e){return this.OP(E.STORE_PROPERTY,e)}LOAD_ROUTINE(e,s){return this.OP(E.LOAD_ROUTINE,s,e)}FUNCTION_CALL(e,s){return this.OP(E.FUNCTION_CALL,s,e)}FUNCTION_APPLY_VARIABLE(e,s){return this.OP(E.FUNCTION_APPLY_VARIABLE,s,e)}FUNCTION_APPLY_PROPERTY(e,s){return this.OP(E.FUNCTION_APPLY_PROPERTY,s,e)}SUPER_CALL(e,s){return this.OP(E.SUPER_CALL,s,e)}RETURN(e){return this.OP(E.RETURN,e)}AFTER(e){return this.OP(E.AFTER,e)}EVERY(e){return this.OP(E.EVERY,e)}DO(e){return this.OP(E.DO,e)}SLEEP(e){return this.OP(E.SLEEP,e)}DELETE(e){return this.OP(E.DELETE,e)}UNARY_OP(e,s){return this.OP(E.UNARY_OP,s,e)}BINARY_OP(e,s){return this.OP(E.BINARY_OP,s,e)}toString(){let e="";for(let s=0;s<this.opcodes.length;s++){let i=this.opcodes[s];e+=E[i],this.arg1[s]!=null&&(e+=` ${this.arg1[s]}`),e+=`
|
|
141
|
+
`}return e}exportArg(e){return e==null?0:e instanceof Mt?e.export():typeof e=="function"?e.name:e}export(){let e=[];for(let s=0;s<this.arg1.length;s++)e[s]=this.exportArg(this.arg1[s]);return{num_args:this.num_args,ops:this.opcodes,args:e,import_refs:this.import_refs,import_values:this.import_values,import_self:this.import_self,locals_size:this.locals_size}}import(e){this.num_args=e.num_args,this.opcodes=e.ops,this.arg1=e.args,this.import_refs=e.import_refs,this.import_values=e.import_values,this.import_self=e.import_self,this.locals_size=e.locals_size;let s={line:0,column:0,start:0,length:0,index:0,tokenizer:{filename:"filename",input:""}},i={expression:{token:s},token:s};for(let r=0;r<this.opcodes.length;r++)this.opcodes[r]===100?this.arg1[r]=Compiler.predefined_unary_functions[this.arg1[r]]:this.opcodes[r]===101?this.arg1[r]=Compiler.predefined_binary_functions[this.arg1[r]]:typeof this.arg1[r]=="object"&&!Array.isArray(this.arg1[r])&&(this.arg1[r]=new Mt(0).import(this.arg1[r])),this.ref[r]=i;return this}},W=class{static{l(this,"Expression")}static{v(this,"Expression")}nowarning;nopop;constructor(){}},Le=class mt{static{l(this,"_Program")}static{v(this,"Program")}statements=[];static Field;static Variable;static Assignment;constructor(){this.statements=[]}add(e){return this.statements.push(e)}isAssignment(){return this.statements.length>0&&this.statements[this.statements.length-1]instanceof xe}static toString(e,s=0){let i,r,n,a,o;if(e instanceof K)return s===0&&e.source||"[function]";if(typeof e=="function")return"[native function]";if(typeof e=="string")return`"${e}"`;if(Array.isArray(e)){if(s>=1)return"[list]";for(a="[",i=0;i<e.length;i++)o=e[i],a+=mt.toString(o,s+1)+(i<e.length-1?",":"");return a+"]"}else if(typeof e=="object"&&e!==null){if(s>=1)return"[object]";for(a=`object
|
|
142
|
+
`,n="",i=1;i<=s;i++)n+=" ";for(r in e)o=e[r],a+=n+` ${r} = ${mt.toString(o,s+1)}
|
|
143
|
+
`;return a+n+"end"}return e||0}static Precedence={"^":21,"/":20,"*":19,"%":18,"+":17,"-":17,"<":16,"<=":15,">":14,">=":13,"==":12,"!=":11,"<<":10,">>":9,"&":8,"|":7,and:6,or:5};static CreateFieldAccess(e,s,i){return s instanceof Ae?(s.appendField(i),s):new Ae(e,s,[i])}static BuildOperations(e,s){let i,r,n,a,o,u;for(;e.length>1;){for(i=0;i<e.length-1&&(n=e[i],a=e[i+1],!(mt.Precedence[a.operation]<=mt.Precedence[n.operation]));)i++;o=s[i],u=s[i+1],r=new bt(e[i].token,e[i].operation,o,u),s.splice(i,2,r),e.splice(i,1)}return new bt(e[0].token,e[0].operation,s[0],s[1])}},xe=class extends W{static{l(this,"Assignment")}static{v(this,"Assignment")}token;field;expression;local;constructor(t,e,s,i){super(),this.token=t,this.field=e,this.expression=s,this.local=i}},or=class extends W{static{l(this,"SelfAssignment")}static{v(this,"SelfAssignment")}token;field;operation;expression;constructor(t,e,s,i){super(),this.token=t,this.field=e,this.operation=s,this.expression=i}},B=class extends W{static{l(this,"Value")}static{v(this,"Value")}token;type;value;static TYPE_NUMBER=1;static TYPE_STRING=2;static TYPE_ARRAY=3;static TYPE_OBJECT=4;static TYPE_FUNCTION=5;static TYPE_CLASS=6;constructor(t,e,s){super(),this.token=t,this.type=e,this.value=s}},se=class extends W{static{l(this,"Variable")}static{v(this,"Variable")}token;identifier;constructor(t,e){super(),this.token=t,this.identifier=e}},Ae=class extends W{static{l(this,"Field")}static{v(this,"Field")}token;expression;chain;constructor(t,e,s){super(),this.token=t,this.expression=e,this.chain=s,this.token=e instanceof W?e.token:t}appendField(t){return this.chain.push(t)}},bt=class extends W{static{l(this,"Operation")}static{v(this,"Operation")}token;operation;term1;term2;constructor(t,e,s,i){super(),this.token=t,this.operation=e,this.term1=s,this.term2=i}},hr=class extends W{static{l(this,"Negate")}static{v(this,"Negate")}token;expression;constructor(t,e){super(),this.token=t,this.expression=e}},lr=class extends W{static{l(this,"Not")}static{v(this,"Not")}token;expression;constructor(t,e){super(),this.token=t,this.expression=e}},Hs=class extends W{static{l(this,"Braced")}static{v(this,"Braced")}token;expression;constructor(t,e){super(),this.token=t,this.expression=e}},Et=class extends W{static{l(this,"Return")}static{v(this,"Return")}token;expression;constructor(t,e){super(),this.token=t,this.expression=e}},cr=class extends W{static{l(this,"Condition")}static{v(this,"Condition")}token;chain;constructor(t,e){super(),this.token=t,this.chain=e}},ur=class extends W{static{l(this,"For")}static{v(this,"For")}token;iterator;range_from;range_to;range_by;sequence;constructor(t,e,s,i,r,n){super(),this.token=t,this.iterator=e,this.range_from=s,this.range_to=i,this.range_by=r,this.sequence=n}},fr=class extends W{static{l(this,"ForIn")}static{v(this,"ForIn")}token;iterator;list;sequence;constructor(t,e,s,i){super(),this.token=t,this.iterator=e,this.list=s,this.sequence=i}},pr=class extends W{static{l(this,"While")}static{v(this,"While")}token;condition;sequence;constructor(t,e,s){super(),this.token=t,this.condition=e,this.sequence=s}},Nt=class extends W{static{l(this,"Break")}static{v(this,"Break")}token;nopop=!0;constructor(t){super(),this.token=t,this.nopop=!0}},Dt=class extends W{static{l(this,"Continue")}static{v(this,"Continue")}token;nopop=!0;constructor(t){super(),this.token=t,this.nopop=!0}},yt=class extends W{static{l(this,"Function2")}static{v(this,"Function")}token;args;sequence;source;constructor(t,e,s,i){super(),this.token=t,this.args=e,this.sequence=s,this.source="function"+t.tokenizer.input.substring(t.index,i.index+2)}},je=class extends W{static{l(this,"FunctionCall")}static{v(this,"FunctionCall")}token;expression;args;constructor(t,e,s){super(),this.token=t,this.expression=e,this.args=s}},dr=class extends W{static{l(this,"CreateObject")}static{v(this,"CreateObject")}token;fields;constructor(t,e){super(),this.token=t,this.fields=e}},Ks=class extends W{static{l(this,"CreateClass")}static{v(this,"CreateClass")}token;ext;fields;constructor(t,e,s){super(),this.token=t,this.ext=e,this.fields=s}},mr=class extends W{static{l(this,"NewCall")}static{v(this,"NewCall")}token;expression;constructor(t,e){super(),this.token=t,this.expression=e,this.expression instanceof je||(this.expression=new je(this.token,this.expression,[]))}},Js=class extends W{static{l(this,"After")}static{v(this,"After")}token;delay;sequence;multiplier;source;constructor(t,e,s,i,r){super(),this.token=t,this.delay=e,this.sequence=s,this.multiplier=r,this.source="after "+t.tokenizer.input.substring(t.index,i.index+2)}},Qs=class extends W{static{l(this,"Every")}static{v(this,"Every")}token;delay;sequence;multiplier;source;constructor(t,e,s,i,r){super(),this.token=t,this.delay=e,this.sequence=s,this.multiplier=r,this.source="every "+t.tokenizer.input.substring(t.index,i.index+2)}},Xs=class extends W{static{l(this,"Do")}static{v(this,"Do")}token;sequence;source;constructor(t,e,s){super(),this.token=t,this.sequence=e,this.source="do "+t.tokenizer.input.substring(t.index,s.index+2)}},gr=class extends W{static{l(this,"Sleep")}static{v(this,"Sleep")}token;delay;multiplier;constructor(t,e,s){super(),this.token=t,this.delay=e,this.multiplier=s}},_r=class extends W{static{l(this,"Delete")}static{v(this,"Delete")}token;field;constructor(t,e){super(),this.token=t,this.field=e}};Le.Field=Ae;Le.Variable=se;Le.Assignment=xe;var _a=class extends Error{static{l(this,"LootiScriptError")}static{v(this,"LootiScriptError")}file;line;column;stackTrace;constructor(t,e,s,i,r){super(t),this.file=e,this.line=s,this.column=i,this.stackTrace=r,this.name="LootiScriptError"}toString(){let t=`${this.name}: ${this.message}
|
|
144
|
+
`;return t+=` at ${this.file}:${this.line}:${this.column}
|
|
145
|
+
`,t}},ir=class extends _a{static{l(this,"LootiSyntaxError")}static{v(this,"LootiSyntaxError")}context;code;suggestions;related;constructor(t,e,s,i,r,n,a,o){super(t,e,s,i),this.context=r,this.code=n,this.suggestions=a,this.related=o,this.name="SyntaxError"}toString(){let t="";return this.code&&(t+=`[${this.code}] `),t+=`${this.name}: ${this.message}
|
|
146
|
+
`,t+=` at ${this.file}:${this.line}:${this.column}
|
|
147
|
+
`,this.context&&(t+=`
|
|
148
|
+
${this.context}
|
|
149
|
+
`),t}};function gt(t,e,s,i=3,r=1){let n=t.split(`
|
|
150
|
+
`),a=Math.max(0,e-i-1),o=Math.min(n.length-1,e+i-1),u=`
|
|
151
|
+
Source context:
|
|
152
|
+
`;for(let g=a;g<=o;g++){let y=g+1,O=y===e?">":" ",b=String(y).padStart(4," "),A=n[g]||"";if(u+=`${O} ${b} | ${A}
|
|
153
|
+
`,y===e){let j=" ".repeat(8+Math.max(0,s-1))+"^".repeat(Math.max(1,r));u+=`${j}
|
|
154
|
+
`}}return u}l(gt,"formatSourceContext");v(gt,"formatSourceContext");var Er=class _t{static{l(this,"_Parser")}static{v(this,"Parser")}input;filename;tokenizer;program;current_block;current;verbose;nesting;object_nesting;not_terminated;function_stack;api_reserved;warnings;unexpected_eof;error_info;last_function_call;static multipliers={millisecond:1,milliseconds:1,second:1e3,seconds:1e3,minute:6e4,minutes:6e4,hour:6e4*60,hours:6e4*60,day:6e4*60*24,days:6e4*60*24};constructor(e,s=""){this.input=e,this.filename=s,/^\s*\/\/\s*javascript\s*\n/.test(this.input)&&(this.input=`system.javascript("""
|
|
155
|
+
|
|
156
|
+
`+this.input.replace(/\\/g,"\\\\")+`
|
|
157
|
+
|
|
158
|
+
""")`),this.tokenizer=new ma(this.input,this.filename),this.program=new Le,this.current_block=[],this.current={line:1,column:1,tokenizer:this.tokenizer,type:0,value:"",start:0,length:0,index:0,is_binary_operator:!1},this.verbose=!1,this.nesting=0,this.object_nesting=0,this.not_terminated=[],this.function_stack=[],this.api_reserved={screen:!0,audio:!0,keyboard:!0,gamepad:!0,sprites:!0,sounds:!0,music:!0,assets:!0,asset_manager:!0,maps:!0,touch:!0,mouse:!0,fonts:!0,Sound:!0,Image:!0,Sprite:!0,Map:!0,system:!0,storage:!0,print:!0,random:!0,Function:!0,List:!0,Object:!0,String:!0,Number:!0,scenes:!0,scene:!0,route:!0,router:!0},this.warnings=[]}nextToken(){let e=this.tokenizer.next();if(e==null)throw this.unexpected_eof=!0,"Unexpected end of file";return this.current=e}nextTokenOptional(){let e=this.tokenizer.next();return e!=null&&(this.current=e),e}parse(){let e,s,i,r;try{for(this.warnings=[];;){if(s=this.parseLine(),s==null&&!this.tokenizer.finished())if(r=this.tokenizer.next(),r!=null&&r.reserved_keyword)if(r.value==="end"){let n=gt(this.input,r.line,r.column,3,3),a=["Remove this extra 'end' statement","Check if you're missing an opening statement (if, for, while, function)","Verify all blocks are properly matched"];return this.error_info={error:"Too many 'end' statements - no matching opening statement found",line:r.line,column:r.column,context:n,code:te.E1002,suggestions:a}}else this.error(`Misuse of reserved keyword: '${r.value}'`);else this.error("Unexpected data");if(s===null)break;this.current_block.push(s),this.program.add(s),this.verbose&&console.info(s)}return this}catch(n){if(e=n,e instanceof ir)return this.error_info={error:e.message,line:e.line,column:e.column,context:e.context};if(this.not_terminated.length>0&&e==="Unexpected end of file"){i=this.not_terminated[this.not_terminated.length-1];let a=null,o=null,u=null;if(i.value==="function")for(let m=this.function_stack.length-1;m>=0;m--){let j=this.function_stack[m];if(j.token===i){a=j.name,o=j.line,u=j.column;break}}let g=typeof i.value=="string"?i.value.length:1,y=gt(i.tokenizer.input,i.line,i.column,3,g),O,b=[],A;return i.value==="function"&&a?(O=`Function '${a}' started at line ${o} is not closed`,b=[`Add 'end' after the last statement to close function '${a}'`,"Check if you have an extra 'end' statement somewhere","Verify all nested blocks (if, for, while) are properly closed"],A={file:this.filename,line:o,column:u,message:`Function '${a}' started here`}):(O=`Unterminated '${i.value}' ; no matching 'end' found`,b=[`Add 'end' to close the '${i.value}' statement`,"Check if you have nested blocks that need to be closed first"]),this.error_info={error:O,line:i.line,column:i.column,context:y,code:te.E1001,suggestions:b,related:A}}else{let a=gt(this.input,this.current.line,this.current.column,3,1);return this.error_info={error:typeof e=="string"?e:e.message||String(e),line:this.current.line,column:this.current.column,context:a,code:te.E1004}}}}parseLine(){let e=this.nextTokenOptional();if(e==null)return null;switch(e.type){case d.TYPE_RETURN:return new Et(e,this.parseExpression());case d.TYPE_BREAK:return new Nt(e);case d.TYPE_CONTINUE:return new Dt(e);case d.TYPE_LOCAL:return this.parseLocalAssignment(e);default:return this.tokenizer.pushBack(e),this.parseExpression()}}parseExpression(e,s=!1){let i,r;if(r=this.parseExpressionStart(),r==null)return null;for(;;){if(i=this.parseExpressionSuffix(r,e),i==null)return r;if(s&&i instanceof je)return i;r=i}}assertExpression(e,s=!1){let i=this.parseExpression(e,s);if(i==null)throw"Expression expected";return i}parseExpressionSuffix(e,s){let i,r,n=this.nextTokenOptional();if(n==null)return s==="self"?e:null;switch(n.type){case d.TYPE_DOT:return e instanceof B&&e.type===B.TYPE_NUMBER?(this.tokenizer.pushBack(n),null):(this.tokenizer.changeNumberToIdentifier(),r=this.assertBroadIdentifier("Expected identifier"),Le.CreateFieldAccess(n,e,new B(r,B.TYPE_STRING,r.value)));case d.TYPE_OPEN_BRACKET:return i=this.assertExpression(),this.assert(d.TYPE_CLOSED_BRACKET,"Expected ']'"),Le.CreateFieldAccess(n,e,i);case d.TYPE_OPEN_BRACE:return this.parseFunctionCall(n,e);case d.TYPE_EQUALS:return this.parseAssignment(n,e);case d.TYPE_PLUS_EQUALS:return this.parseSelfAssignment(n,e,n.type);case d.TYPE_MINUS_EQUALS:return this.parseSelfAssignment(n,e,n.type);case d.TYPE_MULTIPLY_EQUALS:return this.parseSelfAssignment(n,e,n.type);case d.TYPE_DIVIDE_EQUALS:return this.parseSelfAssignment(n,e,n.type);case d.TYPE_MODULO_EQUALS:case d.TYPE_AND_EQUALS:case d.TYPE_OR_EQUALS:return this.parseSelfAssignment(n,e,n.type);default:return s==="self"?(this.tokenizer.pushBack(n),e):n.is_binary_operator&&s!=="noop"?this.parseBinaryOperation(n,e):(this.tokenizer.pushBack(n),null)}}parseExpressionStart(){let e,s=this.nextTokenOptional();if(s==null)return null;switch(s.type){case d.TYPE_IDENTIFIER:return new se(s,s.value);case d.TYPE_NUMBER:return this.parseNumberExpression(s);case d.TYPE_PLUS:return this.assertExpression();case d.TYPE_MINUS:return this.parseExpressionSuffix(new hr(s,this.assertExpression("noop")),"self");case d.TYPE_NOT:return this.parseExpressionSuffix(new lr(s,this.assertExpression("noop")),"self");case d.TYPE_STRING:return this.parseStringExpression(s);case d.TYPE_TEMPLATE:return this.parseTemplate(s);case d.TYPE_IF:return this.parseIf(s);case d.TYPE_FOR:return this.parseFor(s);case d.TYPE_WHILE:return this.parseWhile(s);case d.TYPE_OPEN_BRACE:return this.parseBracedExpression(s);case d.TYPE_OPEN_BRACKET:return this.parseArray(s);case d.TYPE_FUNCTION:return this.parseFunction(s);case d.TYPE_OBJECT:return this.parseObject(s);case d.TYPE_CLASS:return this.parseClass(s);case d.TYPE_NEW:return this.parseNew(s);case d.TYPE_DOT:if(e=this.assert(d.TYPE_NUMBER,"malformed number"),!Number.isInteger(e.value))throw"malformed number";return new B(s,B.TYPE_NUMBER,Number.parseFloat(`.${e.string_value}`));case d.TYPE_AFTER:return this.parseAfter(s);case d.TYPE_EVERY:return this.parseEvery(s);case d.TYPE_DO:return this.parseDo(s);case d.TYPE_SLEEP:return this.parseSleep(s);case d.TYPE_DELETE:return this.parseDelete(s);default:return this.tokenizer.pushBack(s),null}}parseNumberExpression(e){return new B(e,B.TYPE_NUMBER,e.value)}parseStringExpression(e){let s=this.nextTokenOptional();return s!=null&&this.tokenizer.pushBack(s),new B(e,B.TYPE_STRING,e.value)}parseArray(e){let s=[];for(;;){let i=this.nextToken();if(i.type===d.TYPE_CLOSED_BRACKET)return new B(e,B.TYPE_ARRAY,s);i.type===d.TYPE_COMMA||(this.tokenizer.pushBack(i),s.push(this.assertExpression()))}}parseBinaryOperation(e,s){let i=[{token:e,operation:e.value}],r=[s];for(r.push(this.assertExpression("noop"));;){let n=this.nextTokenOptional();if(n==null)break;if(!n.is_binary_operator){this.tokenizer.pushBack(n);break}i.push({token:n,operation:n.value}),r.push(this.assertExpression("noop"))}return Le.BuildOperations(i,r)}parseAssignment(e,s){let i;if(!(s instanceof se||s instanceof Ae))throw"Expected variable identifier or property";this.object_nesting===0&&s instanceof se&&this.api_reserved[s.identifier]&&this.warnings.push({type:"assigning_api_variable",identifier:s.identifier,line:e.line,column:e.column});let r=this.tokenizer.peek(),n=null;s instanceof se&&(n=s.identifier),r&&(r.type,d.TYPE_FUNCTION);let a=this.assertExpression();if(a instanceof yt&&n&&this.function_stack.length>0){let o=a.token;for(let u=this.function_stack.length-1;u>=0;u--){let g=this.function_stack[u];if(g.token===o&&g.name==="anonymous"){g.name=n;break}}}return s instanceof Ae?(this.object_nesting+=1,i=new xe(e,s,a,!1),this.object_nesting-=1):i=new xe(e,s,a,!1),i}parseSelfAssignment(e,s,i){if(!(s instanceof se||s instanceof Ae))throw"Expected variable identifier or property";let r;return i===d.TYPE_PLUS_EQUALS?r="+=":i===d.TYPE_MINUS_EQUALS?r="-=":i===d.TYPE_MULTIPLY_EQUALS?r="*=":i===d.TYPE_DIVIDE_EQUALS?r="/=":i===d.TYPE_MODULO_EQUALS?r="%=":i===d.TYPE_AND_EQUALS?r="&=":i===d.TYPE_OR_EQUALS?r="|=":r=String(i),new or(e,s,r,this.assertExpression())}parseLocalAssignment(e){let s=this.assert(d.TYPE_IDENTIFIER,"Expected identifier");return this.parseOptionalType(),this.assert(d.TYPE_EQUALS,"Expected '='"),new xe(e,new se(s,s.value),this.assertExpression(),!0)}parseBracedExpression(e){if(this.current.type===d.TYPE_CLOSED_BRACE){let r=this.nextToken(),n=this.nextToken();return n.type===d.TYPE_ARROW?this.parseArrowFunction(n,[]):(this.tokenizer.pushBack(n),this.current=r,this.error("Unexpected ')'"))}let s=this.assertExpression();this.parseOptionalType();let i=this.nextToken();if(i.type===d.TYPE_CLOSED_BRACE){let r=this.nextToken();return r.type===d.TYPE_ARROW?this.parseArrowFunction(r,[s]):(this.tokenizer.pushBack(r),this.current=i,new Hs(e,s))}else if(i.type===d.TYPE_COMMA){let r=[s];for(;;){r.push(this.assertExpression()),this.parseOptionalType();let a=this.nextToken();if(a.type===d.TYPE_CLOSED_BRACE)break;if(a.type!==d.TYPE_COMMA)return this.error("Expected ',' or ')'")}let n=this.nextToken();return n.type===d.TYPE_ARROW?this.parseArrowFunction(n,r):this.error("Expected '=>' after parameter list")}else return this.error("missing closing parenthese")}parseArrowFunction(e,s){let i=[];for(let a of s)if(a instanceof se)i.push({name:a.identifier,default:void 0});else throw this.error("Invalid argument in arrow function");let r=[],n=this.parseLine();return n&&(n instanceof B||n instanceof se||n instanceof bt||n instanceof je||n instanceof xe||n instanceof Hs?r.push(new Et(e,n)):r.push(n)),new yt(e,i,r,e)}parseFunctionCall(e,s){let i=[];for(this.last_function_call=new je(e,s,i);;){let r=this.nextTokenOptional();if(r==null)return this.error("missing closing parenthese");if(r.type===d.TYPE_CLOSED_BRACE)return new je(r,s,i);r.type===d.TYPE_COMMA||(this.tokenizer.pushBack(r),i.push(this.assertExpression()))}}addTerminable(e){return this.not_terminated.push(e)}endTerminable(){this.not_terminated.length>0&&this.not_terminated.splice(this.not_terminated.length-1,1)}parseFunction(e){let s,i=this.parseFunctionArgs(),r=[];this.nesting+=1;let n={name:"anonymous",line:e.line,column:e.column,token:e};this.function_stack.push(n),this.addTerminable(e);try{for(;;){let a=this.nextToken();if(a.type===d.TYPE_END)return this.nesting-=1,this.endTerminable(),this.function_stack.pop(),new yt(e,i,r,a);this.tokenizer.pushBack(a),s=this.parseLine(),s!=null?r.push(s):this.error("Unexpected data while parsing function")}}catch(a){throw this.function_stack.length>0&&this.function_stack[this.function_stack.length-1].token===e&&this.function_stack.pop(),a}}parseFunctionArgs(){let e=[],s=null,i=this.nextToken();if(i.type!==d.TYPE_OPEN_BRACE)return this.error("Expected opening parenthese");for(;;){if(i=this.nextToken(),i.type===d.TYPE_CLOSED_BRACE)return e;if(i.type===d.TYPE_COMMA)s=null;else if(i.type===d.TYPE_EQUALS&&s==="argument"){let r=this.assertExpression();e.length>0&&(e[e.length-1].default=r)}else if(i.type===d.TYPE_IDENTIFIER)s="argument",e.push({name:i.value}),this.parseOptionalType();else return this.error("Unexpected token")}}warningAssignmentCondition(e){e instanceof xe&&this.warnings.push({type:"assignment_as_condition",line:e.token.line,column:e.token.column})}parseIf(e){let s,i,r=[],n={condition:this.assertExpression(),sequence:[]};if(this.addTerminable(e),this.warningAssignmentCondition(n.condition),i=this.nextToken(),i.type!==d.TYPE_THEN)return this.error("Expected 'then'");for(;;)if(i=this.nextToken(),i.type===d.TYPE_ELSIF)r.push(n),n={condition:this.assertExpression(),sequence:[]},this.warningAssignmentCondition(n.condition),this.assert(d.TYPE_THEN,"Expected 'then'");else if(i.type===d.TYPE_ELSE)n.else=[];else{if(i.type===d.TYPE_END)return r.push(n),this.endTerminable(),new cr(e,r);{this.tokenizer.pushBack(i);let a=this.parseLine();if(a==null)throw Error("Unexpected data while parsing if");s=a,n.else!=null?n.else.push(s):n.sequence.push(s)}}}assert(e,s){let i=this.nextToken();if(i.type!==e)throw s;return i}assertBroadIdentifier(e){let s=this.nextToken();if(s.type!==d.TYPE_IDENTIFIER&&s.reserved_keyword&&(s.type=d.TYPE_IDENTIFIER),s.type!==d.TYPE_IDENTIFIER)throw e;return s}error(e){let s=this.current,i=gt(s.tokenizer.input,s.line,s.column,2);throw new ir(e,s.tokenizer.filename,s.line,s.column,i)}parseOptionalType(){let e=this.nextTokenOptional();if(e!=null)if(e.type===d.TYPE_COLON)for(this.assert(d.TYPE_IDENTIFIER,"Expected type identifier");;)if(e=this.nextTokenOptional(),e&&e.type===d.TYPE_OPEN_BRACKET)this.assert(d.TYPE_CLOSED_BRACKET,"Expected ']'");else{e&&this.tokenizer.pushBack(e);break}else this.tokenizer.pushBack(e)}parseFor(e){let s,i,r,n,a,o=this.assertExpression();if(o instanceof xe){r=o.expression;let u=o.field;return a=this.nextToken(),a.type!==d.TYPE_TO?this.error("Expected 'to'"):(n=this.assertExpression(),a=this.nextToken(),a.type===d.TYPE_BY?i=this.assertExpression():(i=null,this.tokenizer.pushBack(a)),u instanceof se?new ur(e,u.identifier,r,n,i,this.parseSequence(e)):this.error("Malformed for loop"))}else return o instanceof se?(this.assert(d.TYPE_IN,"Error expected keyword 'in'"),s=this.assertExpression(),new fr(e,o.identifier,s,this.parseSequence(e))):this.error("Malformed for loop")}parseWhile(e){let s=this.assertExpression();return new pr(e,s,this.parseSequence(e))}parseSequence(e){let s,i=[];for(e!=null&&this.addTerminable(e),this.nesting+=1;;){let r=this.nextToken();if(r.type===d.TYPE_END)return e!=null&&this.endTerminable(),this.nesting-=1,i;if(this.tokenizer.pushBack(r),s=this.parseLine(),s==null)throw this.error("Unexpected data");i.push(s)}}parseObject(e){let s,i=[];for(this.nesting+=1,this.object_nesting+=1,this.addTerminable(e);;){let r=this.nextToken();if(r.type===d.TYPE_END)return this.nesting-=1,this.object_nesting-=1,this.endTerminable(),new dr(e,i);if(r.type!==d.TYPE_IDENTIFIER&&r.reserved_keyword&&(r.type=d.TYPE_IDENTIFIER),r.type===d.TYPE_STRING&&(r.type=d.TYPE_IDENTIFIER),r.type===d.TYPE_IDENTIFIER)this.assert(d.TYPE_EQUALS,"Expected '='"),s=this.assertExpression(),i.push({field:r.value,value:s});else return this.error("Malformed object")}}parseClass(e){let s,i=null,r=[];this.nesting+=1,this.object_nesting+=1,this.addTerminable(e);let n=this.nextToken();for(n.type===d.TYPE_EXTENDS&&(i=this.assertExpression(),n=this.nextToken());;){if(n.type===d.TYPE_END)return this.nesting-=1,this.object_nesting-=1,this.endTerminable(),new Ks(e,i,r);if(n.type!==d.TYPE_IDENTIFIER&&n.reserved_keyword&&(n.type=d.TYPE_IDENTIFIER),n.type===d.TYPE_STRING&&(n.type=d.TYPE_IDENTIFIER),n.type===d.TYPE_IDENTIFIER)this.assert(d.TYPE_EQUALS,"Expected '='"),s=this.assertExpression(),r.push({field:n.value,value:s});else return this.error("Malformed object");n=this.nextToken()}}parseNew(e){let s=this.assertExpression(null,!0);return new mr(e,s)}tryParseMultiplier(){let e=null,s=this.nextToken();return s.type===d.TYPE_IDENTIFIER&&_t.multipliers[s.value]&&(e=_t.multipliers[s.value],s=this.nextToken()),{multiplier:e,token:s}}parseBlock(e){let s=[];for(;;){let i=this.nextToken();if(i.type===d.TYPE_END)return this.nesting-=1,this.endTerminable(),{sequence:s,endToken:i};this.tokenizer.pushBack(i);let r=this.parseLine();r!=null?s.push(r):this.error(`Unexpected data while parsing ${e}`)}}parseAfter(e){this.nesting+=1,this.addTerminable(e);let s=this.assertExpression(),{multiplier:i,token:r}=this.tryParseMultiplier();if(r==null||r.type!==d.TYPE_DO)return this.error("Expected keyword 'do'");let{sequence:n,endToken:a}=this.parseBlock("after");return new Js(e,s,n,a,i)}parseEvery(e){this.nesting+=1,this.addTerminable(e);let s=this.assertExpression(),{multiplier:i,token:r}=this.tryParseMultiplier();if(r==null||r.type!==d.TYPE_DO)return this.error("Expected keyword 'do'");let{sequence:n,endToken:a}=this.parseBlock("every");return new Qs(e,s,n,a,i)}parseDo(e){this.nesting+=1,this.addTerminable(e);let{sequence:s,endToken:i}=this.parseBlock("do");return new Xs(e,s,i)}parseSleep(e){let s=null,i=this.assertExpression(),r=this.nextToken();return r!=null&&(r.type===d.TYPE_IDENTIFIER&&_t.multipliers[r.value]?s=_t.multipliers[r.value]:this.tokenizer.pushBack(r)),new gr(e,i,s)}parseDelete(e){let s=this.parseExpression();return s==null||!(s instanceof se||s instanceof Ae)?this.error("expecting variable name or property access after keyword `delete`"):new _r(e,s)}parseTemplate(e){let s=e.value,i=0,r=[];for(;i<s.length;){let a=s.indexOf("${",i);if(a===-1){i<s.length&&r.push(new B(e,B.TYPE_STRING,s.substring(i)));break}a>i&&r.push(new B(e,B.TYPE_STRING,s.substring(i,a)));let o=1,u=a+2,g=!1,y="";for(;u<s.length&&o>0;){let m=s[u];g?m===y&&s[u-1]!=="\\"&&(g=!1):m==='"'||m==="'"||m==="`"?(g=!0,y=m):m==="{"?o++:m==="}"&&o--,o>0&&u++}if(o>0)throw this.error("Unclosed template interpolation");let O=s.substring(a+2,u),A=new this.constructor(O,e.tokenizer.filename).parseExpression();A&&r.push(A),i=u+1}if(r.length===0)return new B(e,B.TYPE_STRING,"");let n=r[0];for(let a=1;a<r.length;a++)n=new bt(e,"+",n,r[a]);return n}};function ei(t,e,s){let i=t.main_thread.processor.constructor,r=new i(t);return function(){let n=Math.min(e.num_args,arguments.length);r.load(e);for(let a=0;a<=n-1;a+=1)r.stack[++r.stack_index]=arguments[a]||0;if(r.stack[++r.stack_index]=arguments.length,e.uses_arguments){let a=[...arguments];for(let o=0;o<=a.length-1;o+=1)a[o]==null&&(a[o]=0);r.stack[++r.stack_index]=a}return r.run(s)}}l(ei,"routineAsFunction");v(ei,"routineAsFunction");function Vt(t,e,s){let i=t.main_thread.processor.constructor,r=new i(t);return function(){let n=e.num_args;r.load(e),r.object=this;for(let a=0;a<=n-1;a+=1)r.stack[++r.stack_index]=arguments[a]||0;if(r.stack[++r.stack_index]=arguments.length,e.uses_arguments){let a=[...arguments];for(let o=0;o<=a.length-1;o+=1)a[o]==null&&(a[o]=0);r.stack[++r.stack_index]=a}return r.run(s),r.stack[0]}}l(Vt,"routineAsApplicableFunction");v(Vt,"routineAsApplicableFunction");function yr(t,e,s){return e instanceof K?ei(t,e,s):e??0}l(yr,"argToNative");v(yr,"argToNative");var Be={UNINITIALIZED:0,MONOMORPHIC:1,POLYMORPHIC:2,MEGAMORPHIC:3},br=1e3,Bt=[],jt=[];function Tr(){if(Bt.length>0){let t=Bt.pop();return t.length=0,t}return[]}l(Tr,"getPooledArray");v(Tr,"getPooledArray");function vr(t){Bt.length<br&&Bt.push(t)}l(vr,"recycleArray");v(vr,"recycleArray");function Ar(){return jt.length>0?jt.pop():{}}l(Ar,"getPooledObject");v(Ar,"getPooledObject");function Pr(t){if(jt.length<br){for(let e in t)delete t[e];jt.push(t)}}l(Pr,"recycleObject");v(Pr,"recycleObject");function ti(t,e,s){return e instanceof K?(e.as_function==null&&(e.as_function=Vt(t,e,s)),e.as_function):typeof e=="function"?e:null}l(ti,"resolveCallable");v(ti,"resolveCallable");function Ve(t,e,s,i,r,n,a){let o;if(Array.isArray(i))o=e.global.List;else if(typeof i=="string"){if(a&&isFinite(i)){let g=a(i,r);return isFinite(g)?g:0}o=e.global.String}else o=i;let u=o[s];for(;u==null&&o.class!=null;)o=o.class,u=o[s];if(u==null&&(u=e.global.Object[s]),u!=null){let g=ti(t,u,e);if(g)return g.call(e.global,i,r,n)}return 0}l(Ve,"dispatchBinaryOp");v(Ve,"dispatchBinaryOp");function Ft(t,e,s,i,r){return Ve(t,e,"+",s,i,r)}l(Ft,"operatorAdd");v(Ft,"operatorAdd");function Ut(t,e,s,i,r){return Ve(t,e,"-",s,i,r,(n,a)=>n-a)}l(Ut,"operatorSub");v(Ut,"operatorSub");function Yt(t,e,s,i,r){return Ve(t,e,"*",s,i,r,(n,a)=>n*a)}l(Yt,"operatorMul");v(Yt,"operatorMul");function Zs(t,e,s,i,r){return Ve(t,e,"/",s,i,r,(n,a)=>n/a)}l(Zs,"operatorDiv");v(Zs,"operatorDiv");function Or(t,e,s,i,r){return Ve(t,e,"&",s,i,r,(n,a)=>n&a)}l(Or,"operatorBand");v(Or,"operatorBand");function kr(t,e,s,i,r){return Ve(t,e,"|",s,i,r,(n,a)=>n|a)}l(kr,"operatorBor");v(kr,"operatorBor");function Sr(t,e,s,i){let r;if(Array.isArray(s))r=e.global.List;else if(typeof s=="string"){if(isFinite(s)){let a=s%i;return isFinite(a)?a:0}r=e.global.String}else r=s;let n=r["%"];for(;n==null&&r.class!=null;)r=r.class,n=r["%"];return n==null&&(n=e.global.Object["%"]),n!=null&&n instanceof K?(n.as_function==null&&(n.as_function=Vt(t,n,e)),n=n.as_function,n.call(e.global,s,i)):0}l(Sr,"operatorModulo");v(Sr,"operatorModulo");function xr(t,e,s){let i;if(Array.isArray(s))i=e.global.List;else if(typeof s=="string"){if(isFinite(s))return-s;i=e.global.String}else i=s;let r=i["-"];for(;r==null&&i.class!=null;)i=i.class,r=i["-"];if(r==null&&(r=e.global.Object["-"]),r!=null){let n=ti(t,r,e);if(n)return n.call(e.global,0,s)}return 0}l(xr,"operatorNegate");v(xr,"operatorNegate");var Lr=class{static{l(this,"Processor")}static{v(this,"Processor")}runner;routine;locals;stack;call_stack;call_stack_frames;log;time_limit;done;local_index;stack_index;op_index;call_stack_index;global;object;locals_offset;call_super;call_supername;metrics;profilingEnabled;_argv=[];constructor(t){this.runner=t,this.locals=[],this.stack=[],this.call_stack=[],this.call_stack_frames=[],this.log=!1,this.time_limit=Number.POSITIVE_INFINITY,this.done=!0,this.local_index=0,this.stack_index=-1,this.op_index=0,this.call_stack_index=0,this.global=null,this.object=null,this.locals_offset=0,this.call_super=null,this.call_supername="",this.metrics={ops:0,allocations:0,cacheHits:0,cacheMisses:0},this.profilingEnabled=!1}reportNativeError(t){typeof this.runner?.reportNativeError=="function"?this.runner.reportNativeError(t):console.error(t)}getArray(){return Tr()}recycleArray(t){vr(t)}getObject(){return Ar()}recycleObject(t){Pr(t)}load(t){this.routine=t,this.resetState()}resetState(){this.local_index=0,this.stack_index=-1,this.op_index=0,this.call_stack_index=0,this.call_stack_frames=[],this.global=null,this.object=this.routine.object||null,this.locals_offset=0,this.call_super=null,this.call_supername="",this.done=!1}generateStackTrace(){return[...this.call_stack_frames].reverse()}formatStackTrace(){let t=this.generateStackTrace();return t.length===0?"":t.map(e=>` at ${e.functionName} (${e.file}:${e.line}:${e.column})`).join(`
|
|
159
|
+
`)}resolveParentClass(t,e){if(t.class!=null&&typeof t.class=="string"){if(e[t.class]!=null&&(t.class=e[t.class],typeof t.class!="string"))return this.resolveParentClass(t.class,e)}else if(t.class!=null&&typeof t.class!="string")return this.resolveParentClass(t.class,e)}applyFunction(t){}resolvePropertyIC(t,e,s){if(t==null)return null;if(s.state===Be.MONOMORPHIC){let i=t.class||t.constructor;if(i===s.shape)return s.hits++,t[e];s.misses++,s.state=Be.POLYMORPHIC,s.shapes=[s.shape,i],s.offsets=[0,0]}else if(s.state===Be.POLYMORPHIC){let i=t.class||t.constructor;if(s.shapes&&s.shapes.length<4){for(let r=0;r<s.shapes.length;r++)if(s.shapes[r]===i)return s.hits++,t[e];s.shapes.push(i),s.misses++}else s.state=Be.MEGAMORPHIC}return s.state===Be.UNINITIALIZED&&(s.state=Be.MONOMORPHIC,s.shape=t.class||t.constructor,s.property=e,s.hits=1),t[e]}routineAsFunction(t,e){return ei(this.runner,t,e)}routineAsApplicableFunction(t,e){return Vt(this.runner,t,e)}argToNative(t,e){return yr(this.runner,t,e)}run(t){let e,s,i,r,n,a,o,u,g,y,O,b,A,m,j,J,D,C,X,q,V,Ee,Re,he,Z,$e,Ge,ze,Pe,Oe,ee,De,$,Y,de,ue,le,ye,M,ke,S,F,me,f,ae,es,ts,ss,Pt,We,pi,di,mi,gi,_i,is,qe,Ei,yi,bi,Ce,Fe,L,rs,Ti,ns,c,h,oe,He,k,as,p,Ie,os;L=this.routine,ae=this.routine.opcodes,s=this.routine.arg1,ee=ae.length,f=this.op_index,c=this.stack,h=this.stack_index,$=this.locals,De=this.local_index,D=this.global||t.global,F=this.object||D,o=this.call_stack,u=this.call_stack_index,g=this.call_super||D,y=this.call_supername||"",Y=this.locals_offset,me=0,Fe=-1;let Ot=this.profilingEnabled;for(;f<ee;)switch(Ot&&this.metrics.ops++,ae[f]){case 1:switch(p=c[h],typeof p){case"number":c[h]="number";break;case"string":c[h]="string";break;case"function":c[h]="function";break;case"object":Array.isArray(p)?c[h]="list":p instanceof K?c[h]="function":c[h]="object"}f++;break;case 2:if(p=F[s[f]],p==null&&(p=D[s[f]]),p==null)c[++h]=0;else switch(typeof p){case"number":c[++h]="number";break;case"string":c[++h]="string";break;case"function":c[++h]="function";break;default:Array.isArray(p)?c[++h]="list":p instanceof K?c[++h]="function":c[++h]="object"}f++;break;case 3:if(p=c[h-1][c[h]],p==null)c[--h]=0;else switch(typeof p){case"number":c[--h]="number";break;case"string":c[--h]="string";break;case"function":c[--h]="function";break;default:Array.isArray(p)?c[--h]="list":p instanceof K?c[--h]="function":c[--h]="object"}f++;break;case 4:c[++h]=L.import_values[s[f++]];break;case 5:c[++h]=F,f++;break;case 6:c[++h]=D,f++;break;case 10:c[++h]=s[f++];break;case 11:c[++h]=$[Y+s[f++]];break;case 12:if(M=s[f],p=F[M],p==null&&F.class!=null)for(S=F;p==null&&S.class!=null;)S=S.class,p=S[M];p==null&&(p=D[M]),p==null&&!L.ref[f].nowarning&&(k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.using_undefined_variable[V]||(t.warnings.using_undefined_variable[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:M})),c[++h]=p??0,f++;break;case 13:ke=$[Y+s[f]],typeof ke!="object"&&(ke=$[Y+s[f]]={},k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.assigning_field_to_undefined[V]||(t.warnings.assigning_field_to_undefined[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:k.value})),c[++h]=ke,f++;break;case 14:for(M=s[f],S=F,p=S[M];p==null&&S.class!=null;)S=S.class,p=S[M];p==null&&D[M]!=null&&(S=D,p=D[M]),(p==null||typeof p!="object")&&(p=S[M]={},k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.assigning_field_to_undefined[V]||(t.warnings.assigning_field_to_undefined[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:s[f]})),c[++h]=p,f++;break;case 15:h--,f++;break;case 16:{S=c[h-1],M=c[h];let R=L.ics[f];if(R||(R=L.ics[f]={state:Be.UNINITIALIZED,hits:0,misses:0,property:M}),p=this.resolvePropertyIC(S,M,R),p==null&&S.class!=null){let kt=S;for(;p==null&&kt.class!=null;)kt=kt.class,p=kt[M]}p==null&&(p=0,L.ref[f].nowarning||(L.ref[f].nowarning=!0,Array.isArray(S)||(k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.using_undefined_variable[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:M}))),c[--h]=p,f++;break}case 17:p=c[h-1][c[h]],typeof p!="object"&&(p=c[h-1][c[h]]={},k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.assigning_field_to_undefined[V]||(t.warnings.assigning_field_to_undefined[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:c[h]})),c[--h]=p,f++;break;case 18:Ot&&this.metrics.allocations++,c[++h]=this.getObject(),f++;break;case 19:typeof c[h]!="object"&&(Ot&&this.metrics.allocations++,c[h]=this.getObject()),f++;break;case 20:Ot&&this.metrics.allocations++,c[++h]=this.getArray(),f++;break;case 21:$[Y+s[f]]=c[h],f++;break;case 22:$[Y+s[f]]=c[h--],f++;break;case 23:F[s[f++]]=c[h];break;case 24:S=c[h-2],J=c[h-1],S[J]=c[h],h-=2,f++;break;case 25:S=c[h-2],J=c[h-1],c[h-2]=S[J]=c[h],h-=2,f++;break;case 26:S=c[h-1],J=c[h],delete S[J],c[h-=1]=0,f++;break;case 27:if(M=s[f],F[M]!=null&&typeof F[M]=="object"){S=F[M],ns=c[h];for(ze in ns)Ie=ns[ze],S[ze]=Ie}else F[M]=c[h];f++;break;case 28:Ce={},ts=c[h],ts?Ce.class=ts:s[f]&&(Ce.class=s[f]),c[h]=Ce,f++;break;case 29:if(a=c[h],i=s[f],typeof a=="function"){for(e=[],C=$e=0,pi=i-1;$e<=pi;C=$e+=1)e.push(c[h-i+C]);h-=i,c[h-1]=new a(...e),f++}else{for(this.resolveParentClass(a,D),Ce={class:a},O=a.constructor;!O&&a.class!=null;)a=a.class,O=a.constructor;if(O!=null&&O instanceof K){if(c[h-i-1]=Ce,h--,b=o[u]||(o[u]={}),u++,b.routine=L,b.object=F,b.super=g,b.supername=y,b.op_index=f+1,Y+=L.locals_size,L=O,ae=O.opcodes,s=O.arg1,f=0,ee=ae.length,F=Ce,g=a,y="constructor",L.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<O.num_args)for(C=Ge=i+1,_i=O.num_args;Ge<=_i;C=Ge+=1)c[++h]=0;else i>O.num_args&&(h-=i-O.num_args);c[++h]=i,L.uses_arguments&&(c[++h]=r)}else h-=i,c[h-1]=Ce,f++}break;case 30:n=c[h--],e=c[h],typeof e=="number"?(e+=n,c[h]=isFinite(e)||typeof n=="string"?e:0):c[h]=Ft(this.runner,t,e,n,s[f]),f++;break;case 31:n=c[h--],e=c[h],typeof e=="number"?(e-=n,c[h]=isFinite(e)?e:0):c[h]=Ut(this.runner,t,e,n,s[f]),f++;break;case 32:n=c[h--],e=c[h],typeof e=="number"?(e*=n,c[h]=isFinite(e)?e:0):c[h]=Yt(this.runner,t,e,n,0),f++;break;case 33:n=c[h--],e=c[h],typeof e=="number"?(e/=n,c[h]=isFinite(e)?e:0):c[h]=Zs(this.runner,t,e,n,0),f++;break;case 34:n=c[h--],e=c[h],typeof e=="number"&&typeof n=="number"?(e%=n,c[h]=isFinite(e)?e:0):c[h]=Sr(this.runner,t,e,n),f++;break;case 35:n=c[h--],e=c[h],typeof e=="number"?(e&=n,c[h]=isFinite(e)?e:0):c[h]=Or(this.runner,t,e,n,0),f++;break;case 36:n=c[h--],e=c[h],typeof e=="number"?(e|=n,c[h]=isFinite(e)?e:0):c[h]=kr(this.runner,t,e,n,0),f++;break;case 37:p=c[h-1]<<c[h],c[--h]=isFinite(p)?p:0,f++;break;case 38:p=c[h-1]>>c[h],c[--h]=isFinite(p)?p:0,f++;break;case 39:e=c[h],typeof e=="number"?c[h]=-e:c[h]=xr(this.runner,t,e),f++;break;case 50:c[h]=c[h]?0:1,f++;break;case 68:for(S=c[h-1],M=c[h],p=S[M];p==null&&S.class!=null;)S=S.class,p=S[M];p==null&&(p=0,L.ref[f].nowarning||(L.ref[f].nowarning=!0,Array.isArray(S)||(k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.using_undefined_variable[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:M}))),c[++h]=p,f++;break;case 40:c[h-1]=c[h]===c[h-1]?1:0,h--,f++;break;case 41:c[h-1]=c[h]!==c[h-1]?1:0,h--,f++;break;case 42:c[h-1]=c[h-1]<c[h]?1:0,h--,f++;break;case 43:c[h-1]=c[h-1]>c[h]?1:0,h--,f++;break;case 44:c[h-1]=c[h-1]<=c[h]?1:0,h--,f++;break;case 45:c[h-1]=c[h-1]>=c[h]?1:0,h--,f++;break;case 95:he=s[f][0],ue=$[Y+he+1]=c[h-1],de=c[h],Z=$[Y+he],c[--h]=0,de===0?($[Y+he+2]=ue>Z?1:-1,f++):($[Y+he+2]=de,de>0&&Z>ue||de<0&&Z<ue?f=s[f][1]:f++);break;case 96:he=s[f][0],de=$[Y+he+2],ue=$[Y+he+1],Z=$[Y+he],Z+=de,de>0&&Z>ue||de<0&&Z<ue?f++:($[Y+he]=Z,f=s[f][1]),me++>500&&(me=0,performance.now()>this.time_limit&&(Fe=f,f=ee));break;case 97:p=c[h],c[h]=0,Z=s[f][0],typeof p=="object"?Array.isArray(p)?$[Y+Z+1]=p:p=$[Y+Z+1]=Object.keys(p):typeof p=="string"?p=$[Y+Z+1]=p.split(""):p=$[Y+Z+1]=[],p.length===0?f=s[f][1]:(Ie=p[0],$[Y+s[f][0]]=Ie??0,$[Y+Z+2]=0,f++);break;case 98:Z=s[f][0],Ee=$[Y+Z+2]+=1,p=$[Y+Z+1],Ee<p.length?(Ie=p[Ee],$[Y+Z]=Ie??0,f=s[f][1]):f++,me++>500&&(me=0,performance.now()>this.time_limit&&(Fe=f,f=ee));break;case 80:f=s[f],me++>500&&(me=0,performance.now()>this.time_limit&&(Fe=f,f=ee));break;case 81:c[h--]?f=s[f]:f++;break;case 82:c[h--]?f++:f=s[f];break;case 83:c[h]?f=s[f]:f++;break;case 84:c[h]?f++:f=s[f];break;case 89:for(Pt=s[f++],We=Pt.clone(),is=Pt.import_refs,Pe=0,Oe=is.length;Pe<Oe;Pe++)Re=is[Pe],Re===Pt.import_self?We.import_values.push(We):We.import_values.push($[Y+Re]);We.object=F,c[++h]=We;break;case 90:if(i=s[f],m=c[h],m instanceof K){h--,b=o[u]||(o[u]={}),u++,b.routine=L,b.object=F,b.super=g,b.supername=y,b.op_index=f+1;let R=L.ref[f]?.token;if(R&&this.call_stack_frames.push({functionName:m.source||"[anonymous function]",file:R.tokenizer.filename,line:R.line,column:R.column}),Y+=L.locals_size,L=m,ae=m.opcodes,s=m.arg1,f=0,ee=ae.length,F=L.object!=null?L.object:D,g=D,y="",L.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(C=le=i+1,qe=m.num_args;le<=qe;C=le+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,L.uses_arguments&&(c[++h]=r)}else if(typeof m=="function"){switch(i){case 0:try{p=m()}catch(R){A=R,this.reportNativeError(A),p=0}c[h]=p??0;break;case 1:try{p=m(this.argToNative(c[h-1],t))}catch(R){A=R,this.reportNativeError(A),p=0}c[h-1]=p??0,h-=1;break;case 2:try{p=m(this.argToNative(c[h-2],t),this.argToNative(c[h-1],t))}catch(R){A=R,this.reportNativeError(A),p=0}c[h-2]=p??0,h-=2;break;case 3:try{p=m(this.argToNative(c[h-3],t),this.argToNative(c[h-2],t),this.argToNative(c[h-1],t))}catch(R){A=R,this.reportNativeError(A),p=0}c[h-3]=p??0,h-=3;break;default:for(r=this._argv,r.length=0,h-=i,C=ye=0,Ei=i-1;ye<=Ei;C=ye+=1)r[C]=this.argToNative(c[h+C],t);try{p=m.apply(null,r)}catch(R){A=R,this.reportNativeError(A),p=0}c[h]=p??0}f++}else h-=i,c[h]=m??0,k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.invoking_non_function[V]||(j=L.ref[f],X=j.expression.token.start,q=j.token.start+j.token.length,t.warnings.invoking_non_function[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:j.token.tokenizer.input.substring(X,q)}),f++;break;case 91:if(M=c[h],oe=S=F,m=S[M],m==null){for(;m==null&&oe.class!=null;)oe=oe.class,m=oe[M];m==null&&(m=D.Object[M]),m==null&&(m=D[M],oe=D,S=D)}if(i=s[f],m instanceof K){if(h-=1,b=o[u]||(o[u]={}),u++,b.routine=L,b.object=F,b.super=g,b.supername=y,b.op_index=f+1,Y+=L.locals_size,L=m,ae=m.opcodes,s=m.arg1,f=0,ee=ae.length,F=S,g=oe,y=M,L.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(C=es=i+1,yi=m.num_args;es<=yi;C=es+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,L.uses_arguments&&(c[++h]=r)}else if(typeof m=="function"){switch(i){case 0:try{p=m.call(S)}catch(R){A=R,this.reportNativeError(A),p=0}c[h]=p??0;break;case 1:try{p=m.call(S,this.argToNative(c[h-1],t))}catch(R){A=R,this.reportNativeError(A),p=0}c[--h]=p??0;break;case 2:try{p=m.call(S,this.argToNative(c[h-2],t),this.argToNative(c[h-1],t))}catch(R){A=R,this.reportNativeError(A),p=0}c[h-2]=p??0,h-=2;break;case 3:try{p=m.call(S,this.argToNative(c[h-3],t),this.argToNative(c[h-2],t),this.argToNative(c[h-1],t))}catch(R){A=R,this.reportNativeError(A),p=0}c[h-3]=p??0,h-=3;break;default:for(r=this._argv,r.length=0,h-=i,C=ss=0,bi=i-1;ss<=bi;C=ss+=1)r[C]=this.argToNative(c[h+C],t);try{p=m.apply(S,r)}catch(R){A=R,this.reportNativeError(A),p=0}c[h]=p??0}f++}else h-=i,c[h]=m??0,k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.invoking_non_function[V]||(j=L.ref[f],X=j.expression.token.start,q=j.token.start+j.token.length,t.warnings.invoking_non_function[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:j.token.tokenizer.input.substring(X,q)}),f++;break;case 92:for(S=c[h-1],oe=S,M=c[h],m=S[M];m==null&&oe.class!=null;)oe=oe.class,m=oe[M];if(i=s[f],m==null&&(S instanceof K?m=D.Function[M]:typeof S=="string"?m=D.String[M]:typeof S=="number"?m=D.Number[M]:Array.isArray(S)?m=D.List[M]:typeof S=="object"&&(m=D.Object[M])),m instanceof K){if(h-=2,b=o[u]||(o[u]={}),u++,b.object=F,b.super=g,b.supername=y,b.routine=L,b.op_index=f+1,Y+=L.locals_size,L=m,ae=m.opcodes,s=m.arg1,f=0,ee=ae.length,F=S,g=oe,y=M,L.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(C=rs=i+1,di=m.num_args;rs<=di;C=rs+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,L.uses_arguments&&(c[++h]=r)}else if(typeof m=="function"){switch(i){case 0:try{p=m.call(S)}catch(R){A=R,this.reportNativeError(A),p=0}c[--h]=p??0;break;case 1:try{p=m.call(S,this.argToNative(c[h-2],t))}catch(R){A=R,this.reportNativeError(A),p=0}c[h-2]=p??0,h-=2;break;case 2:try{p=m.call(S,this.argToNative(c[h-3],t),this.argToNative(c[h-2],t))}catch(R){A=R,this.reportNativeError(A),p=0}c[h-3]=p??0,h-=3;break;case 3:try{p=m.call(S,this.argToNative(c[h-4],t),this.argToNative(c[h-3],t),this.argToNative(c[h-2],t))}catch(R){A=R,this.reportNativeError(A),p=0}c[h-4]=p??0,h-=4;break;default:for(r=this._argv,r.length=0,h-=i+1,C=as=0,mi=i-1;as<=mi;C=as+=1)r[C]=this.argToNative(c[h+C],t);try{p=m.apply(S,r)}catch(R){A=R,this.reportNativeError(A),p=0}c[h]=p??0}f++}else h-=i+1,c[h]=m??0,k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.invoking_non_function[V]||(j=L.ref[f],X=j.expression.token.start,q=j.token.start+j.token.length,t.warnings.invoking_non_function[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:j.token.tokenizer.input.substring(X,q)}),f++;break;case 93:if(g!=null&&y!=null){for(oe=g,m=null;m==null&&oe.class!=null;)oe=oe.class,m=oe[y];if(m!=null&&m instanceof K){if(i=s[f],b=o[u]||(o[u]={}),u++,b.object=F,b.super=g,b.supername=y,b.routine=L,b.op_index=f+1,Y+=L.locals_size,L=m,ae=m.opcodes,s=m.arg1,f=0,ee=ae.length,g=oe,L.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(C=os=i+1,gi=m.num_args;os<=gi;C=os+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,L.uses_arguments&&(c[++h]=r)}else i=s[f],h-=i,c[++h]=0,f++}else i=s[f],h-=i,c[++h]=0,f++;break;case 94:De-=s[f],u<=0?f=ee:(b=o[--u],F=b.object,g=b.super,y=b.supername,L=b.routine,f=b.op_index,ae=L.opcodes,s=L.arg1,Y-=L.locals_size,ee=ae.length);break;case 100:p=s[f](c[h]),c[h]=isFinite(p)?p:0,f++;break;case 101:p=s[f](c[h-1],c[h]),c[--h]=isFinite(p)?p:0,f++;break;case 110:He=this.runner.createThread(c[h-1],c[h],!1),c[--h]=He,f+=1;break;case 111:He=this.runner.createThread(c[h-1],c[h],!0),c[--h]=He,f+=1;break;case 112:He=this.runner.createThread(c[h],0,!1),c[h]=He,f+=1;break;case 113:Ti=isFinite(c[h])?c[h]:0,this.runner.sleep(Ti),f+=1,Fe=f,f=ee;break;case 120:if(M=s[f].name,i=s[f].args,p=F[M],p==null&&F.class!=null)for(S=F;p==null&&S.class!=null;)S=S.class,p=S[M];if(p==null&&(p=D[M]),p==null&&!L.ref[f].nowarning&&(k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.using_undefined_variable[V]||(t.warnings.using_undefined_variable[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:M})),m=p??0,m instanceof K){b=o[u]||(o[u]={}),u++,b.routine=L,b.object=F,b.super=g,b.supername=y,b.op_index=f+1;let R=L.ref[f]?.token;if(R&&this.call_stack_frames.push({functionName:m.source||"[anonymous function]",file:R.tokenizer.filename,line:R.line,column:R.column}),Y+=L.locals_size,L=m,ae=m.opcodes,s=m.arg1,f=0,ee=ae.length,F=L.object!=null?L.object:D,g=D,y="",L.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(C=le=i+1,qe=m.num_args;le<=qe;C=le+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,L.uses_arguments&&(c[++h]=r)}else if(typeof m=="function"){switch(i){case 0:try{p=m()}catch(R){this.reportNativeError(R),p=0}c[++h]=p??0;break;case 1:try{p=m(this.argToNative(c[h],t))}catch(R){this.reportNativeError(R),p=0}c[h]=p??0;break;case 2:try{p=m(this.argToNative(c[h-1],t),this.argToNative(c[h],t))}catch(R){this.reportNativeError(R),p=0}c[--h]=p??0;break;case 3:try{p=m(this.argToNative(c[h-2],t),this.argToNative(c[h-1],t),this.argToNative(c[h],t))}catch(R){this.reportNativeError(R),p=0}c[h-2]=p??0,h-=2;break;default:for(r=this._argv,r.length=0,h-=i-1,C=0;C<i;C++)r[C]=this.argToNative(c[h+C],t);try{p=m.apply(null,r)}catch(R){this.reportNativeError(R),p=0}c[h]=p??0}f++}else h-=i,c[++h]=m??0,f++;break;case 121:for(i=s[f],S=c[h-1],M=c[h],p=S[M];p==null&&S.class!=null;)S=S.class,p=S[M];if(p==null&&(p=0,L.ref[f].nowarning||(L.ref[f].nowarning=!0,Array.isArray(S)||(k=L.ref[f].token,V=k.tokenizer.filename+"-"+k.line+"-"+k.column,t.warnings.using_undefined_variable[V]={file:k.tokenizer.filename,line:k.line,column:k.column,expression:M}))),m=p,c[--h]=m,m instanceof K){h--,b=o[u]||(o[u]={}),u++,b.routine=L,b.object=F,b.super=g,b.supername=y,b.op_index=f+1;let R=L.ref[f]?.token;if(R&&this.call_stack_frames.push({functionName:m.source||"[anonymous function]",file:R.tokenizer.filename,line:R.line,column:R.column}),Y+=L.locals_size,L=m,ae=m.opcodes,s=m.arg1,f=0,ee=ae.length,F=L.object!=null?L.object:D,g=D,y="",L.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(C=le=i+1,qe=m.num_args;le<=qe;C=le+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,L.uses_arguments&&(c[++h]=r)}else if(typeof m=="function"){switch(i){case 0:try{p=m()}catch(R){this.reportNativeError(R),p=0}c[h]=p??0;break;case 1:try{p=m(this.argToNative(c[h-1],t))}catch(R){this.reportNativeError(R),p=0}c[h-1]=p??0,h--;break;case 2:try{p=m(this.argToNative(c[h-2],t),this.argToNative(c[h-1],t))}catch(R){this.reportNativeError(R),p=0}c[h-2]=p??0,h-=2;break;case 3:try{p=m(this.argToNative(c[h-3],t),this.argToNative(c[h-2],t),this.argToNative(c[h-1],t))}catch(R){this.reportNativeError(R),p=0}c[h-3]=p??0,h-=3;break;default:for(r=this._argv,r.length=0,h-=i,C=0;C<i;C++)r[C]=this.argToNative(c[h+C],t);try{p=m.apply(null,r)}catch(R){this.reportNativeError(R),p=0}c[h]=p??0}f++}else h-=i,c[h]=m??0,f++;break;case 122:e=s[f],n=c[h],typeof n=="number"?(n+=e,c[h]=isFinite(n)?n:0):c[h]=Ft(this.runner,t,n,e,0),f++;break;case 123:e=s[f],n=c[h],typeof n=="number"?(n-=e,c[h]=isFinite(n)?n:0):c[h]=Ut(this.runner,t,n,e,0),f++;break;case 124:e=s[f],n=c[h],typeof n=="number"?(n*=e,c[h]=isFinite(n)?n:0):c[h]=Yt(this.runner,t,n,e,0),f++;break;case 125:e=$[Y+s[f]],n=c[h],typeof n=="number"&&typeof e=="number"?(n+=e,c[h]=isFinite(n)?n:0):c[h]=Ft(this.runner,t,n,e,0),f++;break;case 126:e=$[Y+s[f]],n=c[h],typeof n=="number"&&typeof e=="number"?(n-=e,c[h]=isFinite(n)?n:0):c[h]=Ut(this.runner,t,n,e,0),f++;break;case 127:e=$[Y+s[f]],n=c[h],typeof n=="number"&&typeof e=="number"?(n*=e,c[h]=isFinite(n)?n:0):c[h]=Yt(this.runner,t,n,e,0),f++;break;case 128:e=s[f],n=c[h],typeof n=="number"?(n/=e,c[h]=isFinite(n)?n:0):c[h]=Zs(this.runner,t,n,e,0),f++;break;case 129:e=$[Y+s[f]],c[h]=c[h]<e?1:0,f++;break;case 130:e=$[Y+s[f]],c[h]=c[h]>e?1:0,f++;break;case 131:e=$[Y+s[f]],c[h]=c[h]===e?1:0,f++;break;case 200:h=s[f](c,h,$,Y,F,D),f++;break;default:throw`Unsupported operation: ${ae[f]}`}return Fe>=0?(this.op_index=Fe,this.routine=L,this.stack_index=h,this.local_index=De,this.object=F,this.call_stack_index=u,this.call_super=g,this.call_supername=y,this.locals_offset=Y,this.done=!1):(this.op_index=0,this.done=!0,this.routine.callback!=null&&(this.routine.callback(c[h]),this.routine.callback=null)),this.log&&(console.info("total operations: "+me),console.info(`stack_index: ${h}`),console.info(`result: ${c[h]}`)),c[h]}},wr=class _e{static{l(this,"_Compiler")}static{v(this,"Compiler")}program;code_saves;code;routine;locals;count;break_label;continue_label;processor;constructor(e){let s,i,r,n,a;for(this.program=e,this.code_saves=[],this.code=[""],this.routine=new K(0),this.locals=new rr(this),this.count=0,this.break_label=null,this.continue_label=null,n=this.program.statements,s=i=0,r=n.length;i<r&&(a=n[s],this.compile(a),s<this.program.statements.length-1&&this.routine.POP(a),!(a instanceof Et||a instanceof Nt||a instanceof Dt));s=++i);this.routine.optimize(),this.routine.resolveLabels(),this.optimizeFusedOpcodes(),this.count+=this.routine.opcodes.length,this.routine.locals_size=this.locals.max_index}optimizeFusedOpcodes(){let e=this.routine.opcodes,s=this.routine.arg1,i=this.routine.ref,r=0;for(;r<e.length-1;){if(e[r]===E.LOAD_VARIABLE&&e[r+1]===E.FUNCTION_CALL){let n=s[r],a=s[r+1],o=i[r+1];e[r]=E.LOAD_VAR_CALL,s[r]={name:n,args:a},i[r]=o,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_PROPERTY&&e[r+1]===E.FUNCTION_CALL){let n=s[r+1],a=i[r+1];e[r]=E.LOAD_PROP_CALL,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_VALUE&&typeof s[r]=="number"&&e[r+1]===E.ADD){let n=s[r],a=i[r+1];e[r]=E.LOAD_CONST_ADD,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_VALUE&&typeof s[r]=="number"&&e[r+1]===E.SUB){let n=s[r],a=i[r+1];e[r]=E.LOAD_CONST_SUB,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_VALUE&&typeof s[r]=="number"&&e[r+1]===E.MUL){let n=s[r],a=i[r+1];e[r]=E.LOAD_CONST_MUL,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_LOCAL&&e[r+1]===E.ADD){let n=s[r],a=i[r+1];e[r]=E.LOAD_LOCAL_ADD,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_LOCAL&&e[r+1]===E.SUB){let n=s[r],a=i[r+1];e[r]=E.LOAD_LOCAL_SUB,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_LOCAL&&e[r+1]===E.MUL){let n=s[r],a=i[r+1];e[r]=E.LOAD_LOCAL_MUL,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_VALUE&&typeof s[r]=="number"&&e[r+1]===E.DIV){let n=s[r],a=i[r+1];e[r]=E.LOAD_CONST_DIV,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_LOCAL&&e[r+1]===E.LT){let n=s[r],a=i[r+1];e[r]=E.LOAD_LOCAL_LT,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_LOCAL&&e[r+1]===E.GT){let n=s[r],a=i[r+1];e[r]=E.LOAD_LOCAL_GT,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(e[r]===E.LOAD_LOCAL&&e[r+1]===E.EQ){let n=s[r],a=i[r+1];e[r]=E.LOAD_LOCAL_EQ,s[r]=n,i[r]=a,e.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}r++}}compile(e){if(e instanceof B)this.compileValue(e);else if(e instanceof bt)this.compileOperation(e);else if(e instanceof xe)this.compileAssignment(e);else if(e instanceof se)this.compileVariable(e);else if(e instanceof yt)this.compileFunction(e);else if(e instanceof je)this.compileFunctionCall(e);else if(e instanceof pr)this.compileWhile(e);else if(e instanceof or)this.compileSelfAssignment(e);else if(e instanceof Hs)this.compileBraced(e);else if(e instanceof dr)this.compileCreateObject(e);else if(e instanceof Ae)this.compileField(e);else if(e instanceof hr)this.compileNegate(e);else if(e instanceof ur)this.compileFor(e);else if(e instanceof fr)this.compileForIn(e);else if(e instanceof lr)this.compileNot(e);else if(e instanceof Et)this.compileReturn(e);else if(e instanceof cr)this.compileCondition(e);else if(e instanceof Nt)this.compileBreak(e);else if(e instanceof Dt)this.compileContinue(e);else if(e instanceof Ks)this.compileCreateClass(e);else if(e instanceof mr)this.compileNewCall(e);else if(e instanceof Js)this.compileAfter(e);else if(e instanceof Qs)this.compileEvery(e);else if(e instanceof Xs)this.compileDo(e);else if(e instanceof gr)this.compileSleep(e);else if(e instanceof _r)this.compileDelete(e);else throw console.info(e),"Not implemented"}compileAssignment(e){let s,i,r,n,a,o;if(e.local)if(e.field instanceof se)e.expression instanceof yt?(n=this.locals.register(e.field.identifier),this.compile(e.expression),this.routine.arg1[this.routine.arg1.length-1].import_self=n,this.routine.STORE_LOCAL(n,e)):e.expression instanceof Js||e.expression instanceof Xs||e.expression instanceof Qs?(n=this.locals.register(e.field.identifier),s=this.routine.arg1.length,this.compile(e.expression),this.routine.arg1[s].import_self=n,this.routine.STORE_LOCAL(n,e)):(this.compile(e.expression),n=this.locals.register(e.field.identifier),this.routine.STORE_LOCAL(n,e));else throw"illegal";else if(e.field instanceof se)this.locals.get(e.field.identifier)!=null?(this.compile(e.expression),n=this.locals.get(e.field.identifier),this.routine.STORE_LOCAL(n,e)):e.expression instanceof Ks?this.compileUpdateClass(e.expression,e.field.identifier):(this.compile(e.expression),this.routine.STORE_VARIABLE(e.field.identifier,e));else{for(i=e.field,i.expression instanceof se?i.expression.identifier==="this"?this.routine.LOAD_THIS(i):this.locals.get(i.expression.identifier)!=null?(n=this.locals.get(i.expression.identifier),this.routine.LOAD_LOCAL_OBJECT(n,i.expression)):i.expression.identifier==="global"?this.routine.LOAD_GLOBAL(i):this.routine.LOAD_VARIABLE_OBJECT(i.expression.identifier,e):(this.compile(i.expression),this.routine.MAKE_OBJECT(e)),r=a=0,o=i.chain.length-2;a<=o;r=a+=1)this.compile(i.chain[r]),this.routine.LOAD_PROPERTY_OBJECT(i.chain[r]);this.compile(i.chain[i.chain.length-1]),this.compile(e.expression),this.routine.STORE_PROPERTY(e)}}compileSelfAssignment(e){let s,i,r,n,a,o;switch(e.operation){case"+=":a="ADD";break;case"-=":a="SUB";break;case"*=":a="MUL";break;case"/=":a="DIV";break;case"%=":a="MODULO";break;case"&=":a="BINARY_AND";break;case"|=":a="BINARY_OR";break;default:throw"Unknown self-assignment operation: "+e.operation}if(e.field instanceof se)this.locals.get(e.field.identifier)!=null?(r=this.locals.get(e.field.identifier),this.routine.LOAD_LOCAL(r,e),this.compile(e.expression),this.routine[a](e),this.routine.STORE_LOCAL(r,e)):(this.routine.LOAD_VARIABLE(e.field.identifier,e),this.compile(e.expression),this.routine[a](e),this.routine.STORE_VARIABLE(e.field.identifier,e));else{for(s=e.field,s.expression instanceof se?s.expression.identifier==="this"?this.routine.LOAD_THIS(s):this.locals.get(s.expression.identifier)!=null?(r=this.locals.get(s.expression.identifier),this.routine.LOAD_LOCAL_OBJECT(r,e)):s.expression.identifier==="global"?this.routine.LOAD_GLOBAL(s):this.routine.LOAD_VARIABLE_OBJECT(s.expression.identifier,e):(this.compile(s.expression),this.routine.MAKE_OBJECT(e)),i=n=0,o=s.chain.length-2;n<=o;i=n+=1)this.compile(s.chain[i]),this.routine.LOAD_PROPERTY_OBJECT(s.chain[i]);this.compile(s.chain[s.chain.length-1]),this.routine.LOAD_PROPERTY_ATOP(e),this.compile(e.expression),this.routine[a](e),this.routine.STORE_PROPERTY(e)}}compileOperation(e){let s,i,r;if((i=e.operation)==="+"||i==="-"||i==="*"||i==="/"||i==="%"||i==="&"||i==="|"||i==="<<"||i===">>"){if(e.term1 instanceof B&&e.term1.type===B.TYPE_NUMBER&&e.term2 instanceof B&&e.term2.type===B.TYPE_NUMBER){let n,a=e.term1.value,o=e.term2.value;switch(e.operation){case"+":n=a+o;break;case"-":n=a-o;break;case"*":n=a*o;break;case"/":n=a/o;break;case"%":n=a%o;break;case"&":n=a&o;break;case"|":n=a|o;break;case"<<":n=a<<o;break;case">>":n=a>>o;break;default:n=0}this.routine.LOAD_VALUE(n,e);return}switch(this.compile(e.term1),this.compile(e.term2),e.operation){case"+":this.routine.ADD(e);break;case"-":this.routine.SUB(e);break;case"*":this.routine.MUL(e);break;case"/":this.routine.DIV(e);break;case"%":this.routine.MODULO(e);break;case"&":this.routine.BINARY_AND(e);break;case"|":this.routine.BINARY_OR(e);break;case"<<":this.routine.SHIFT_LEFT(e);break;case">>":this.routine.SHIFT_RIGHT(e)}}else if((r=e.operation)==="=="||r==="!="||r==="<"||r===">"||r==="<="||r===">="){if(e.term1 instanceof B&&e.term1.type===B.TYPE_NUMBER&&e.term2 instanceof B&&e.term2.type===B.TYPE_NUMBER){let n=e.term1.value,a=e.term2.value,o;switch(e.operation){case"==":o=n===a?1:0;break;case"!=":o=n!==a?1:0;break;case"<":o=n<a?1:0;break;case">":o=n>a?1:0;break;case"<=":o=n<=a?1:0;break;case">=":o=n>=a?1:0;break;default:o=0}this.routine.LOAD_VALUE(o,e);return}switch(this.compile(e.term1),this.compile(e.term2),e.operation){case"==":this.routine.EQ(e);break;case"!=":this.routine.NEQ(e);break;case"<":this.routine.LT(e);break;case">":this.routine.GT(e);break;case"<=":this.routine.LTE(e);break;case">=":this.routine.GTE(e)}}else e.operation==="and"?(s=this.routine.createLabel("and"),e.term1.nowarning=!0,e.term2.nowarning=!0,this.compile(e.term1),this.routine.JUMPN_NOPOP(s,e),this.routine.POP(e),this.compile(e.term2),this.routine.setLabel(s)):e.operation==="or"?(s=this.routine.createLabel("or"),e.term1.nowarning=!0,e.term2.nowarning=!0,this.compile(e.term1),this.routine.JUMPY_NOPOP(s,e),this.routine.POP(e),this.compile(e.term2),this.routine.setLabel(s)):e.operation==="^"&&(this.compile(e.term1),this.compile(e.term2),this.routine.BINARY_OP(_e.predefined_binary_functions.pow,e))}compileBraced(e){this.compile(e.expression)}compileNegate(e){e.expression instanceof B&&e.expression.type===B.TYPE_NUMBER?this.routine.LOAD_VALUE(-e.expression.value,e):(this.compile(e.expression),this.routine.NEGATE(e))}compileNot(e){if(e.expression instanceof B&&e.expression.type===B.TYPE_NUMBER){this.routine.LOAD_VALUE(e.expression.value?0:1,e);return}e.expression.nowarning=!0,this.compile(e.expression),this.routine.NOT(e)}compileValue(e){let s,i,r;switch(e.type){case B.TYPE_NUMBER:this.routine.LOAD_VALUE(e.value,e);break;case B.TYPE_STRING:this.routine.LOAD_VALUE(e.value,e);break;case B.TYPE_ARRAY:for(this.routine.CREATE_ARRAY(e),s=i=0,r=e.value.length-1;i<=r;s=i+=1)this.routine.LOAD_VALUE(s,e),this.compile(e.value[s]),this.routine.CREATE_PROPERTY(e)}}compileVariable(e){let s,i;i=e.identifier,i==="this"?this.routine.LOAD_THIS(e):i==="global"?this.routine.LOAD_GLOBAL(e):_e.predefined_values[i]!=null?this.routine.LOAD_VALUE(_e.predefined_values[i],e):this.locals.get(i)!=null?(s=this.locals.get(i),this.routine.LOAD_LOCAL(s,e)):this.routine.LOAD_VARIABLE(i,e)}compileField(e){var s,i,r,n,a,o,u,g,y;if((e.expression.identifier==="keyboard"||e.expression.identifier==="gamepad")&&(e.nowarning=!0),s=e.chain[e.chain.length-1],s instanceof B&&s.value==="type")if(e.chain.length===1)e.expression instanceof se?(r=e.expression.identifier,this.locals.get(r)!=null?(n=this.locals.get(r),this.routine.LOAD_LOCAL(n,e),this.routine.TYPE(e)):_e.predefined_values[r]!=null?this.routine.LOAD_VALUE("number",e):_e.predefined_unary_functions[r]!=null||_e.predefined_binary_functions[r]?this.routine.LOAD_VALUE("function",e):this.routine.VARIABLE_TYPE(r,e.expression)):(this.compile(e.expression),this.routine.TYPE(e));else{for(this.compile(e.expression),i=a=0,g=e.chain.length-3;a<=g;i=a+=1)this.compile(e.chain[i]),this.routine.LOAD_PROPERTY(e);this.compile(e.chain[e.chain.length-2]),this.routine.PROPERTY_TYPE(e.expression)}else for(this.compile(e.expression),y=e.chain,o=0,u=y.length;o<u;o++)s=y[o],this.compile(s),this.routine.LOAD_PROPERTY(e)}compileFieldParent(e){var s,i,r,n;for(this.compile(e.expression),i=r=0,n=e.chain.length-2;r<=n;i=r+=1)s=e.chain[i],this.compile(s),this.routine.LOAD_PROPERTY(e)}compileFunctionCall(e){var s,i,r,n,a,o,u,g,y,O,b,A,m,j,J,D,C,X,q;if(e.expression instanceof Ae){for(J=e.args,r=a=0,g=J.length;a<g;r=++a)s=J[r],this.compile(s);this.compileFieldParent(e.expression),this.compile(e.expression.chain[e.expression.chain.length-1]),this.routine.FUNCTION_APPLY_PROPERTY(e.args.length,e)}else if(e.expression instanceof se)if(_e.predefined_unary_functions[e.expression.identifier]!=null)i=_e.predefined_unary_functions[e.expression.identifier],e.args.length>0?this.compile(e.args[0]):this.routine.LOAD_VALUE(0,e),this.routine.UNARY_OP(i,e);else if(_e.predefined_binary_functions[e.expression.identifier]!=null)i=_e.predefined_binary_functions[e.expression.identifier],e.args.length>0?this.compile(e.args[0]):this.routine.LOAD_VALUE(0,e),e.args.length>1?this.compile(e.args[1]):this.routine.LOAD_VALUE(0,e),this.routine.BINARY_OP(i,e);else if(e.expression.identifier==="super"){for(D=e.args,r=o=0,y=D.length;o<y;r=++o)s=D[r],this.compile(s);this.routine.SUPER_CALL(e.args.length,e)}else if(this.locals.get(e.expression.identifier)!=null){for(C=e.args,r=u=0,O=C.length;u<O;r=++u)s=C[r],this.compile(s);n=this.locals.get(e.expression.identifier),this.routine.LOAD_LOCAL(n,e),this.routine.FUNCTION_CALL(e.args.length,e)}else{for(X=e.args,r=m=0,b=X.length;m<b;r=++m)s=X[r],this.compile(s);this.routine.LOAD_VALUE(e.expression.identifier,e),this.routine.FUNCTION_APPLY_VARIABLE(e.args.length,e)}else{for(q=e.args,j=0,A=q.length;j<A;j++)s=q[j],this.compile(s);this.compile(e.expression),this.routine.FUNCTION_CALL(e.args.length,e)}}compileFor(e){if(e.range_from instanceof B&&e.range_from.type===B.TYPE_NUMBER&&e.range_to instanceof B&&e.range_to.type===B.TYPE_NUMBER&&(e.range_by==null||e.range_by instanceof B&&e.range_by.type===B.TYPE_NUMBER)){let u=e.range_from.value,g=e.range_to.value,y=e.range_by instanceof B?e.range_by.value:1,O=0;if(y>0&&g>=u?O=Math.floor((g-u)/y)+1:y<0&&g<=u&&(O=Math.floor((u-g)/Math.abs(y))+1),O>0&&O<=5){let b=this.locals.register(e.iterator);this.locals.push();for(let A=0;A<O;A++){let m=u+A*y;this.routine.LOAD_VALUE(m,e),this.routine.STORE_LOCAL(b,e),this.routine.POP(e),this.compileSequence(e.sequence)}this.locals.pop();return}}var s,i,r,n,a,o;n=this.locals.register(e.iterator),this.locals.allocate(),this.locals.allocate(),this.compile(e.range_from),this.routine.STORE_LOCAL(n,e),this.routine.POP(e),this.compile(e.range_to),e.range_by!=null?this.compile(e.range_by):this.routine.LOAD_VALUE(0,e),r=this.routine.createLabel("for_start"),s=this.routine.createLabel("for_continue"),i=this.routine.createLabel("for_end"),this.routine.FORLOOP_INIT([n,i],e),this.routine.setLabel(r),this.locals.push(),a=this.break_label,o=this.continue_label,this.break_label=i,this.continue_label=s,this.compileSequence(e.sequence),this.break_label=a,this.continue_label=o,this.routine.setLabel(s),this.routine.FORLOOP_CONTROL([n,r],e),this.routine.setLabel(i),this.locals.pop()}compileForIn(e){var s,i,r,n,a,o;n=this.locals.register(e.iterator),this.locals.allocate(),this.locals.allocate(),this.compile(e.list),r=this.routine.createLabel("for_start"),s=this.routine.createLabel("for_continue"),i=this.routine.createLabel("for_end"),this.routine.FORIN_INIT([n,i],e),this.routine.setLabel(r),this.locals.push(),a=this.break_label,o=this.continue_label,this.break_label=i,this.continue_label=s,this.compileSequence(e.sequence),this.break_label=a,this.continue_label=o,this.routine.setLabel(s),this.routine.FORIN_CONTROL([n,r],e),this.routine.setLabel(i),this.locals.pop()}compileSequence(e){var s,i,r;for(s=i=0,r=e.length-1;i<=r&&(e[s].nopop||this.routine.POP(e[s]),this.compile(e[s]),!(e[s]instanceof Et||e[s]instanceof Nt||e[s]instanceof Dt));s=i+=1);}compileWhile(e){var s,i,r,n;this.locals.push(),n=this.routine.createLabel("while_start"),s=this.routine.createLabel("while_end"),this.routine.LOAD_VALUE(0,e),this.routine.setLabel(n),this.compile(e.condition),this.routine.JUMPN(s),i=this.break_label,r=this.continue_label,this.break_label=s,this.continue_label=n,this.compileSequence(e.sequence),this.routine.JUMP(n,e),this.break_label=i,this.continue_label=r,this.routine.setLabel(s),this.locals.pop()}compileBreak(e){this.break_label!=null&&this.routine.JUMP(this.break_label,e)}compileContinue(e){this.continue_label!=null&&this.routine.JUMP(this.continue_label,e)}compileFunction(e){var s;s=this.compileFunctionBody(e),this.routine.LOAD_ROUTINE(s,e)}compileFunctionBody(e){let s="args"in e&&e.args!=null;var i,r,n,a,o,u,g,y,O,b,A,m,j,J,D,C,X;if(X=this.routine,b=this.locals,this.routine=new K(s?e.args.length:0),this.locals=new rr(this,b),this.routine.uses_arguments=!0,s){let q=e.args;for(this.routine.uses_arguments&&(r=this.locals.register("arguments"),this.routine.STORE_LOCAL(r,e),this.routine.POP(e)),m=this.locals.register("+numargs"),this.routine.STORE_LOCAL(m,e),this.routine.POP(e),n=o=J=q.length-1;o>=0;n=o+=-1)i=q[n],a=this.locals.register(i.name),this.routine.STORE_LOCAL(a,e),this.routine.POP(e);for(n=u=0,J=q.length-1;u<=J;n=u+=1)i=q[n],i.default!=null&&(a=this.locals.get(i.name),y=this.routine.createLabel("default_arg"),this.routine.LOAD_VALUE(n,e),this.routine.LOAD_LOCAL(m,e),this.routine.LT(e),this.routine.JUMPY(y,e),this.compile(i.default),this.routine.STORE_LOCAL(a,e),this.routine.POP(e),this.routine.setLabel(y))}if(e.sequence.length>0)for(n=g=0,D=e.sequence.length-1;g<=D;n=g+=1)this.compile(e.sequence[n]),n<e.sequence.length-1?this.routine.POP(e.sequence[n]):this.routine.RETURN(e.sequence[n]);else this.routine.LOAD_VALUE(0,e),this.routine.RETURN(e);for(s&&!this.locals.arguments_used&&(this.routine.uses_arguments=!1,this.routine.remove(0),this.routine.remove(0)),a=0,C=this.locals.imports,A=0,O=C.length;A<O;A++){let q=C[A];this.routine.OP_INSERT(E.LOAD_IMPORT,e,a,a*3),this.routine.OP_INSERT(E.STORE_LOCAL,e,q.index,a*3+1),this.routine.OP_INSERT(E.POP,e,0,a*3+2),this.routine.import_refs.push(q.source),a+=1}return this.routine.optimize(),this.routine.resolveLabels(),this.count+=this.routine.opcodes.length,j=this.routine,this.routine.locals_size=this.locals.max_index,this.routine=X,this.locals=b,j}compileReturn(e){e.expression!=null?(this.compile(e.expression),this.routine.RETURN(e)):(this.routine.LOAD_VALUE(0,e),this.routine.RETURN(e))}compileCondition(e){var s,i,r,n,a,o,u;for(i=e.chain,this.routine.LOAD_VALUE(0,e),r=this.routine.createLabel("condition_end"),a=o=0,u=i.length-1;o<=u;a=o+=1)n=this.routine.createLabel("condition_next"),s=i[a],s.condition.nowarning=!0,this.compile(s.condition),this.routine.JUMPN(n),this.locals.push(),this.compileSequence(s.sequence),this.locals.pop(),this.routine.JUMP(r,e),this.routine.setLabel(n),a===i.length-1&&s.else!=null&&(this.locals.push(),this.compileSequence(s.else),this.locals.pop());this.routine.setLabel(r)}formatField(e){return e==="constructor"&&(e="_constructor"),String(e).replace(/"/g,'\\"')}compileCreateObject(e){let s,i,r,n;for(this.routine.CREATE_OBJECT(e),n=e.fields,i=0,r=n.length;i<r;i++)s=n[i],this.routine.LOAD_VALUE(s.field,e),this.compile(s.value),this.routine.CREATE_PROPERTY(e)}compileCreateClass(e){let s,i,r,n,a;for(e.ext!=null?(e.ext.nowarning=!0,this.compile(e.ext)):this.routine.LOAD_VALUE(0,e),a=e.ext!=null&&e.ext instanceof se?e.ext.identifier:0,this.routine.CREATE_CLASS(a,e),n=e.fields,i=0,r=n.length;i<r;i++)s=n[i],this.routine.LOAD_VALUE(s.field,e),this.compile(s.value),this.routine.CREATE_PROPERTY(e)}compileUpdateClass(e,s){this.compileCreateClass(e),this.routine.UPDATE_CLASS(s,e)}compileNewCall(e){let s,i,r,n,a,o;for(i=e.expression,this.routine.LOAD_VALUE(0,e),o=i.args,r=n=0,a=o.length;n<a;r=++n)s=o[r],this.compile(s);this.compile(i.expression),this.routine.NEW_CALL(i.args.length,e),this.routine.POP(e)}compileAfter(e){let s;s=this.compileFunctionBody(e),this.routine.LOAD_ROUTINE(s,e),this.compile(e.delay),e.multiplier!=null&&e.multiplier!==1&&(this.routine.LOAD_VALUE(e.multiplier,e),this.routine.MUL(e)),this.routine.AFTER(e)}compileEvery(e){let s;s=this.compileFunctionBody(e),this.routine.LOAD_ROUTINE(s,e),this.compile(e.delay),e.multiplier!=null&&e.multiplier!==1&&(this.routine.LOAD_VALUE(e.multiplier,e),this.routine.MUL(e)),this.routine.EVERY(e)}compileDo(e){let s;s=this.compileFunctionBody(e),this.routine.LOAD_ROUTINE(s,e),this.routine.DO(e)}compileSleep(e){this.compile(e.delay),e.multiplier!=null&&e.multiplier!==1&&(this.routine.LOAD_VALUE(e.multiplier,e),this.routine.MUL(e)),this.routine.SLEEP(e)}compileDelete(e){let s,i,r,n;if(e.field instanceof se)this.routine.LOAD_THIS(e),this.routine.LOAD_VALUE(e.field.identifier,e),this.routine.DELETE(e);else if(e.field instanceof Ae){for(this.compile(e.field.expression),s=e.field.chain,i=r=0,n=s.length-1;r<=n;i=r+=1)this.compile(s[i]),i<s.length-1&&this.routine.LOAD_PROPERTY(e);this.routine.DELETE(e)}else throw"Delete expects variable or field access"}exec(e){if(this.processor||(this.processor=new Lr(null)),!this.routine)throw new Error("No routine to execute");return this.processor.load(this.routine),this.processor.run(e)}static predefined_unary_functions={round:Math.round,floor:Math.floor,ceil:Math.ceil,abs:Math.abs,sqrt:Math.sqrt,sin:Math.sin,cos:Math.cos,tan:Math.tan,acos:Math.acos,asin:Math.asin,atan:Math.atan,sind:v(e=>Math.sin(e*Math.PI/180),"sind"),cosd:v(e=>Math.cos(e*Math.PI/180),"cosd"),tand:v(e=>Math.tan(e*Math.PI/180),"tand"),asind:v(e=>Math.asin(e)/Math.PI*180,"asind"),acosd:v(e=>Math.acos(e)/Math.PI*180,"acosd"),atand:v(e=>Math.atan(e)/Math.PI*180,"atand"),log:Math.log,exp:Math.exp};static predefined_binary_functions={min:Math.min,max:Math.max,pow:Math.pow,atan2:Math.atan2,atan2d:v((e,s)=>Math.atan2(e,s)/Math.PI*180,"atan2d")};static predefined_values={PI:Math.PI,true:1,false:0}},rr=class{static{l(this,"Locals")}static{v(this,"Locals")}compiler;parent;layers;index;max_index;imports;arguments_used;constructor(t,e=null){this.compiler=t,this.parent=e,this.layers=[],this.index=0,this.max_index=0,this.imports=[],this.push()}increment(){let t=this.index++;return this.max_index=Math.max(this.index,this.max_index),t}push(){return this.layers.push(new Ea(this))}pop(){return this.layers.splice(this.layers.length-1,1)}register(t){return this.layers[this.layers.length-1].register(t)}allocate(){return this.layers[this.layers.length-1].allocate()}get(t){let e,s,i,r;for(t==="arguments"&&(this.arguments_used=!0),e=i=this.layers.length-1;i>=0;e=i-=1)if(r=this.layers[e].get(t),r!=null)return r;return this.parent!=null&&(r=this.parent.get(t),r!=null)?(s=this.register(t),this.imports.push({name:t,index:s,source:r}),s):null}},Ea=class{static{l(this,"LocalLayer")}static{v(this,"LocalLayer")}locals;start_index;registered;constructor(t){this.locals=t,this.start_index=this.locals.index,this.registered={}}register(t){return this.registered[t]=this.locals.increment()}allocate(){return this.locals.increment()}get(t){return this.registered[t]!=null?this.registered[t]:null}},ya=100,nr=class{static{l(this,"VMProfiler")}static{v(this,"VMProfiler")}startTime=0;startOps=0;startAllocations=0;frameCount=0;sampleCount=0;processor;totalOps=0;totalTime=0;totalAllocations=0;totalFrames=0;totalOpsPerSec=0;totalAvgFrameTime=0;constructor(t){this.processor=t}start(){this.startTime=performance.now(),this.startOps=this.processor.metrics?.ops||0,this.startAllocations=this.processor.metrics?.allocations||0,this.frameCount=0}stop(){let e=performance.now()-this.startTime,s=this.processor.metrics?.ops||0,i=this.processor.metrics?.allocations||0,r=s-this.startOps,n=i-this.startAllocations,a=r/e*1e3,o=e/(this.frameCount||1),u={ops:r,time:e,allocations:n,frames:this.frameCount,samples:this.sampleCount+1,opsPerSec:a,avgFrameTime:o};return this.sampleCount<ya&&(this.totalOps+=r,this.totalTime+=e,this.totalAllocations+=n,this.totalFrames+=this.frameCount,this.totalOpsPerSec+=a,this.totalAvgFrameTime+=o,this.sampleCount++),u}frame(){this.frameCount++}getAverageMetrics(){return this.sampleCount===0?this.stop():{ops:this.totalOps/this.sampleCount,time:this.totalTime/this.sampleCount,allocations:this.totalAllocations/this.sampleCount,frames:this.totalFrames/this.sampleCount,samples:this.sampleCount,opsPerSec:this.totalOpsPerSec/this.sampleCount,avgFrameTime:this.totalAvgFrameTime/this.sampleCount}}reset(){this.sampleCount=0,this.totalOps=0,this.totalTime=0,this.totalAllocations=0,this.totalFrames=0,this.totalOpsPerSec=0,this.totalAvgFrameTime=0}},ar=class{static{l(this,"Thread")}static{v(this,"Thread")}runner;loop;processor;paused;terminated;next_calls;interface;routine;start_time;delay;repeat;sleep_until;constructor(t){this.runner=t,this.loop=!1,this.processor=new Lr(this.runner),this.paused=!1,this.terminated=!1,this.next_calls=[],this.interface={pause:v(()=>this.pause(),"pause"),resume:v(()=>this.resume(),"resume"),stop:v(()=>this.stop(),"stop"),status:"running"}}addCall(t){this.next_calls.indexOf(t)<0&&this.next_calls.push(t)}loadNext(){let t,e,s,i;return this.next_calls.length>0?(e=this.next_calls.splice(0,1)[0],e instanceof K?this.processor.load(e):(s=new Er(e,""),s.parse(),i=s.program,t=new wr(i),this.processor.load(t.routine),(e==="update()"||e==="serverUpdate()")&&this.runner.updateControls!=null&&this.runner.updateControls()),!0):!1}pause(){return this.interface.status==="running"?(this.interface.status="paused",this.paused=!0,1):0}resume(){return this.interface.status==="paused"?(this.interface.status="running",this.paused=!1,1):0}stop(){return this.interface.status="stopped",this.terminated=!0,1}},Rr=class{static{l(this,"Runner")}static{v(this,"Runner")}l8bvm;initialized;system;main_thread;threads;current_thread;thread_index;fps;fps_max;cpu_load;triggers_controls_update;updateControls;onNativeError;profiler;constructor(t){this.l8bvm=t,this.initialized=!1,this.threads=[],this.current_thread=null,this.thread_index=0,this.fps=60,this.fps_max=60,this.cpu_load=0,this.triggers_controls_update=!1,this.onNativeError=null,this.profiler=new nr(null)}reportNativeError(t){this.onNativeError?this.onNativeError(t):console.error(t)}init(){return this.initialized=!0,this.l8bvm.context.global.system||(this.l8bvm.context.global.system={}),this.system=this.l8bvm.context.global.system,this.system.preemptive=1,this.system.threads=[],this.main_thread=new ar(this),this.threads=[this.main_thread],this.current_thread=this.main_thread,this.thread_index=0,this.profiler=new nr(this.main_thread.processor),this.system.profiler={start:v(()=>{this.main_thread.processor.profilingEnabled=!0,this.profiler.start()},"start"),stop:v(()=>(this.main_thread.processor.profilingEnabled=!1,this.profiler.stop()),"stop"),getMetrics:v(()=>this.profiler.getAverageMetrics(),"getMetrics")},this.l8bvm.context.global.print=this.l8bvm.context.meta.print,this.l8bvm.context.global.random=new rt(0),this.l8bvm.context.global.Function={bind:v(function(t){let e;return this instanceof K?(e=this.clone(),e.object=t,e):this},"bind")},this.l8bvm.context.global.Math=tr,this.l8bvm.context.global.JSON=Zi,this.l8bvm.context.global.List=er,this.l8bvm.context.global.Function={bind:v((...t)=>t[0].bind.apply(t[0],t.slice(1)),"bind")},this.l8bvm.context.global.String={...sr,fromCharCode:v(function(){return String.fromCharCode.apply(null,arguments)},"fromCharCode")},this.l8bvm.context.global.Number={parse:v(t=>{let e=Number.parseFloat(t);return isFinite(e)?e:0},"parse"),toString:v(function(){return this.toString()},"toString")},this.l8bvm.context.global.Object={"+":v((t,e)=>t!=null?t+e:e,"+"),"-":v((t,e)=>t-e,"-"),"*":v((t,e)=>t*e,"*"),"/":v((t,e)=>t/e,"/"),"%":v((t,e)=>t%e,"%")},this.fps=60,this.fps_max=60,this.cpu_load=0,this.l8bvm.context.meta.print("LootiScript 1.0"),this.triggers_controls_update=!0}run(t,e="",s){let i,r,n,a,o,u,g,y,O=null,b;if(this.initialized||this.init(),u=new Er(t,e),u.parse(),u.error_info!=null)throw r=u.error_info,r.type="compile",r;if(u.warnings.length>0)for(y=u.warnings,a=0,o=y.length;a<o;a++)switch(b=y[a],n=e+"-"+b.line+"-"+b.column,b.type){case"assigning_api_variable":this.l8bvm.context.warnings.assigning_api_variable[n]==null&&(this.l8bvm.context.warnings.assigning_api_variable[n]={file:e,line:b.line,column:b.column,expression:b.identifier});break;case"assignment_as_condition":this.l8bvm.context.warnings.assignment_as_condition[n]==null&&(this.l8bvm.context.warnings.assignment_as_condition[n]={file:e,line:b.line,column:b.column})}return g=u.program,i=new wr(g),O=null,i.routine.callback=A=>s!=null?s(Le.toString(A)):O=A,this.main_thread.addCall(i.routine),this.tick(),O}call(t,e){let s,i;if(t==="draw"||t==="update"||t==="serverUpdate"){this.l8bvm.context.global[t]!=null&&this.main_thread.addCall(`${t}()`);return}if(this.l8bvm.context.global[t]!=null)if(e==null||!e.length)this.main_thread.addCall(`${t}()`);else{if(i=this.l8bvm.context.global[t],i instanceof K)return s=this.main_thread.processor.routineAsFunction(i,this.l8bvm.context),s(...e);if(typeof i=="function")return i(...e)}else return 0}toString(t){return Le.toString(t)}process(t,e){let s;return s=t.processor,s.time_limit=e,this.current_thread=t,s.run(this.l8bvm.context)}tick(){let t,e,s,i,r,n,a,o,u,g,y,O,b,A;for(this.system.fps!=null&&(this.fps=this.fps*.9+this.system.fps*.1),this.fps_max=Math.max(this.fps,this.fps_max),this.fps<59?a=10:a=Math.floor(1e3/this.fps*.8),O=performance.now(),b=O+100,A=this.system.preemptive?b:1/0,u=this.main_thread.processor,u.done||(this.main_thread.sleep_until!=null?performance.now()>=this.main_thread.sleep_until&&(delete this.main_thread.sleep_until,this.process(this.main_thread,A)):this.process(this.main_thread,A));u.done&&performance.now()<A&&this.main_thread.loadNext();)this.process(this.main_thread,A);for(b=O+a,A=this.system.preemptive?b:1/0,this.main_thread.processor.profilingEnabled&&this.profiler.frame(),o=!0;o;){for(o=!1,g=this.threads,i=0,r=g.length;i<r;i++)if(y=g[i],y!==this.main_thread){if(y.paused||y.terminated)continue;if(u=y.processor,!u.done)y.sleep_until!=null?performance.now()>=y.sleep_until&&(delete y.sleep_until,this.process(y,A),o=!0):(this.process(y,A),o=!0);else if(y.start_time!=null)if(y.repeat)for(;O>=y.start_time&&!(y.paused||y.terminated);)O>=y.start_time+150?y.start_time=O+(y.delay||0):y.start_time+=y.delay||0,u.load(y.routine),this.process(y,A),o=!0;else O>=y.start_time&&(delete y.start_time,u.load(y.routine),this.process(y,A),o=!0);else y.terminated=!0}if(performance.now()>b)break}let m=1;for(e=1;e<this.threads.length;e++)if(y=this.threads[e],y.terminated){if(s=this.system.threads.indexOf(y.interface),s>=0){let J=this.system.threads.length-1;s!==J&&(this.system.threads[s]=this.system.threads[J]),this.system.threads.length--}}else this.threads[m++]=this.threads[e];this.threads.length=m,y=this.threads[0],t=performance.now()-O;let j=b-O;n=t/j*100,this.cpu_load=this.cpu_load*.9+n*.1,this.system.cpu_load=Math.min(100,Math.round(this.cpu_load))}createThread(t,e,s){let i,r;for(r=new ar(this),r.routine=t,this.threads.push(r),r.start_time=performance.now()+e-1e3/this.fps,s&&(r.repeat=s,r.delay=e),this.system.threads.push(r.interface),i=0;i<t.import_values.length;i++)t.import_values[i]===t&&(t.import_values[i]=r.interface);return r.interface}sleep(t){this.current_thread!=null&&(this.current_thread.sleep_until=performance.now()+Math.max(0,t))}};function Cr(){let t=globalThis;return t.process?.env?.NODE_ENV==="development"||t.Bun?.env?.NODE_ENV==="development"}l(Cr,"isDevelopmentMode");v(Cr,"isDevelopmentMode");var ba=class{static{l(this,"Stack2")}static{v(this,"Stack")}stack;index;touched;constructor(){this.stack=["stack[stack_index]"],this.index=0,this.touched={}}push(e){return this.stack[++this.index]=e,this.touched[this.index]=!0}pop(){let e;return this.index>=0?e=this.stack.splice(this.index,1)[0]:this.stack[this.index]!=null?e=this.stack[this.index]:e="stack[stack_index-"+this.index+"]",this.index-=1,e}get(e=0){let s;return e==null&&(e=0),s=this.index+e,s>=0?this.stack[s]:this.stack[s]!=null?this.stack[s]:"stack[stack_index-"+-s+"]"}},ih=class{static{l(this,"Transpiler2")}static{v(this,"Transpiler")}vcount=0;stack;locals;variables;opcodeHandlers;constructor(){this.opcodeHandlers={LOAD_VALUE:this.LOAD_VALUE.bind(this),LOAD_LOCAL:this.LOAD_LOCAL.bind(this),LOAD_LOCAL_OBJECT:this.LOAD_LOCAL_OBJECT.bind(this),STORE_LOCAL:this.STORE_LOCAL.bind(this),POP:this.POP.bind(this),CREATE_PROPERTY:this.CREATE_PROPERTY.bind(this),LOAD_PROPERTY:this.LOAD_PROPERTY.bind(this),LOAD_PROPERTY_ATOP:this.LOAD_PROPERTY_ATOP.bind(this),NEW_OBJECT:this.NEW_OBJECT.bind(this),NEW_ARRAY:this.NEW_ARRAY.bind(this),MAKE_OBJECT:this.MAKE_OBJECT.bind(this),STORE_VARIABLE:this.STORE_VARIABLE.bind(this),STORE_PROPERTY:this.STORE_PROPERTY.bind(this)}}transpile(t){for(let e=0;e<t.opcodes.length;e++){let s=E[t.opcodes[e]];if(this.transpilable(s,t.arg1[e])){let i=e+1;for(;i<t.opcodes.length&&t.removeable(i)&&this.transpilable(E[t.opcodes[i]],t.arg1[i]);)i+=1;i-=1,i-e>=2&&this.transpileSegment(t,e,i)}}}transpileSegment(t,e,s){let i,r,n,a,o;for(this.vcount=0,this.stack=new ba,this.locals={},this.variables={},o="",a=e;a<=s;a++){let u=E[t.opcodes[a]],g=this.opcodeHandlers[u];g?i=g(t.arg1[a]):i=void 0,i&&(o+=i+`
|
|
160
|
+
`)}for(n in this.stack.touched)if(this.stack.touched[n]){let u=Number(n);u<0?o+="stack[stack_index-"+Math.abs(u)+"] = "+this.stack.stack[u]+` ;
|
|
161
|
+
`:u>0?o+="stack[stack_index+"+n+"] = "+this.stack.stack[u]+` ;
|
|
162
|
+
`:o+="stack[stack_index] = "+this.stack.stack[u]+` ;
|
|
163
|
+
`}this.stack.index<0?o+="stack_index -= "+Math.abs(this.stack.index)+` ;
|
|
164
|
+
`:this.stack.index>0&&(o+="stack_index += "+this.stack.index+` ;
|
|
165
|
+
`),o+=`return stack_index ;
|
|
166
|
+
`,Cr()&&console.info(`Transpiled body:
|
|
167
|
+
`+o);try{let u=new Function("stack","stack_index","locals","locals_offset","object","global",o);t.opcodes[e]=E.COMPILED,t.arg1[e]=u}catch(u){r=u,console.error("Transpilation failed:"),console.error(o),console.error(r)}for(a=e+1;a<=s;a++)t.remove(e+1)}createVariable(){return"v"+this.vcount++}transpilable(t,e){return t==="LOAD_VALUE"?typeof e=="string"||typeof e=="number":this.opcodeHandlers[t]!=null}LOAD_VALUE(t){return typeof t=="string"?this.stack.push(' "'+t.replace(/"/g,'\\"')+'" '):typeof t=="number"&&this.stack.push(t+""),""}LOAD_LOCAL(t){let e=this.createVariable();return this.stack.push(e),"let "+e+" = locals[locals_offset+"+t+"] ; // LOAD_LOCAL"}LOAD_LOCAL_OBJECT(t){let e,s;return this.locals[t]!=null?(s=this.locals[t],this.stack.push(s),"if (typeof "+s+' != "object") { '+s+" = locals[locals_offset+"+t+"] = {} } ;"):(s=this.createVariable(),e="let "+s+" = locals[locals_offset+"+t+`] ;
|
|
168
|
+
if (typeof `+s+' != "object") { '+s+" = locals[locals_offset+"+t+"] = {} } ;",this.stack.push(s),this.locals[t]=s,e)}STORE_LOCAL(t){let e=this.stack.get();return"locals[locals_offset+"+t+"] = "+e+" ; // STORE_LOCAL"}POP(){return this.stack.pop(),""}CREATE_PROPERTY(t){let e=this.stack.get(-2)+"["+this.stack.get(-1)+"] = "+this.stack.get()+" ;";return this.stack.pop(),this.stack.pop(),e}LOAD_PROPERTY(t){let e,s;return s=this.createVariable(),e="let "+s+" = "+this.stack.get(-1)+"["+this.stack.get()+`] ; // LOAD_PROPERTY
|
|
169
|
+
if (`+s+" == null) { "+s+" = 0 ; }",this.stack.pop(),this.stack.pop(),this.stack.push(s),e}LOAD_PROPERTY_ATOP(t){let e,s;return s=this.createVariable(),e="let "+s+" = "+this.stack.get(-1)+"["+this.stack.get()+`] ; // LOAD_PROPERTY_ATOP
|
|
170
|
+
if (`+s+" == null) { "+s+" = 0 ; }",this.stack.push(s),e}NEW_OBJECT(){let t=this.createVariable();return this.stack.push(t),"let "+t+" = {} ;"}NEW_ARRAY(){let t=this.createVariable();return this.stack.push(t),"let "+t+" = [] ;"}MAKE_OBJECT(){let t,e;return e=this.createVariable(),t="let "+e+" = "+this.stack.get()+` ;
|
|
171
|
+
if (typeof `+e+' != "object") '+e+" = {} ; ",this.stack.pop(),this.stack.push(e),t}STORE_VARIABLE(t){return this.variables[t]!=null?this.variables[t]+' = object["'+t+'"] = '+this.stack.get()+" ; // STORE_VARIABLE":'object["'+t+'"] = '+this.stack.get()+" ; // STORE_VARIABLE"}STORE_PROPERTY(t){let e,s;return s=this.createVariable(),e="let "+s+" = "+this.stack.get(-2)+"["+this.stack.get(-1)+"] = "+this.stack.get(0)+" ; // STORE_PROPERTY",this.stack.pop(),this.stack.pop(),this.stack.pop(),this.stack.push(s),e}};var Ta=Object.defineProperty,$t=l((t,e)=>Ta(t,"name",{value:e,configurable:!0}),"__name"),Gt=class{static{l(this,"StorageService")}static{$t(this,"StorageService")}namespace;cache=new Map;pendingWrites=new Map;writeTimer=null;runtime;constructor(t="/l8b",e=!1,s){this.namespace=t,this.runtime=s,!e&&typeof localStorage<"u"&&this.clear()}get(t){if(!t||typeof t!="string"||t.trim()==="")return N(this.runtime?.listener,_.E7063,{key:String(t)}),null;if(this.cache.has(t))return this.cache.get(t);if(typeof localStorage<"u")try{let e=`${this.namespace}.${t}`,s=localStorage.getItem(e);if(s!==null){let i=JSON.parse(s);return this.cache.set(t,i),i}}catch(e){N(this.runtime?.listener,_.E7062,{error:`Get operation failed: ${String(e)}`})}return null}set(t,e){if(!t||typeof t!="string"||t.trim()===""){N(this.runtime?.listener,_.E7063,{key:String(t)});return}if(this.cache.set(t,e),this.pendingWrites.set(t,e),this.writeTimer===null){let s=typeof window<"u"&&typeof window.setTimeout=="function"?window.setTimeout.bind(window):setTimeout;this.writeTimer=s(()=>{this.flush()},100)}}flush(){if(this.writeTimer!==null&&(clearTimeout(this.writeTimer),this.writeTimer=null),typeof localStorage>"u"){this.pendingWrites.clear();return}for(let[t,e]of this.pendingWrites)try{let s=`${this.namespace}.${t}`,i=JSON.stringify(this.sanitize(e));localStorage.setItem(s,i)}catch(s){s.name==="QuotaExceededError"||s.code===22?N(this.runtime?.listener,_.E7061,{}):N(this.runtime?.listener,_.E7062,{error:`Set operation failed: ${String(s)}`})}this.pendingWrites.clear()}check(){this.pendingWrites.size>0&&this.flush()}delete(t){if(!t||typeof t!="string"||t.trim()===""){N(this.runtime?.listener,_.E7063,{key:String(t)});return}if(this.cache.delete(t),this.pendingWrites.delete(t),typeof localStorage<"u")try{localStorage.removeItem(`${this.namespace}.${t}`)}catch(e){N(this.runtime?.listener,_.E7062,{error:`Delete operation failed: ${String(e)}`})}}clear(){if(typeof localStorage>"u")return;let t=`${this.namespace}.`,e=[];for(let s=0;s<localStorage.length;s++){let i=localStorage.key(s);i&&i.startsWith(t)&&e.push(i)}for(let s of e)localStorage.removeItem(s);this.cache.clear(),this.pendingWrites.clear()}sanitize(t,e=new WeakSet){if(t==null)return t;if(typeof t!="object")return typeof t=="function"?void 0:t;if(e.has(t))return;if(e.add(t),Array.isArray(t))return t.map(i=>this.sanitize(i,e)).filter(i=>i!==void 0);let s={};for(let i in t)if(Object.hasOwn(t,i)){let r=this.sanitize(t[i],e);r!==void 0&&(s[i]=r)}return s}interfaceCache=null;getInterface(){return this.interfaceCache?this.interfaceCache:(this.interfaceCache={set:$t((t,e)=>this.set(t,e),"set"),get:$t(t=>this.get(t),"get"),delete:$t(t=>this.delete(t),"delete")},this.interfaceCache)}};var va=Object.defineProperty,z=l((t,e)=>va(t,"name",{value:e,configurable:!0}),"__name"),Ir={round:z(t=>Math.round(t),"round"),floor:z(t=>Math.floor(t),"floor"),ceil:z(t=>Math.ceil(t),"ceil"),abs:z(t=>Math.abs(t),"abs"),min:z((t,e)=>Math.min(t,e),"min"),max:z((t,e)=>Math.max(t,e),"max"),sqrt:z(t=>Math.sqrt(t),"sqrt"),pow:z((t,e)=>t**e,"pow"),sin:z(t=>Math.sin(t),"sin"),cos:z(t=>Math.cos(t),"cos"),tan:z(t=>Math.tan(t),"tan"),asin:z(t=>Math.asin(t),"asin"),acos:z(t=>Math.acos(t),"acos"),atan:z(t=>Math.atan(t),"atan"),atan2:z((t,e)=>Math.atan2(t,e),"atan2"),sind:z(t=>Math.sin(t/180*Math.PI),"sind"),cosd:z(t=>Math.cos(t/180*Math.PI),"cosd"),tand:z(t=>Math.tan(t/180*Math.PI),"tand"),asind:z(t=>Math.asin(t)*180/Math.PI,"asind"),acosd:z(t=>Math.acos(t)*180/Math.PI,"acosd"),atand:z(t=>Math.atan(t)*180/Math.PI,"atand"),atan2d:z((t,e)=>Math.atan2(t,e)*180/Math.PI,"atan2d"),log:z(t=>Math.log(t),"log"),exp:z(t=>Math.exp(t),"exp"),random:new rt(0),PI:Math.PI,true:1,false:0},Mr=z(t=>console.log(t),"_defaultPrint");function si(t){return{...Ir,print:t??Mr}}l(si,"createMetaFunctions");z(si,"createMetaFunctions");function Wt(t,e){return{meta:{...Ir,print:t.print??Mr,...t},global:e,local:e,object:e,breakable:0,continuable:0,returnable:0,stack_size:0,timeout:Date.now()+3e3,warnings:{using_undefined_variable:{},assigning_field_to_undefined:{},invoking_non_function:{},assigning_api_variable:{},assignment_as_condition:{}}}}l(Wt,"createVMContext");z(Wt,"createVMContext");function qt(){Array.prototype.insert||(Array.prototype.insert=function(t){return this.splice(0,0,t),t}),Array.prototype.insertAt||(Array.prototype.insertAt=function(t,e){return e>=0&&e<this.length?this.splice(e,0,t):this.push(t),t}),Array.prototype.remove||(Array.prototype.remove=function(t){return t>=0&&t<this.length?this.splice(t,1)[0]:0}),Array.prototype.removeElement||(Array.prototype.removeElement=function(t){let e=this.indexOf(t);return e>=0?this.splice(e,1)[0]:0}),Array.prototype.contains||(Array.prototype.contains=function(t){return this.indexOf(t)>=0?1:0}),Array.prototype.sortList||(Array.prototype.sortList=function(t){return t?this.sort(t):this.sort()})}l(qt,"setupArrayExtensions");z(qt,"setupArrayExtensions");function zt(t,e,s,i){let r=typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:t?.message??String(t),n=t?.stackTrace;return!n&&i?.main_thread?.processor?.generateStackTrace&&(n=i.main_thread.processor.generateStackTrace()),{error:r,type:t?.type??s,line:t?.line,column:t?.column,file:t?.file??e,stack:t?.stack,stackTrace:n}}l(zt,"extractErrorInfo");z(zt,"extractErrorInfo");var Ht=class{static{l(this,"L8BVM")}static{z(this,"L8BVM")}context;runner;storage_service;error_info=null;constructor(t={},e={},s="/l8b",i=!1){this.context=Wt(t,e),this.storage_service=new Gt(s,i),this.context.global.storage=this.storage_service.getInterface(),this.runner=new Rr(this),this.runner.init(),qt()}run(t,e=3e3,s=""){this.error_info=null,this.context.timeout=Date.now()+e,this.context.stack_size=0;try{let i=this.runner.run(t,s);return this.storage_service.check(),i!=null?this.runner.toString(i):null}catch(i){throw this.error_info=zt(i,s,"runtime",this.runner),i}}call(t,e=[],s=3e3){this.error_info=null,this.context.timeout=Date.now()+s,this.context.stack_size=0;try{let i=this.runner.call(t,...e);return this.storage_service.check(),i}catch(i){throw this.error_info=zt(i,t,"call",this.runner),i}}loadRoutine(t,e=""){this.error_info=null;try{let s;t instanceof K?s=t:s=new K(0).import(Nr(t)),this.runner.main_thread.addCall(s),this.runner.tick()}catch(s){throw this.error_info=zt(s,e,"compile"),s}}clearWarnings(){this.context.warnings={using_undefined_variable:{},assigning_field_to_undefined:{},invoking_non_function:{},assigning_api_variable:{},assignment_as_condition:{}}}getWarnings(){return this.context.warnings||{}}toString(t){return this.runner.toString(t)}};function Nr(t){return Dr(t)?t.routine:t}l(Nr,"normalizeSerializedRoutine");z(Nr,"normalizeSerializedRoutine");function Dr(t){return typeof t=="object"&&t!==null&&"format"in t&&t.format==="l8b-compiled-routine"&&"routine"in t}l(Dr,"isCompiledModuleArtifact");z(Dr,"isCompiledModuleArtifact");var nt=class{static{l(this,"SourceUpdater")}vm;listener;audio;screen;reportWarnings;emitBridgeEvent;updateMemory={};previousInit=null;constructor(e,s,i,r,n,a){this.vm=e,this.listener=s,this.audio=i,this.screen=r,this.reportWarnings=n,this.emitBridgeEvent=a}updateSource(e,s,i=!1){if(!this.vm||s===this.updateMemory[e])return!1;this.updateMemory[e]=s,this.audio&&this.audio.cancelBeeps(),this.screen&&this.screen.clear();try{if(this.vm.run(s,3e3,e),this.emitBridgeEvent&&this.emitBridgeEvent("compile_success",{file:e}),this.reportWarnings&&this.reportWarnings(),this.vm.error_info){let r=Object.assign({},this.vm.error_info);return r.type="init",r.file=e,this.listener.reportError?.(r),!1}if(this.vm.runner?.getFunctionSource){let r=this.vm.runner.getFunctionSource("init");if(r&&r!==this.previousInit&&i&&(this.previousInit=r,this.vm.call("init"),this.vm.error_info)){let n=Object.assign({},this.vm.error_info);n.type="init",this.listener.reportError?.(n)}}return!0}catch(r){return r.file=e,this.listener.reportError?.(r),!1}}};var Aa=Object.defineProperty,ce=l((t,e)=>Aa(t,"name",{value:e,configurable:!0}),"__name"),ii=ce(()=>({press:{},release:{}}),"createState"),Fr={0:"A",1:"B",2:"X",3:"Y",4:"LB",5:"RB",8:"VIEW",9:"MENU",10:"LS",11:"RS",12:"DPAD_UP",13:"DPAD_DOWN",14:"DPAD_LEFT",15:"DPAD_RIGHT"},Ur={6:"LT",7:"RT"},Yr=ce(t=>t?(t.press??={},t.release??={},t):ii(),"ensureState"),ri=class{static{l(this,"GamepadInput")}static{ce(this,"GamepadInput")}status;previous;count=0;constructor(){this.status=ii(),this.previous={global:ii()}}update(){let t=this.getGamepads();if(!t){this.count=0;return}let e=0;for(let s=0;s<t.length;s++){let i=t[s];if(!i)break;e++,this.status[s]=Yr(this.status[s]),this.previous[s]=Yr(this.previous[s]);for(let[r,n]of Object.entries(Fr)){let a=Number(r),o=i.buttons[a];o&&(this.status[s][n]=o.pressed?1:0)}for(let[r,n]of Object.entries(Ur)){let a=Number(r),o=i.buttons[a];o&&(this.status[s][n]=o.value??0)}i.axes.length>=2&&this.updateStick(i.axes[0],-i.axes[1],this.status[s],"LEFT"),i.axes.length>=4&&this.updateStick(i.axes[2],-i.axes[3],this.status[s],"RIGHT")}this.aggregateStatus(t,e),this.count=e,this.updateChanges(this.status,this.previous.global);for(let s=0;s<e;s++)this.updateChanges(this.status[s],this.previous[s]);for(let s=e;s<4;s++)delete this.status[s],delete this.previous[s]}getGamepads(){if(typeof navigator>"u"||!navigator.getGamepads)return null;try{return navigator.getGamepads()}catch{return null}}updateStick(t,e,s,i){let r=Math.sqrt(t*t+e*e),n=Math.floor((Math.atan2(e,t)+Math.PI*2)%(Math.PI*2)/(Math.PI*2)*360);s[`${i}_STICK_ANGLE`]=n,s[`${i}_STICK_AMOUNT`]=r,s[`${i}_STICK_UP`]=e>.5?1:0,s[`${i}_STICK_DOWN`]=e<-.5?1:0,s[`${i}_STICK_LEFT`]=t<-.5?1:0,s[`${i}_STICK_RIGHT`]=t>.5?1:0}aggregateStatus(t,e){for(let[s,i]of Object.entries(Fr)){this.status[i]=0;let r=Number(s);for(let n of t){if(!n)break;if(n.buttons[r]?.pressed){this.status[i]=1;break}}}for(let[s,i]of Object.entries(Ur)){this.status[i]=0;let r=Number(s);for(let n of t){if(!n)break;let a=n.buttons[r];a&&(this.status[i]=a.value??0)}}this.status.UP=0,this.status.DOWN=0,this.status.LEFT=0,this.status.RIGHT=0,this.status.LEFT_STICK_UP=0,this.status.LEFT_STICK_DOWN=0,this.status.LEFT_STICK_LEFT=0,this.status.LEFT_STICK_RIGHT=0,this.status.RIGHT_STICK_UP=0,this.status.RIGHT_STICK_DOWN=0,this.status.RIGHT_STICK_LEFT=0,this.status.RIGHT_STICK_RIGHT=0,this.status.LEFT_STICK_ANGLE=0,this.status.LEFT_STICK_AMOUNT=0,this.status.RIGHT_STICK_ANGLE=0,this.status.RIGHT_STICK_AMOUNT=0,this.status.RT=0,this.status.LT=0;for(let s=0;s<e;s++){let i=this.status[s];i&&(i.UP=i.DPAD_UP||i.LEFT_STICK_UP||i.RIGHT_STICK_UP?1:0,i.DOWN=i.DPAD_DOWN||i.LEFT_STICK_DOWN||i.RIGHT_STICK_DOWN?1:0,i.LEFT=i.DPAD_LEFT||i.LEFT_STICK_LEFT||i.RIGHT_STICK_LEFT?1:0,i.RIGHT=i.DPAD_RIGHT||i.LEFT_STICK_RIGHT||i.RIGHT_STICK_RIGHT?1:0,i.UP&&(this.status.UP=1),i.DOWN&&(this.status.DOWN=1),i.LEFT&&(this.status.LEFT=1),i.RIGHT&&(this.status.RIGHT=1),i.LEFT_STICK_UP&&(this.status.LEFT_STICK_UP=1),i.LEFT_STICK_DOWN&&(this.status.LEFT_STICK_DOWN=1),i.LEFT_STICK_LEFT&&(this.status.LEFT_STICK_LEFT=1),i.LEFT_STICK_RIGHT&&(this.status.LEFT_STICK_RIGHT=1),i.RIGHT_STICK_UP&&(this.status.RIGHT_STICK_UP=1),i.RIGHT_STICK_DOWN&&(this.status.RIGHT_STICK_DOWN=1),i.RIGHT_STICK_LEFT&&(this.status.RIGHT_STICK_LEFT=1),i.RIGHT_STICK_RIGHT&&(this.status.RIGHT_STICK_RIGHT=1),i.LT&&(this.status.LT=i.LT),i.RT&&(this.status.RT=i.RT),(i.LEFT_STICK_AMOUNT??0)>(this.status.LEFT_STICK_AMOUNT??0)&&(this.status.LEFT_STICK_AMOUNT=i.LEFT_STICK_AMOUNT,this.status.LEFT_STICK_ANGLE=i.LEFT_STICK_ANGLE),(i.RIGHT_STICK_AMOUNT??0)>(this.status.RIGHT_STICK_AMOUNT??0)&&(this.status.RIGHT_STICK_AMOUNT=i.RIGHT_STICK_AMOUNT,this.status.RIGHT_STICK_ANGLE=i.RIGHT_STICK_ANGLE))}}updateChanges(t,e){for(let s in t.press)t.press[s]=0;for(let s in t.release)t.release[s]=0;for(let s in e)s==="press"||s==="release"||e[s]&&!t[s]&&(t.release[s]=1);for(let s in t)s==="press"||s==="release"||t[s]&&!e[s]&&(t.press[s]=1);for(let s in e)s==="press"||s==="release"||(e[s]=0);for(let s in t)s==="press"||s==="release"||(e[s]=t[s])}},Br=200,jr=-1e4,Pa=/Escape|(F\d+)/,Vr="mouse",ni=typeof document<"u",Tt=ce((t,e,s)=>{let i=t.getBoundingClientRect(),r=Math.min(t.clientWidth,t.clientHeight)||1,n=(e-i.left-t.clientWidth/2)/r*Br,a=(t.clientHeight/2-(s-i.top))/r*Br;return{x:n,y:a}},"computeRelativePosition"),ai=class{static{l(this,"KeyboardInput")}static{ce(this,"KeyboardInput")}state={press:{},release:{},UP:0,DOWN:0,LEFT:0,RIGHT:0};previous={};dirtyKeys=new Set;constructor(t=ni?document:void 0){t&&(t.addEventListener("keydown",e=>this.handleKeyDown(e)),t.addEventListener("keyup",e=>this.handleKeyUp(e)))}convertCode(t){let e="",s=!1;for(let i=0;i<t.length;i++){let r=t.charAt(i);r===r.toUpperCase()&&s?(e+="_",s=!1):s=!0,e+=r.toUpperCase()}return e}handleKeyDown(t){t.altKey||t.ctrlKey||t.metaKey||Pa.test(t.key)||t.preventDefault();let e=this.convertCode(t.code),s=t.key.toUpperCase();this.state[e]=1,this.state[s]=1,this.dirtyKeys.add(e),this.dirtyKeys.add(s),this.updateDirectional()}handleKeyUp(t){let e=this.convertCode(t.code),s=t.key.toUpperCase();this.state[e]=0,this.state[s]=0,this.dirtyKeys.add(e),this.dirtyKeys.add(s),this.updateDirectional()}updateDirectional(){this.state.UP=this.state.KEY_W||this.state.ARROW_UP||0,this.state.DOWN=this.state.KEY_S||this.state.ARROW_DOWN||0,this.state.LEFT=this.state.KEY_A||this.state.ARROW_LEFT||0,this.state.RIGHT=this.state.KEY_D||this.state.ARROW_RIGHT||0}update(){for(let t of this.dirtyKeys)this.state.press[t]&&(this.state.press[t]=0),this.state.release[t]&&(this.state.release[t]=0);for(let t of this.dirtyKeys){let e=this.state[t],s=this.previous[t]||0;e&&!s?this.state.press[t]=1:!e&&s&&(this.state.release[t]=1),this.previous[t]=e}this.dirtyKeys.clear()}reset(){for(let t in this.state)t==="press"||t==="release"||(this.state[t]=0);for(let t in this.previous)this.previous[t]=0;this.dirtyKeys.clear()}},oi=class{static{l(this,"MouseInput")}static{ce(this,"MouseInput")}state={x:jr,y:jr,pressed:0,left:0,middle:0,right:0,press:0,release:0,wheel:0};previousPressed=!1;wheel=0;canvas;removeListeners;constructor(t){t&&this.setCanvas(t)}setCanvas(t){this.detach(),this.canvas=t,this.attach()}syncFromTouch(t,e,s){this.state.x=t,this.state.y=e,s?(this.state.left=1,this.state.middle=0,this.state.right=0,this.state.pressed=1):(this.state.left=0,this.state.middle=0,this.state.right=0,this.state.pressed=0)}update(){this.state.pressed&&!this.previousPressed?(this.previousPressed=!0,this.state.press=1):this.state.press=0,!this.state.pressed&&this.previousPressed?(this.previousPressed=!1,this.state.release=1):this.state.release=0,this.state.wheel=this.wheel,this.wheel=0}attach(){if(!ni)return;let t=document,e=ce(a=>this.handleMouseDown(a),"onDown"),s=ce(a=>this.handleMouseMove(a),"onMove"),i=ce(a=>this.handleMouseUp(a),"onUp"),r=ce(a=>this.handleWheel(a),"onWheel"),n=ce(a=>this.handleWheel(a),"onDomWheel");t.addEventListener("mousedown",e,{passive:!1}),t.addEventListener("mousemove",s,{passive:!1}),t.addEventListener("mouseup",i,{passive:!1}),t.addEventListener("mousewheel",r,{passive:!1}),t.addEventListener("DOMMouseScroll",n,{passive:!1}),this.removeListeners=()=>{t.removeEventListener("mousedown",e),t.removeEventListener("mousemove",s),t.removeEventListener("mouseup",i),t.removeEventListener("mousewheel",r),t.removeEventListener("DOMMouseScroll",n)}}detach(){this.removeListeners?.(),this.removeListeners=void 0,this.canvas=void 0}handleMouseDown(t){if(!this.canvas)return;t.preventDefault();let{x:e,y:s}=Tt(this.canvas,t.clientX,t.clientY);switch(this.state.x=e,this.state.y=s,t.button){case 0:this.state.left=1;break;case 1:this.state.middle=1;break;case 2:this.state.right=1;break}this.state.pressed=Math.min(1,this.state.left+this.state.right+this.state.middle)}handleMouseMove(t){if(!this.canvas)return;t.preventDefault();let{x:e,y:s}=Tt(this.canvas,t.clientX,t.clientY);this.state.x=e,this.state.y=s}handleMouseUp(t){if(!this.canvas)return;t.preventDefault();let{x:e,y:s}=Tt(this.canvas,t.clientX,t.clientY);switch(this.state.x=e,this.state.y=s,t.button){case 0:this.state.left=0;break;case 1:this.state.middle=0;break;case 2:this.state.right=0;break}this.state.pressed=Math.min(1,this.state.left+this.state.right+this.state.middle)}handleWheel(t){let e=t;typeof e.deltaY=="number"&&e.deltaY!==0?this.wheel=e.deltaY>0?-1:1:typeof e.wheelDelta=="number"&&e.wheelDelta!==0?this.wheel=e.wheelDelta<0?-1:1:typeof e.detail=="number"&&e.detail!==0?this.wheel=e.detail>0?-1:1:this.wheel=0,t.preventDefault()}},hi=class{static{l(this,"TouchInput")}static{ce(this,"TouchInput")}mouse;state={touching:0,x:0,y:0,press:0,release:0,touches:[]};touches=new Map;previousTouching=!1;canvas;removeListeners;constructor(t,e){this.mouse=t,e&&this.setCanvas(e)}setCanvas(t){this.detach(),this.canvas=t,this.attach()}update(){this.syncMouseTouch();let t=[];for(let[e,{x:s,y:i}]of this.touches.entries())t.push({id:e,x:s,y:i}),this.state.x=s,this.state.y=i;this.state.touches=t,this.state.touching=this.touches.size>0?1:0,this.state.touching&&!this.previousTouching?(this.previousTouching=!0,this.state.press=1):this.state.press=0,!this.state.touching&&this.previousTouching?(this.previousTouching=!1,this.state.release=1):this.state.release=0}syncMouseTouch(){let t=this.mouse.state;t.pressed?this.touches.set(Vr,{x:t.x,y:t.y}):this.touches.delete(Vr)}attach(){if(!ni)return;let t=ce(i=>this.handleTouchStart(i),"onStart"),e=ce(i=>this.handleTouchMove(i),"onMove"),s=ce(i=>this.handleTouchEnd(i),"onEnd");document.addEventListener("touchstart",t,{passive:!1}),document.addEventListener("touchmove",e,{passive:!1}),document.addEventListener("touchend",s,{passive:!1}),document.addEventListener("touchcancel",s,{passive:!1}),this.removeListeners=()=>{document.removeEventListener("touchstart",t),document.removeEventListener("touchmove",e),document.removeEventListener("touchend",s),document.removeEventListener("touchcancel",s)}}detach(){this.removeListeners?.(),this.removeListeners=void 0,this.canvas=void 0,this.touches.clear()}handleTouchStart(t){if(this.canvas){t.preventDefault(),t.stopPropagation();for(let e=0;e<t.changedTouches.length;e++){let s=t.changedTouches[e],{x:i,y:r}=Tt(this.canvas,s.clientX,s.clientY);this.touches.set(s.identifier,{x:i,y:r}),this.mouse.syncFromTouch(i,r,!0)}}}handleTouchMove(t){if(this.canvas){t.preventDefault(),t.stopPropagation();for(let e=0;e<t.changedTouches.length;e++){let s=t.changedTouches[e];if(!this.touches.has(s.identifier))continue;let{x:i,y:r}=Tt(this.canvas,s.clientX,s.clientY);this.touches.set(s.identifier,{x:i,y:r}),this.mouse.syncFromTouch(i,r,!0)}}}handleTouchEnd(t){if(this.canvas){t.preventDefault(),t.stopPropagation();for(let e=0;e<t.changedTouches.length;e++){let s=t.changedTouches[e];this.touches.delete(s.identifier)}this.mouse.syncFromTouch(this.state.x,this.state.y,!1)}}},nl=class{static{l(this,"Input")}static{ce(this,"Input")}keyboard;mouse;touch;gamepad;runtime;constructor(t,e){this.runtime=e,this.keyboard=new ai,this.mouse=new oi(t),this.touch=new hi(this.mouse,t),this.gamepad=new ri}update(){this.keyboard.update(),this.mouse.update(),this.touch.update(),this.gamepad.update()}getKeyboard(){return!this.keyboard||!this.keyboard.state?(N(this.runtime?.listener,_.E7052,{error:"Keyboard state not available"}),{}):this.keyboard.state}getMouse(){return!this.mouse||!this.mouse.state?(N(this.runtime?.listener,_.E7052,{error:"Mouse state not available"}),{}):this.mouse.state}getTouch(){return!this.touch||!this.touch.state?(N(this.runtime?.listener,_.E7052,{error:"Touch state not available"}),{}):this.touch.state}getGamepad(){return(!this.gamepad||!navigator.getGamepads)&&N(this.runtime?.listener,_.E7051,{device:"gamepad"}),this.gamepad}setCanvas(t){this.mouse.setCanvas(t),this.touch.setCanvas(t)}};var at=class{static{l(this,"InputManager")}keyboard;mouse;touch;gamepad;constructor(e){this.keyboard=new ai,this.mouse=new oi,this.touch=new hi(this.mouse),this.gamepad=new ri,e&&this.attachCanvas(e)}attachCanvas(e){this.mouse.setCanvas(e),this.touch.setCanvas(e)}update(){this.keyboard.update(),this.mouse.update(),this.touch.update(),this.gamepad.update()}getStates(){return{keyboard:this.keyboard.state,mouse:this.mouse.state,touch:this.touch.state,gamepad:this.gamepad.status}}};var ot=class{static{l(this,"GameLoop")}callbacks;state;stopped=!1;animationFrameId=null;constructor(e){this.callbacks=e,this.state={currentFrame:0,floatingFrame:0,dt:Fi,lastTime:performance.now(),fps:60,updateRate:60},this.loop=this.loop.bind(this)}start(){this.stopped=!1,this.state.lastTime=performance.now(),this.state.currentFrame=0,this.state.floatingFrame=0,this.loop()}stop(){this.stopped=!0,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}resume(){this.stopped&&(this.stopped=!1,this.state.lastTime=performance.now(),this.loop())}loop(){if(this.stopped)return;this.animationFrameId=requestAnimationFrame(this.loop);let e=performance.now();Math.abs(e-this.state.lastTime)>Ui&&(this.state.lastTime=e-Rt);let s=e-this.state.lastTime;this.state.dt=this.state.dt*.9+s*.1,this.state.lastTime=e;let i=Math.round(1e3/this.state.dt);this.state.fps=i,this.callbacks.setFPS&&this.callbacks.setFPS(i);let r=this.state.updateRate;if(this.callbacks.getUpdateRate){let a=this.callbacks.getUpdateRate();a!=null&&a>0&&Number.isFinite(a)&&(r=a)}this.state.floatingFrame+=this.state.dt*r/1e3;let n=Math.min(10,Math.round(this.state.floatingFrame-this.state.currentFrame));(n===0||n===2)&&r===60&&Math.abs(i-60)<2&&(n=1,this.state.floatingFrame=this.state.currentFrame+1);for(let a=1;a<=n;a++)this.callbacks.onUpdate(),a<n&&this.callbacks.onTick&&this.callbacks.onTick();this.state.currentFrame+=n,this.callbacks.onDraw(),this.callbacks.onTick&&this.callbacks.onTick(),n>0&&this.callbacks.onWatchStep&&this.callbacks.onWatchStep()}getState(){return this.state}setUpdateRate(e){e>0&&Number.isFinite(e)&&(this.state.updateRate=e)}getFPS(){return this.state.fps}};var ht=class{static{l(this,"System")}systemAPI;constructor(){this.systemAPI={get time(){return Date.now()},fps:60,cpu_load:0,update_rate:60,get language(){return typeof navigator<"u"?navigator.language:"en"},inputs:{get keyboard(){return 1},get mouse(){return 1},get touch(){return typeof window<"u"&&"ontouchstart"in window?1:0},get gamepad(){return typeof navigator<"u"&&typeof navigator.getGamepads=="function"?1:0}},loading:0,prompt:l((e,s)=>{if(typeof window<"u"){let i=window.prompt(e);i!==null&&s&&s(i)}},"prompt"),say:l(e=>{typeof window<"u"&&window.alert(e)},"say"),file:{dropped:0},javascript:{},disable_autofullscreen:0,preemptive:1}}getAPI(){return this.systemAPI}setFPS(e){this.systemAPI.fps=e}setCPULoad(e){this.systemAPI.cpu_load=e}setLoading(e){this.systemAPI.loading=e}};var Kt=class{static{l(this,"DebugLogger")}lastInputDebug;lastScreenDebug;debugInputs(e,s){if(!s?.input)return;let i=this.createInputSnapshot(e,s.input);i&&(this.lastInputDebug&&ka(i,this.lastInputDebug)||(this.lastInputDebug=i,console.debug("[@al8b/runtime][input]",i)))}debugScreen(e,s){if(!s?.screen)return;let i=e.getCanvas(),r={width:e.width,height:e.height,canvasWidth:i.width,canvasHeight:i.height};this.lastScreenDebug&&r.width===this.lastScreenDebug.width&&r.height===this.lastScreenDebug.height&&r.canvasWidth===this.lastScreenDebug.canvasWidth&&r.canvasHeight===this.lastScreenDebug.canvasHeight||(this.lastScreenDebug=r,console.debug("[@al8b/runtime][screen]",{screen:{width:e.width,height:e.height},canvas:{width:i.width,height:i.height,clientWidth:i.clientWidth,clientHeight:i.clientHeight,style:{width:i.style.width,height:i.style.height}}}))}createInputSnapshot(e,s){let i=Oa(s);if(i.length===0)return null;let r=e.getStates(),n={};return i.includes("touch")&&(n.touch={touching:r.touch.touching,press:r.touch.press,release:r.touch.release,x:Number(r.touch.x?.toFixed?.(2)??r.touch.x),y:Number(r.touch.y?.toFixed?.(2)??r.touch.y),count:r.touch.touches?.length??0}),i.includes("mouse")&&(n.mouse={pressed:r.mouse.pressed,left:r.mouse.left,x:Number(r.mouse.x?.toFixed?.(2)??r.mouse.x),y:Number(r.mouse.y?.toFixed?.(2)??r.mouse.y),wheel:r.mouse.wheel}),i.includes("keyboard")&&(n.keyboard={UP:r.keyboard.UP,DOWN:r.keyboard.DOWN,LEFT:r.keyboard.LEFT,RIGHT:r.keyboard.RIGHT,press:r.keyboard.press,release:r.keyboard.release}),i.includes("gamepad")&&(n.gamepad={count:e.gamepad.count,A:r.gamepad.A,B:r.gamepad.B,UP:r.gamepad.UP,DOWN:r.gamepad.DOWN,LEFT:r.gamepad.LEFT,RIGHT:r.gamepad.RIGHT}),Object.keys(n).length===0?null:n}};function Oa(t){if(typeof t=="boolean")return t?["keyboard","mouse","touch","gamepad"]:[];let e=[];return t.keyboard&&e.push("keyboard"),t.mouse&&e.push("mouse"),t.touch&&e.push("touch"),t.gamepad&&e.push("gamepad"),e}l(Oa,"getEnabledInputChannels");function ka(t,e){if(t===e)return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;let s=Object.keys(t),i=Object.keys(e);if(s.length!==i.length)return!1;for(let r of s){let n=t[r],a=e[r];if(n!==a){if(n==null||a==null){if(n!==a)return!1;continue}if(typeof n=="object"&&typeof a=="object"){let o=Object.keys(n),u=Object.keys(a);if(o.length!==u.length)return!1;for(let g of o)if(n[g]!==a[g])return!1}else return!1}}return!0}l(ka,"shallowEqual");function Sa(t){if(t.code||t.context||t.suggestions)return t;let e=t.code||"E2005",s=ve(e,{file:t.file,line:t.line,column:t.column,context:t.context,suggestions:t.suggestions,related:t.related,stackTrace:t.stackTrace,data:{error:t.error||t.message}}),i=Te(s);return{...t,...s,formatted:i}}l(Sa,"formatRuntimeError");function we(t,e){if(t.reportError){let s=Sa(e);t.reportError(s)}}l(we,"reportError");function ui(t,e){if(!t)return;let s=t.context?.warnings;if(s){if(s.invoking_non_function)for(let i of Object.values(s.invoking_non_function)){let r=i;r.reported||(r.reported=!0,we(e,{error:"",type:"non_function",expression:r.expression,line:r.line,column:r.column,file:r.file}))}if(s.using_undefined_variable)for(let i of Object.values(s.using_undefined_variable)){let r=i;r.reported||(r.reported=!0,we(e,{error:"",type:"undefined_variable",expression:r.expression,line:r.line,column:r.column,file:r.file}))}}}l(ui,"reportWarnings");var Jt=class{static{l(this,"RuntimeAssetsRegistry")}collections={sprites:{},maps:{},sounds:{},music:{},assets:{}};replace(e){this.collections=e}getCollections(){return this.collections}get sprites(){return this.collections.sprites}get maps(){return this.collections.maps}get sounds(){return this.collections.sounds}get music(){return this.collections.music}get assets(){return this.collections.assets}};var xa=Object.defineProperty,La=l((t,e)=>xa(t,"name",{value:e,configurable:!0}),"__name"),$r=/^#[0-9A-Fa-f]{6}$/,Gr=class vt{static{l(this,"_Palette")}static{La(this,"Palette")}colors;name;rgbCache;runtime;constructor(e={},s){this.runtime=s,"colors"in e&&Array.isArray(e.colors)?this.validatePaletteFormat(e.colors)?(this.colors=[...e.colors],this.name=e.name||"Custom"):(N(this.runtime?.listener,_.E7072,{format:"invalid color array"}),this.colors=[],this.name="Invalid"):(this.colors=[],this.name="Empty"),this.rgbCache=new Map}validatePaletteFormat(e){return Array.isArray(e)?e.every(s=>typeof s=="string"&&$r.test(s)):!1}get(e){return!isFinite(e)||e<0?(N(this.runtime?.listener,_.E7073,{index:e,maxIndex:this.colors.length-1}),"#000000"):this.colors.length===0?"#000000":this.colors[e%this.colors.length]||"#000000"}getRGB(e){if(this.rgbCache.has(e))return this.rgbCache.get(e);let s=this.get(e),i=this.hexToRGB(s);return this.rgbCache.set(e,i),i}getAll(){return[...this.colors]}get size(){return this.colors.length}get paletteName(){return this.name}set(e,s){if(!isFinite(e)||e<0){N(this.runtime?.listener,_.E7073,{index:e,maxIndex:this.colors.length-1});return}if(!$r.test(s)){N(this.runtime?.listener,_.E7072,{format:s});return}for(;this.colors.length<=e;)this.colors.push("#000000");this.colors[e]=s,this.rgbCache.delete(e)}add(e){return this.colors.push(e),this.colors.length-1}remove(e){e>=0&&e<this.colors.length&&(this.colors.splice(e,1),this.rgbCache.clear())}setPalette(e){if(!this.validatePaletteFormat(e)){N(this.runtime?.listener,_.E7072,{format:"invalid color array"});return}this.colors=[...e],this.rgbCache.clear()}reset(e){e&&(this.colors=[...e.colors],this.name=e.name),this.rgbCache.clear()}hexToRGB(e){let s=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return s?{r:Number.parseInt(s[1],16),g:Number.parseInt(s[2],16),b:Number.parseInt(s[3],16)}:{r:0,g:0,b:0}}static rgbToHex(e,s,i){return"#"+((1<<24)+(e<<16)+(s<<8)+i).toString(16).slice(1).toUpperCase()}findClosest(e){let s=this.hexToRGB(e),i=0,r=Number.POSITIVE_INFINITY;for(let n=0;n<this.colors.length;n++){let a=this.getRGB(n),o=(s.r-a.r)**2+(s.g-a.g)**2+(s.b-a.b)**2;o<r&&(r=o,i=n)}return i}gradient(e,s,i){let r=this.getRGB(e),n=this.getRGB(s),a=[];for(let o=0;o<i;o++){let u=o/(i-1),g=Math.round(r.r+(n.r-r.r)*u),y=Math.round(r.g+(n.g-r.g)*u),O=Math.round(r.b+(n.b-r.b)*u);a.push(vt.rgbToHex(g,y,O))}return a}lighten(e,s=.2){let i=this.getRGB(e),r=Math.min(255,Math.round(i.r+(255-i.r)*s)),n=Math.min(255,Math.round(i.g+(255-i.g)*s)),a=Math.min(255,Math.round(i.b+(255-i.b)*s));return vt.rgbToHex(r,n,a)}darken(e,s=.2){let i=this.getRGB(e),r=Math.max(0,Math.round(i.r*(1-s))),n=Math.max(0,Math.round(i.g*(1-s))),a=Math.max(0,Math.round(i.b*(1-s)));return vt.rgbToHex(r,n,a)}mix(e,s,i=.5){let r=this.getRGB(e),n=this.getRGB(s),a=Math.round(r.r+(n.r-r.r)*i),o=Math.round(r.g+(n.g-r.g)*i),u=Math.round(r.b+(n.b-r.b)*i);return vt.rgbToHex(a,o,u)}toData(){return{name:this.name,colors:this.getAll()}}};var At=class{static{l(this,"ObjectPool")}pool=[];factory;reset;maxSize;constructor(e,s,i=100){this.factory=e,this.reset=s,this.maxSize=i}acquire(){return this.pool.length>0?this.pool.pop():this.factory()}release(e){this.pool.length>=this.maxSize||(this.reset(e),this.pool.push(e))}clear(){this.pool=[]}size(){return this.pool.length}getMaxSize(){return this.maxSize}setMaxSize(e){this.maxSize=e,this.pool.length>e&&(this.pool=this.pool.slice(0,e))}};function zr(t){return{print:l(e=>{let s=t.getVM();(typeof e=="object"||typeof e=="function")&&s&&(e=s.toString(e)),t.listener.log?t.listener.log(String(e)):console.log(e)},"print")}}l(zr,"createRuntimeMeta");function Wr(t){let e=t.input.getStates(),s={user:l(()=>Qt(t.getSessionSnapshot()?.user??null),"user"),player:l(()=>Qt(t.getSessionSnapshot()?.player??null),"player"),game:l(()=>Qt(t.getSessionSnapshot()?.game??null),"game"),room:l(()=>Qt(t.getSessionSnapshot()?.room??null),"room")},i={emit:l((n,a)=>{t.sendHostEvent({type:n,payload:a,source:"host"})},"emit"),request:l((n,a,o)=>t.sendHostRequest(n,a,o),"request")},r={export:l(()=>t.exportSnapshot(),"export"),import:l(n=>t.importSnapshot(n),"import"),reset:l(n=>t.resetRuntime(n),"reset"),save:l((n,a)=>t.saveSnapshot(n,a),"save"),load:l((n,a)=>t.loadSnapshot(n,a),"load")};return{screen:t.screen.getInterface(),audio:t.audio.getInterface(),keyboard:e.keyboard,mouse:e.mouse,touch:e.touch,gamepad:e.gamepad,sprites:t.assets.sprites,maps:t.assets.maps,sounds:t.assets.sounds,music:t.assets.music,assets:t.assets.assets,player:t.playerService.getInterface(),host:i,session:s,memory:r,system:t.system.getAPI(),scene:l((n,a)=>{let o=qr(wa(a),t.getVM(),t.listener);t.sceneManager.registerScene(n,o)},"scene"),route:l((n,a)=>t.sceneManager.registerRoute(n,a),"route"),router:t.sceneManager.router.getInterface(),Image:Se,Sprite:st,TileMap:Xe,Sound:Me,Palette:Gr,Random:rt,ObjectPool:At}}l(Wr,"createRuntimeGlobalApi");function qr(t,e,s){if(!e?.runner?.main_thread?.processor)return s.log?.("[RuntimeController] VM not ready for scene conversion. Scene functions may not work correctly."),t;let i=e.runner.main_thread.processor,r=e.context,n={};for(let[a,o]of Object.entries(t)){if(o instanceof K){n[a]=i.routineAsFunction(o,r);continue}if(o&&typeof o=="object"&&!Array.isArray(o)){n[a]=qr(o,e,s);continue}n[a]=o}return n}l(qr,"convertSceneDefinition");function wa(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Scene definition must be an object.");return t}l(wa,"asSceneDefinition");function Qt(t){return t==null?t:JSON.parse(JSON.stringify(t))}l(Qt,"cloneValue");function Kr(t={}){return new fi(t)}l(Kr,"createRuntime");var fi=class{static{l(this,"RuntimeControllerImpl")}options;listener;assetRegistry=new Jt;assetLoader;debugLogger=new Kt;DEBUG_UPDATE_FREQUENCY=10;snapshotRestorer=new Ws;bridgeUnsubscribe=null;sourceUpdater=null;gameLoop=null;frameCount=0;lastUpdateRate=-1;isStopped=!1;preserveStorageOnNextBoot;sessionSnapshot;screen;audio;input;system;playerService;sceneManager;vm=null;timeMachine=null;constructor(e={}){this.options=e,this.listener=e.listener||{},this.preserveStorageOnNextBoot=e.preserveStorage||!1,this.sessionSnapshot=e.initialSession||null,this.screen=new Ki({runtime:this,canvas:e.canvas,width:e.width||400,height:e.height||400}),this.audio=new Ai(this),this.input=new at(this.screen.getCanvas()),this.system=new ht,this.playerService=new Bi({pause:l(()=>this.stop(),"pause"),resume:l(()=>this.resume(),"resume"),postMessage:l(s=>this.emitPlayerMessage(s),"postMessage"),getFps:l(()=>this.system.getAPI().fps,"getFps"),getUpdateRate:l(()=>this.system.getAPI().update_rate,"getUpdateRate"),setUpdateRate:l(s=>{this.system.getAPI().update_rate=s},"setUpdateRate")}),this.sceneManager=new $i,this.assetLoader=new it(e.url||"",e.resources||{},this.audio,this.listener),this.logStep("RuntimeController constructed",{width:this.screen.width,height:this.screen.height,resources:{images:e.resources?.images?.length??0,sounds:e.resources?.sounds?.length??0,music:e.resources?.music?.length??0}})}get sprites(){return this.assetRegistry.sprites}get maps(){return this.assetRegistry.maps}get sounds(){return this.assetRegistry.sounds}get music(){return this.assetRegistry.music}get assets(){return this.assetRegistry.assets}get stopped(){return this.isStopped}getSession(){return this.sessionSnapshot?Hr(this.sessionSnapshot):null}async start(){this.logStep("startup: begin"),await this.hydrateSession(),this.ensureBridgeSubscription(),this.logStep("startup: loading assets"),await this.loadAssets(),this.logStep("startup: assets loaded",{sprites:Object.keys(this.sprites).length,maps:Object.keys(this.maps).length,sounds:Object.keys(this.sounds).length,music:Object.keys(this.music).length,assets:Object.keys(this.assets).length}),this.logStep("startup: waiting for asset readiness"),await this.waitForAssetsReady(),this.logStep("startup: assets ready"),this.logStep("startup: initializing VM"),this.initializeVM(),this.logStep("startup: VM ready",{sourceFiles:Object.keys(this.options.sources||{}).length}),this.logStep("startup: starting game loop"),this.startGameLoop(),this.isStopped=!1,this.logStep("startup: completed")}stop(){this.logStep("lifecycle: stop requested"),this.isStopped=!0,this.gameLoop?.stop(),this.audio.stopAll()}resume(){this.logStep("lifecycle: resume requested"),this.isStopped=!1,this.gameLoop?.resume()}async reset(e={}){this.logStep("lifecycle: reset requested",e);let s=e.preserveSnapshot?this.exportSnapshot():null,i=e.preserveSession??!0,r=e.preserveStorage??this.options.preserveStorage??!1;this.stop(),this.teardownRuntimeState(),i||(this.sessionSnapshot=null),this.preserveStorageOnNextBoot=r,await this.start(),s&&await this.importSnapshot(s)}exportSnapshot(){let e=this.vm?.context?.global,s=this.sceneManager.router.getState();return{version:1,global:e?Ra(e):{},session:this.getSession(),router:{path:s.path,sceneName:this.sceneManager.getCurrentSceneName()},system:{updateRate:this.system.getAPI().update_rate}}}async importSnapshot(e){this.vm?.context?.global&&(this.snapshotRestorer.restoreState(this.vm.context.global,e.global),this.system.getAPI().update_rate=e.system.updateRate,this.updateGameLoopUpdateRate(),e.session&&(this.sessionSnapshot=Hr(e.session)),e.router.path?this.sceneManager.router.replace(e.router.path):e.router.sceneName&&this.sceneManager.setActiveScene(e.router.sceneName))}updateSource(e,s,i=!1){return this.sourceUpdater?this.sourceUpdater.updateSource(e,s,i):!1}handleMessage(e){if(e){if(typeof e=="object"&&"type"in e&&typeof e.type=="string"){this.sendHostEvent(e);return}e.name==="time_machine"&&this.timeMachine&&this.timeMachine.messageReceived(e)}}sendHostEvent(e){this.handleHostEvent(e)}getCanvas(){return this.screen.getCanvas()}async loadAssets(){let e=await this.assetLoader.loadAll();this.assetRegistry.replace(e)}async waitForAssetsReady(){return new Promise(e=>{let s=l(()=>{if(this.assetLoader.isReady()){this.system.setLoading(100),e();return}let i=this.assetLoader.getProgress();this.system.setLoading(Math.floor(i*100)),this.assetLoader.showLoadingBar(this.screen.getInterface()),requestAnimationFrame(s)},"checkReady");s()})}initializeVM(){this.logStep("vm: building meta/global APIs");let e={listener:this.listener,options:this.options,screen:this.screen,audio:this.audio,input:this.input,system:this.system,playerService:this.playerService,sceneManager:this.sceneManager,assets:this.assetRegistry,bridge:this.options.bridge,getVM:l(()=>this.vm,"getVM"),getSessionSnapshot:l(()=>this.getSession(),"getSessionSnapshot"),sendHostEvent:l(r=>this.emitBridgeEvent(r.type,r.payload),"sendHostEvent"),sendHostRequest:l((r,n,a)=>this.sendBridgeRequest(r,n,a),"sendHostRequest"),exportSnapshot:l(()=>this.exportSnapshot(),"exportSnapshot"),importSnapshot:l(r=>this.importSnapshot(r),"importSnapshot"),resetRuntime:l(r=>this.reset(r),"resetRuntime"),saveSnapshot:l((r,n)=>this.saveSnapshot(r,n),"saveSnapshot"),loadSnapshot:l((r,n)=>this.loadSnapshot(r,n),"loadSnapshot")},s=zr(e),i=Wr(e);this.vm=new Ht(s,i,this.options.namespace||"/l8b",this.preserveStorageOnNextBoot),this.sourceUpdater=new nt(this.vm,this.listener,this.audio,this.screen,()=>ui(this.vm,this.listener),(r,n)=>this.emitBridgeEvent(r,n)),this.timeMachine=new Xi(this),this.timeMachine.onStatus(r=>{this.emitBridgeEvent("time_machine_status",{status:r})}),this.loadPrograms(),this.initializeScenesAndRouter(),this.emitBridgeEvent("runtime.started",{})}loadPrograms(){if(!this.vm)return;let e=this.options.compiledRoutines||{},s=this.options.sources||{};if(Object.keys(e).length>0){this.logStep("vm: loading compiled routines",{files:Object.keys(e)});for(let[i,r]of Object.entries(e))try{this.vm.loadRoutine(r,i)}catch(n){we(this.listener,{error:n.message||String(n),type:"compile",stack:n.stack,file:i}),this.logStep("vm: routine load error",{file:i,message:n?.message||String(n)})}}else if(Object.keys(s).length>0){this.logStep("vm: executing sources",{files:Object.keys(s)});for(let[i,r]of Object.entries(s))this.sourceUpdater?.updateSource(i,r,!1)}else this.logStep("vm: no sources or compiled routines provided");try{this.vm.call("init"),this.vm.runner.tick(),this.logStep("vm: init() executed")}catch(i){we(this.listener,{error:i.message||String(i),type:"init",stack:i.stack}),this.logStep("vm: init() error",{message:i?.message||String(i)})}}initializeScenesAndRouter(){let e=this.sceneManager.registry.getNames();this.logStep("router: initializing",{registeredScenes:e.length,sceneNames:e}),this.sceneManager.router.init();let s=this.sceneManager.hasActiveScene()?this.sceneManager.getCurrentSceneName?.()||"unknown":null,i=this.sceneManager.router.getState();this.logStep("router: initialized",{activeScene:s||"none",path:i.path,hasActiveScene:this.sceneManager.hasActiveScene()})}startGameLoop(){this.logStep("loop: creating game loop"),this.gameLoop=new ot({onUpdate:l(()=>this.handleUpdate(),"onUpdate"),onDraw:l(()=>this.handleDraw(),"onDraw"),onTick:l(()=>this.handleTick(),"onTick"),onWatchStep:l(()=>this.handleWatchStep(),"onWatchStep"),getUpdateRate:l(()=>{if(this.vm)try{return this.vm.context?.global?.system?.update_rate}catch{return}},"getUpdateRate"),setFPS:l(e=>{if(this.vm)try{this.vm.context?.global?.system&&(this.vm.context.global.system.fps=e)}catch{}},"setFPS")}),this.gameLoop.start(),this.logStep("loop: started")}updateGameLoopUpdateRate(){if(!(!this.vm||!this.gameLoop))try{let e=this.vm.context?.global?.system?.update_rate,s=e!=null&&e>0&&Number.isFinite(e)?e:60;s!==this.lastUpdateRate&&(this.lastUpdateRate=s,this.gameLoop.setUpdateRate(s))}catch{}}handleUpdate(){if(this.vm){this.frameCount++,this.input.update(),this.frameCount%this.DEBUG_UPDATE_FREQUENCY===0&&(this.debugLogger.debugInputs(this.input,this.options.debug),this.debugLogger.debugScreen(this.screen,this.options.debug)),this.gameLoop&&(this.system.setFPS(this.gameLoop.getFPS()),this.updateGameLoopUpdateRate());try{if(this.sceneManager.hasActiveScene()?this.sceneManager.update():(this.vm.call("update"),this.vm.runner.tick()),this.vm.error_info){let e=Object.assign({},this.vm.error_info);e.type="update",we(this.listener,e)}}catch(e){we(this.listener,{error:e.message||String(e),type:"update",stack:e.stack})}}}handleDraw(){if(this.vm){try{if(this.screen.initDraw(),this.screen.updateInterface(),this.sceneManager.hasActiveScene()?this.sceneManager.draw():(this.vm.call("draw"),this.vm.runner.tick()),ui(this.vm,this.listener),this.vm.error_info){let e=Object.assign({},this.vm.error_info);e.type="draw",we(this.listener,e)}}catch(e){we(this.listener,{error:e.message||String(e),type:"draw",stack:e.stack})}this.timeMachine?.step()}}handleTick(){this.vm?.runner&&this.vm.runner.tick?.()}handleWatchStep(){this.timeMachine?.loopStep()}ensureBridgeSubscription(){if(this.bridgeUnsubscribe||!this.options.bridge?.subscribe)return;let e=this.options.bridge.subscribe(s=>this.handleHostEvent(s));this.bridgeUnsubscribe=typeof e=="function"?e:null}handleHostEvent(e){switch(e.type){case"session.update":this.mergeSession(e.payload);break;case"runtime.reset":this.reset(Ia(e.payload));break;case"runtime.import_snapshot":Ma(e.payload)&&this.importSnapshot(e.payload);break;case"runtime.export_snapshot":this.emitBridgeEvent("runtime.snapshot",this.exportSnapshot());break;case"runtime.stop":case"runtime.pause":this.stop();break;case"runtime.resume":this.resume();break;case"time_machine":if(this.timeMachine&<(e.payload)){let s=e.payload.command;typeof s=="string"&&this.timeMachine.messageReceived({name:"time_machine",command:s,position:typeof e.payload.position=="number"?e.payload.position:void 0})}break}}emitPlayerMessage(e){lt(e)&&typeof e.type=="string"?this.emitBridgeEvent(e.type,e):this.emitBridgeEvent("player.message",e)}emitBridgeEvent(e,s){this.options.bridge?.emit?.(e,s)}sendBridgeRequest(e,s,i){let r=this.options.bridge?.request;if(!r)return i?.({ok:!1,error:`No runtime bridge request handler registered for "${e}"`}),null;let n=Ca(e);try{let a=r(e,s);return Xt(a)?a.then(o=>i?.(o)).catch(o=>i?.({ok:!1,error:o instanceof Error?o.message:String(o)})):i?.(a),n}catch(a){return i?.({ok:!1,error:a instanceof Error?a.message:String(a)}),n}}saveSnapshot(e,s){let i=this.exportSnapshot(),r=this.options.bridge?.saveSnapshot;if(!r){let n={ok:!1,error:"No runtime bridge saveSnapshot handler registered",snapshot:i};return s?.(n),n}try{let n=r(i,e);return Xt(n)?(n.then(()=>s?.({ok:!0,snapshot:i})).catch(a=>s?.({ok:!1,error:a instanceof Error?a.message:String(a)})),null):(s?.({ok:!0,snapshot:i}),{ok:!0,snapshot:i})}catch(n){let a={ok:!1,error:n instanceof Error?n.message:String(n)};return s?.(a),a}}loadSnapshot(e,s){let i=this.options.bridge?.loadSnapshot;if(!i){let r={ok:!1,error:"No runtime bridge loadSnapshot handler registered"};return s?.(r),r}try{let r=i(e);return Xt(r)?(r.then(async n=>{n&&await this.importSnapshot(n),s?.({ok:!0,snapshot:n})}).catch(n=>s?.({ok:!1,error:n instanceof Error?n.message:String(n)})),null):(r&&this.importSnapshot(r),s?.({ok:!0,snapshot:r}),r)}catch(r){let n={ok:!1,error:r instanceof Error?r.message:String(r)};return s?.(n),n}}async hydrateSession(){if(this.sessionSnapshot)return;let e=this.options.bridge?.getSession;if(!e){this.sessionSnapshot=this.options.initialSession||null;return}try{let s=e();this.sessionSnapshot=Xt(s)?await s:s}catch{this.sessionSnapshot=this.options.initialSession||null}}mergeSession(e){if(!lt(e))return;let s=this.sessionSnapshot||{};this.sessionSnapshot={...s,...e}}teardownRuntimeState(){this.gameLoop=null,this.sourceUpdater=null,this.vm=null,this.timeMachine=null,this.frameCount=0,this.lastUpdateRate=-1,this.isStopped=!1,this.sceneManager.registry.clear(),this.sceneManager.routeManager.clear()}logStep(e,s){if(!this.options.debug?.lifecycle)return;let i="[@al8b/runtime][lifecycle]";if(s!==void 0?console.info(`${i} ${e}`,s):console.info(`${i} ${e}`),this.listener.log)try{let r=s===void 0?"":` ${JSON.stringify(s)}`;this.listener.log(`${i} ${e}${r}`)}catch{this.listener.log(`${i} ${e}`)}}};function Ra(t){let e=t,s=[e.random,e.screen,e.audio,e.keyboard,e.mouse,e.touch,e.gamepad,e.system,e.storage,e.host,e.session,e.memory].filter(i=>i!=null);return Zt(e,s)}l(Ra,"serializeGlobalSnapshot");function Zt(t,e=[]){if(t==null)return t;if(e.includes(t))return null;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(s=>Zt(s,e));if(typeof t=="object"){let s={};for(let[i,r]of Object.entries(t))s[i]=Zt(r,e);return s}return null}l(Zt,"deepCloneValue");function Hr(t){return Zt(t)}l(Hr,"cloneSnapshot");function Ca(t){return`${t}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`}l(Ca,"createRequestId");function Xt(t){return typeof t=="object"&&t!==null&&"then"in t&&typeof t.then=="function"}l(Xt,"isPromiseLike");function lt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}l(lt,"isRecord");function Ia(t){return lt(t)?t:void 0}l(Ia,"asRecord");function Ma(t){return!(!lt(t)||t.version!==1||!lt(t.global)||!("router"in t)||!("session"in t))}l(Ma,"isRuntimeSnapshot");function Na(t){if(typeof structuredClone<"u")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return t}}l(Na,"deepClone");function Da(t,e){if(t===e)return!0;if(typeof t!="object"||typeof e!="object"||t===null||e===null)return!1;let s=t,i=e,r=Object.keys(s),n=Object.keys(i);if(r.length!==n.length)return!1;for(let a of r)if(!(a in i)||s[a]!==i[a])return!1;return!0}l(Da,"shallowEqual");return tn(Fa);})();
|