@al8b/runtime 0.1.12 → 0.1.14

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.
Files changed (56) hide show
  1. package/dist/assets/index.d.mts +0 -1
  2. package/dist/assets/index.d.ts +0 -1
  3. package/dist/assets/loader.d.mts +0 -1
  4. package/dist/assets/loader.d.ts +0 -1
  5. package/dist/browser/index.js +780 -2681
  6. package/dist/browser/index.js.map +1 -1
  7. package/dist/browser/index.min.js +27 -39
  8. package/dist/core/api-factory.d.mts +1 -5
  9. package/dist/core/api-factory.d.ts +1 -5
  10. package/dist/core/api-factory.js +17 -38
  11. package/dist/core/api-factory.js.map +1 -1
  12. package/dist/core/api-factory.mjs +18 -38
  13. package/dist/core/api-factory.mjs.map +1 -1
  14. package/dist/core/controller.d.mts +0 -5
  15. package/dist/core/controller.d.ts +0 -5
  16. package/dist/core/controller.js +23 -98
  17. package/dist/core/controller.js.map +1 -1
  18. package/dist/core/controller.mjs +24 -99
  19. package/dist/core/controller.mjs.map +1 -1
  20. package/dist/core/debug-logger.d.mts +0 -1
  21. package/dist/core/debug-logger.d.ts +0 -1
  22. package/dist/core/error-handler.d.mts +1 -2
  23. package/dist/core/error-handler.d.ts +1 -2
  24. package/dist/core/error-handler.js +2 -17
  25. package/dist/core/error-handler.js.map +1 -1
  26. package/dist/core/error-handler.mjs +2 -17
  27. package/dist/core/error-handler.mjs.map +1 -1
  28. package/dist/core/index.d.mts +0 -2
  29. package/dist/core/index.d.ts +0 -2
  30. package/dist/core/index.js +23 -98
  31. package/dist/core/index.js.map +1 -1
  32. package/dist/core/index.mjs +24 -99
  33. package/dist/core/index.mjs.map +1 -1
  34. package/dist/hot-reload/index.d.mts +0 -1
  35. package/dist/hot-reload/index.d.ts +0 -1
  36. package/dist/hot-reload/index.js.map +1 -1
  37. package/dist/hot-reload/index.mjs.map +1 -1
  38. package/dist/hot-reload/updater.d.mts +0 -1
  39. package/dist/hot-reload/updater.d.ts +0 -1
  40. package/dist/hot-reload/updater.js.map +1 -1
  41. package/dist/hot-reload/updater.mjs.map +1 -1
  42. package/dist/index.d.mts +0 -2
  43. package/dist/index.d.ts +0 -2
  44. package/dist/index.js +23 -98
  45. package/dist/index.js.map +1 -1
  46. package/dist/index.mjs +24 -99
  47. package/dist/index.mjs.map +1 -1
  48. package/dist/types/bridge.d.mts +0 -4
  49. package/dist/types/bridge.d.ts +0 -4
  50. package/dist/types/bridge.js.map +1 -1
  51. package/dist/types/index.d.mts +0 -1
  52. package/dist/types/index.d.ts +0 -1
  53. package/dist/types/runtime.d.mts +13 -2
  54. package/dist/types/runtime.d.ts +13 -2
  55. package/dist/types/runtime.js.map +1 -1
  56. package/package.json +46 -50
@@ -1,16 +1,4 @@
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=`
1
+ "use strict";var L8BRuntime=(()=>{var ce=Object.defineProperty;var xr=Object.getOwnPropertyDescriptor;var vr=Object.getOwnPropertyNames;var Sr=Object.prototype.hasOwnProperty;var l=(e,t)=>ce(e,"name",{value:t,configurable:!0});var kr=(e,t)=>{for(var s in t)ce(e,s,{get:t[s],enumerable:!0})},Rr=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of vr(t))!Sr.call(e,r)&&r!==s&&ce(e,r,{get:()=>t[r],enumerable:!(i=xr(t,r))||i.enumerable});return e};var wr=e=>Rr(ce({},"__esModule",{value:!0}),e);var Mn={};kr(Mn,{AssetLoader:()=>Gt,GameLoop:()=>Ht,Image:()=>mt,InputManager:()=>Wt,L8BVM:()=>Re,ObjectPool:()=>ae,Sound:()=>Ot,SourceUpdater:()=>zt,Sprite:()=>jt,StorageService:()=>xe,System:()=>qt,TileMap:()=>Ft,createMetaFunctions:()=>Fs,createRuntime:()=>Lr,createVMContext:()=>Se,deepClone:()=>Dn,setupArrayExtensions:()=>ke,shallowEqual:()=>Nn});var Cr=Object.defineProperty,V=l((e,t)=>Cr(e,"name",{value:t,configurable:!0}),"__name"),Mt=440,Ve=2**(1/12),ze=69,Ir=class{static{l(this,"Beeper")}static{V(this,"Beeper")}audio;notes={};plainNotes={};currentOctave=5;currentDuration=.5;currentVolume=.5;currentSpan=1;currentWaveform="square";constructor(e){this.audio=e,this.initializeNotes()}initializeNotes(){let e=[["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 t=0;t<=127;t++){this.notes[t]=t;let s=Math.floor(t/12)-1;for(let i of e[t%12])this.notes[i+s]=t;if(s===-1)for(let i of e[t%12])this.plainNotes[i]=t}}beep(e){let t="normal",s=[],i=[],r,n=e.split(" ");for(let a of n)if(a!=="")switch(t){case"normal":if(this.notes[a]!==void 0)r=this.notes[a],this.currentOctave=Math.floor(r/12),s.push({frequency:Mt*Ve**(r-ze),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:Mt*Ve**(r-ze),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))t=a;else if(a==="-")s.push({frequency:Mt,volume:0,span:this.currentSpan,duration:this.currentDuration,waveform:this.currentWaveform});else if(a==="end"&&i.length>0&&s.length>0){s.push({frequency:Mt,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":{t="normal";let o=Number.parseFloat(a);!Number.isNaN(o)&&o>0&&(this.currentDuration=60/o);break}case"duration":{t="normal";let o=Number.parseFloat(a);!Number.isNaN(o)&&o>0&&(this.currentDuration=o/1e3);break}case"volume":{t="normal";let o=Number.parseFloat(a);Number.isNaN(o)||(this.currentVolume=o/100);break}case"span":{t="normal";let o=Number.parseFloat(a);Number.isNaN(o)||(this.currentSpan=o/100);break}case"loop":{t="normal",i.push({start:s.length});let o=Number.parseFloat(a);Number.isNaN(o)||(i[i.length-1].repeats=o);break}case"to":if(t="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 _=r+u;u>0?_<=o:_>=o;_+=u)s.push({frequency:Mt*Ve**(_-ze),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:Mt,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)}},Dr=`
14
2
  class L8bAudioProcessor extends AudioWorkletProcessor {
15
3
  constructor() {
16
4
  super();
@@ -132,40 +120,40 @@ class L8bAudioProcessor extends AudioWorkletProcessor {
132
120
  }
133
121
 
134
122
  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+=`
123
+ `,ii=class{static{l(this,"AudioCore")}static{V(this,"AudioCore")}context;buffer=[];playing=[];wakeupList=[];workletNode;beeper;runtime;masterVolume=1;constructor(e){this.runtime=e,this.getContext()}isStarted(){return this.context.state==="running"}addToWakeUpList(e){this.wakeupList.push(e)}interfaceCache=null;setVolume(e){this.masterVolume=Math.max(0,Math.min(1,e))}getVolume(){return this.masterVolume}getInterface(){return this.interfaceCache?this.interfaceCache:(this.interfaceCache={beep:V(e=>this.beep(e),"beep"),cancelBeeps:V(()=>this.cancelBeeps(),"cancelBeeps"),playSound:V((e,t,s,i,r)=>this.playSound(e,t,s,i,r),"playSound"),playMusic:V((e,t,s)=>this.playMusic(e,t,s),"playMusic"),setVolume:V(e=>this.setVolume(e),"setVolume"),getVolume:V(()=>this.getVolume(),"getVolume"),stopAll:V(()=>this.stopAll(),"stopAll")},this.interfaceCache)}playSound(e,t=1,s=1,i=0,r=!1){if(typeof e=="string"){let n=e.replace(/\//g,"-"),a=this.runtime.sounds[n];return a?a.play(t*this.masterVolume,s,i,r):(this.runtime?.listener?.reportError?.({code:"E7013",message:"Sound not found",data:{soundName:n}}),0)}return 0}playMusic(e,t=1,s=!1){if(typeof e=="string"){let i=e.replace(/\//g,"-"),r=this.runtime.music[i];return r?r.play(t*this.masterVolume,s):(this.runtime?.listener?.reportError?.({code:"E7014",message:"Music not found",data:{musicName:i}}),0)}return 0}getContext(){if(!this.context){let e=window.AudioContext||window.webkitAudioContext;if(this.context=new e,this.context.state!=="running"){let t=V(()=>{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",t),document.body.removeEventListener("mouseup",t),document.body.removeEventListener("click",t),document.body.removeEventListener("keydown",t)}},"activate");document.body.addEventListener("touchend",t,{once:!0}),document.body.addEventListener("mouseup",t,{once:!0}),document.body.addEventListener("click",t,{once:!0}),document.body.addEventListener("keydown",t,{once:!0})}else this.beeper&&this.start()}return this.context}async start(){if(!this.workletNode)try{let e=new Blob([Dr],{type:"application/javascript"}),t=URL.createObjectURL(e);await this.context.audioWorklet.addModule(t),this.workletNode=new AudioWorkletNode(this.context,"l8b-audio-processor"),this.workletNode.connect(this.context.destination),this.flushBuffer()}catch(e){this.runtime?.listener?.reportError?.({code:"E7012",message:"Audio worklet error",data:{error:String(e)}})}}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 Ir(this),this.context.state==="running"&&this.start()),this.beeper}beep(e){this.getBeeper().beep(e)}addBeeps(e){for(let t of e)t.duration*=this.context.sampleRate,t.increment=t.frequency/this.context.sampleRate;this.workletNode?this.workletNode.port.postMessage(JSON.stringify({name:"beep",sequence:e})):this.buffer.push(JSON.stringify({name:"beep",sequence:e}))}cancelBeeps(){this.workletNode?this.workletNode.port.postMessage(JSON.stringify({name:"cancel_beeps"})):this.buffer.push(JSON.stringify({name:"cancel_beeps"})),this.stopAll()}addPlaying(e){this.playing.push(e)}removePlaying(e){let t=this.playing.indexOf(e);t>=0&&this.playing.splice(t,1)}stopAll(){for(let e of this.playing)try{e.stop()}catch(t){this.runtime?.listener?.reportError?.({code:"E7016",message:"Audio error",data:{error:String(t)}})}this.playing=[]}},We=class{static{l(this,"Music")}static{V(this,"Music")}ready=1;name="";url;tag;playing=!1;audio;constructor(e,t){this.audio=e,this.url=t,this.tag=new Audio(this.url),this.ready=1}play(e=1,t=!1){return this.playing=!0,this.tag.loop=!!t,this.tag.volume=Math.max(0,Math.min(1,e)),this.audio.isStarted()?this.tag.play():this.audio.addToWakeUpList(this),this.audio.addPlaying(this),{play:V(()=>this.tag.play(),"play"),stop:V(()=>{this.playing=!1,this.tag.pause(),this.audio.removePlaying(this)},"stop"),setVolume:V(s=>{this.tag.volume=Math.max(0,Math.min(1,s))},"setVolume"),getPosition:V(()=>this.tag.currentTime,"getPosition"),getDuration:V(()=>this.tag.duration,"getDuration"),setPosition:V(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)}},Ot=class ri{static{l(this,"_Sound")}static{V(this,"Sound")}ready=0;buffer;name="";url;audio;constructor(t,s){this.audio=t,s instanceof AudioBuffer?(this.buffer=s,this.url="",this.ready=1):(this.url=s,this.loadSound(s))}loadSound(t){let s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType="arraybuffer",s.onload=()=>{this.audio.context.decodeAudioData(s.response,i=>{this.buffer=i,this.ready=1},i=>{this.audio?.runtime?.listener?.reportError?.({code:"E7016",message:"Audio decoding failed",data:{error:`Audio decoding failed: ${String(i)}`}})})},s.onerror=()=>{this.audio?.runtime?.listener?.reportError?.({code:"E7016",message:"Failed to load sound",data:{error:`Failed to load sound: ${t}`}})},s.send()}play(t=1,s=1,i=0,r=!1){if(!this.buffer)return{stop:V(()=>{},"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=t;let u=n.createPanner();u.panningModel="equalpower",u.setPan=A=>{u.setPosition(A,0,1-Math.abs(A))},u.setPan(i),a.connect(o),o.connect(u),u.connect(n.destination),a.start();let _=null;r&&(_={stop:V(()=>{a.stop()},"stop")},this.audio.addPlaying(_));let E={stop:V(()=>(a.stop(),_&&this.audio.removePlaying(_),1),"stop"),setVolume:V(A=>{o.gain.value=Math.max(0,Math.min(1,A))},"setVolume"),setPitch:V(A=>{a.playbackRate.value=Math.max(.001,Math.min(1e3,A))},"setPitch"),setPan:V(A=>{u.setPan(Math.max(-1,Math.min(1,A)))},"setPan"),getDuration:V(()=>a.buffer?a.buffer.duration:0,"getDuration"),finished:!1};return a.onended=()=>{E.finished=!0},E}static createSoundClass(t){return class{static{l(this,"MicroSound")}static{V(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=t.context.createBuffer(i,r,n),this.sound=new ri(t,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 Nr=Object.defineProperty,ot=l((e,t)=>Nr(e,"name",{value:t,configurable:!0}),"__name"),Mr=ot((e,t,s,i,r)=>{e.canvas||(e.canvas=document.createElement("canvas"));let n=t*i,a=s*r;(e.canvas.width!==n||e.canvas.height!==a)&&(e.canvas.width=n,e.canvas.height=a);let o=e.canvas.getContext("2d");if(!o){let u="Failed to get 2D rendering context for tile canvas";throw new Error(u)}return o.clearRect(0,0,e.canvas.width,e.canvas.height),e.animated=[],o},"ensureCanvas"),Fr=ot((e,t,s,i,r,n,a)=>{let o=t.frames[0].canvas;if(!o||o.width===0||o.height===0)return!1;if(a.subX!=null){let u=a.subX*s,_=(a.subY??0)*i;e.drawImage(o,u,_,s,i,s*r,i*n,s,i)}else e.drawImage(o,s*r,i*n);return!0},"drawTile"),Yr=ot((e,t,s,i,r,n,a)=>{let o={x:s*r,y:i*n,w:s,h:i,sprite:t};a.subX!=null&&(o.tx=a.subX*s,o.ty=(a.subY??0)*i),e.animated.push(o)},"queueAnimatedTile"),Ur=ot((e,t,s)=>{let i=performance.now();(!e.buffer||e.buffer.width!==t*(e.canvas.width/t)||e.buffer.height!==s*(e.canvas.height/s))&&(e.buffer=document.createElement("canvas"),e.buffer.width=e.canvas.width,e.buffer.height=e.canvas.height);let r=e.buffer.getContext("2d");r.clearRect(0,0,e.buffer.width,e.buffer.height),r.drawImage(e.canvas,0,0);for(let n of e.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,t,s,n.x,n.y,t,s):r.drawImage(o,n.x,n.y,t,s))}return e.buffer},"renderAnimatedTiles"),Br=ot(e=>e.replace(/\//g,"-"),"normalizeRefForStorage"),ni=ot(e=>e.replace(/-/g,"/"),"normalizeRefForUsage");function He(e){let t=e.indexOf(":");if(t===-1)return{spriteName:e};let s=e.substring(0,t),i=e.substring(t+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(He,"parseTileRef");ot(He,"parseTileRef");var Ft=class ai{static{l(this,"_TileMap")}static{ot(this,"TileMap")}width;height;block_width;block_height;sprites;map=[];ready=!0;needs_update=!1;name="";parsedMap=[];renderState={canvas:null,buffer:null,animated:[]};constructor(t,s,i,r,n){if(t<=0||s<=0||!isFinite(t)||!isFinite(s))throw new Error(`Invalid map dimensions: width=${t}, height=${s}`);this.width=t,this.height=s,this.block_width=i,this.block_height=r,this.sprites=n??{},this.clear()}clear(){for(let t=0;t<this.height;t++)for(let s=0;s<this.width;s++){let i=s+t*this.width;this.map[i]=null,this.parsedMap[i]=null}}set(t,s,i){if(t<0||s<0||t>=this.width||s>=this.height||!isFinite(t)||!isFinite(s))return;let r=i;typeof r=="string"&&(r=Br(r));let n=t+s*this.width;this.map[n]=r,this.parsedMap[n]=r?He(r):null,this.needs_update=!0}get(t,s){if(t<0||s<0||t>=this.width||s>=this.height||!isFinite(t)||!isFinite(s))return 0;let i=this.map[t+s*this.width];return typeof i=="string"&&(i=ni(i)),i||0}getCanvas(){return(this.renderState.canvas==null||this.needs_update)&&this.update(),this.renderState.canvas}draw(t,s,i,r,n){if(this.renderState.animated.length>0){let a=Ur(this.renderState,this.block_width,this.block_height);t.drawImage(a,s,i,r,n)}else t.drawImage(this.getCanvas(),s,i,r,n)}update(){this.needs_update=!1;let t=Mr(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[ni(n.spriteName)];!a||!a.frames[0]||(a.frames.length>1?Yr(this.renderState,a,this.block_width,this.block_height,i,s,n):Fr(t,a,this.block_width,this.block_height,i,s,n))}}loadFile(t,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",t),i.send()}load(t,s){let i=JSON.parse(t);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]=He(u)}else this.map[a]=null,this.parsedMap[a]=null}this.needs_update=!0}clone(){let t=new ai(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;t.map[r]=this.map[r],t.parsedMap[r]=this.parsedMap[r]}return t.needs_update=!0,t}copyFrom(t){this.width=t.width,this.height=t.height,this.block_width=t.block_width,this.block_height=t.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]=t.map[r],this.parsedMap[r]=t.parsedMap[r]}return this.update(),this}};function qe(e,t,s){let i=new Ft(1,1,1,1,t);i.ready=!1;let r=new XMLHttpRequest;return r.onreadystatechange=()=>{r.readyState===XMLHttpRequest.DONE&&(i.ready=!0,r.status===200&&oi(i,r.responseText,t),i.needs_update=!0,s?.())},r.open("GET",e),r.send(),i}l(qe,"LoadMap");ot(qe,"LoadMap");function oi(e,t,s){return e.load(t,s??e.sprites),e}l(oi,"UpdateMap");ot(oi,"UpdateMap");function jr(e){let t=1,s=[0],i={};for(let a=0;a<e.height;a++)for(let o=0;o<e.width;o++){let u=e.map[o+a*e.width];u&&u.length>0&&i[u]==null&&(s.push(u),i[u]=t++)}let r=[];for(let a=0;a<e.height;a++)for(let o=0;o<e.width;o++){let u=e.map[o+a*e.width];r[o+a*e.width]=u&&u.length>0?i[u]:0}let n={width:e.width,height:e.height,block_width:e.block_width,block_height:e.block_height,sprites:s,data:r};return JSON.stringify(n)}l(jr,"SaveMap");ot(jr,"SaveMap");var hi=Object.defineProperty,I=l((e,t)=>hi(e,"name",{value:t,configurable:!0}),"__name"),xt=l((e,t)=>{for(var s in t)hi(e,s,{get:t[s],enumerable:!0})},"__export"),li={normal:"source-over",additive:"lighter"},Gr=["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 e of Gr)li[e]=e;var Vr={};xt(Vr,{setColor:l(()=>$e,"setColor"),setLinearGradient:l(()=>Ke,"setLinearGradient"),setRadialGradient:l(()=>Je,"setRadialGradient")});function $e(e,t){t!=null&&typeof t=="string"&&(e.fillStyle=t,e.strokeStyle=t)}l($e,"setColor");I($e,"setColor");function Ke(e,t,s,i,r,n,a){let o=e.createLinearGradient(t,s,i,r);o.addColorStop(0,n),o.addColorStop(1,a),e.fillStyle=o,e.strokeStyle=o}l(Ke,"setLinearGradient");I(Ke,"setLinearGradient");function Je(e,t,s,i,r,n){let a=e.createRadialGradient(t,s,0,t,s,i);a.addColorStop(0,r),a.addColorStop(1,n),e.fillStyle=a,e.strokeStyle=a}l(Je,"setRadialGradient");I(Je,"setRadialGradient");function ci(e){return e?{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(ci,"createDefaultContextState");I(ci,"createDefaultContextState");function ue(e){e.image_transform=e.translation_x!==0||e.translation_y!==0||e.scale_x!==1||e.scale_y!==1||e.rotation!==0}l(ue,"updateImageTransform");I(ue,"updateImageTransform");var zr={};xt(zr,{closeDrawOp:l(()=>X,"closeDrawOp"),drawLine:l(()=>is,"drawLine"),drawRect:l(()=>ts,"drawRect"),drawRound:l(()=>ss,"drawRound"),drawRoundRect:l(()=>es,"drawRoundRect"),fillRect:l(()=>Qe,"fillRect"),fillRound:l(()=>Ze,"fillRound"),fillRoundRect:l(()=>Xe,"fillRoundRect"),initDrawOp:l(()=>Q,"initDrawOp")});function Q(e,t,s,i,r=!0){let n=!1;return t.image_transform&&(e.save(),n=!0,e.translate(t.translation_x,t.translation_y),e.scale(t.scale_x,t.scale_y),e.rotate(t.rotation/180*Math.PI),e.translate(s,i)),r&&(t.object_rotation!==0||t.object_scale_x!==1||t.object_scale_y!==1)&&(n||(e.save(),n=!0,e.translate(s,i)),t.object_rotation!==0&&e.rotate(t.object_rotation/180*Math.PI),(t.object_scale_x!==1||t.object_scale_y!==1)&&e.scale(t.object_scale_x,t.object_scale_y)),n}l(Q,"initDrawOp");I(Q,"initDrawOp");function X(e){e.restore()}l(X,"closeDrawOp");I(X,"closeDrawOp");function Qe(e,t,s,i,r,n){e.globalAlpha=t.alpha,Q(e,t,s,i)?(e.fillRect(-r/2-t.anchor_x*r/2,-n/2+t.anchor_y*n/2,r,n),X(e)):e.fillRect(s-r/2-t.anchor_x*r/2,i-n/2+t.anchor_y*n/2,r,n)}l(Qe,"fillRect");I(Qe,"fillRect");function Xe(e,t,s,i,r,n,a){e.globalAlpha=t.alpha,Q(e,t,s,i)?(e.fillRoundRect(-r/2-t.anchor_x*r/2,-n/2+t.anchor_y*n/2,r,n,a),X(e)):e.fillRoundRect(s-r/2-t.anchor_x*r/2,i-n/2+t.anchor_y*n/2,r,n,a)}l(Xe,"fillRoundRect");I(Xe,"fillRoundRect");function Ze(e,t,s,i,r,n){e.globalAlpha=t.alpha,r=Math.abs(r),n=Math.abs(n),Q(e,t,s,i)?(e.beginPath(),e.ellipse(-t.anchor_x*r/2,0+t.anchor_y*n/2,r/2,n/2,0,0,Math.PI*2,!1),e.fill(),X(e)):(e.beginPath(),e.ellipse(s-t.anchor_x*r/2,i+t.anchor_y*n/2,r/2,n/2,0,0,Math.PI*2,!1),e.fill())}l(Ze,"fillRound");I(Ze,"fillRound");function ts(e,t,s,i,r,n){e.globalAlpha=t.alpha,e.lineWidth=t.line_width,Q(e,t,s,i)?(e.strokeRect(-r/2-t.anchor_x*r/2,-n/2+t.anchor_y*n/2,r,n),X(e)):e.strokeRect(s-r/2-t.anchor_x*r/2,i-n/2+t.anchor_y*n/2,r,n)}l(ts,"drawRect");I(ts,"drawRect");function es(e,t,s,i,r,n,a){e.globalAlpha=t.alpha,e.lineWidth=t.line_width,Q(e,t,s,i)?(e.strokeRoundRect(-r/2-t.anchor_x*r/2,-n/2+t.anchor_y*n/2,r,n,a),X(e)):e.strokeRoundRect(s-r/2-t.anchor_x*r/2,i-n/2+t.anchor_y*n/2,r,n,a)}l(es,"drawRoundRect");I(es,"drawRoundRect");function ss(e,t,s,i,r,n){e.globalAlpha=t.alpha,e.lineWidth=t.line_width,r=Math.abs(r),n=Math.abs(n),Q(e,t,s,i)?(e.beginPath(),e.ellipse(0-t.anchor_x*r/2,0+t.anchor_y*n/2,r/2,n/2,0,0,Math.PI*2,!1),e.stroke(),X(e)):(e.beginPath(),e.ellipse(s-t.anchor_x*r/2,i+t.anchor_y*n/2,r/2,n/2,0,0,Math.PI*2,!1),e.stroke())}l(ss,"drawRound");I(ss,"drawRound");function is(e,t,s,i,r,n){e.globalAlpha=t.alpha,e.lineWidth=t.line_width;let a=Q(e,t,0,0,!1);e.beginPath(),e.moveTo(s,i),e.lineTo(r,n),e.stroke(),a&&X(e)}l(is,"drawLine");I(is,"drawLine");var Bt=new Set,Yt=new Map;function ui(e){if(e){if(Bt.has(e))return Promise.resolve();if(Yt.has(e))return Yt.get(e);if(typeof document<"u"&&"fonts"in document){let t=document.fonts.load(`12pt ${e}`).then(()=>{Bt.add(e),Yt.delete(e)}).catch(()=>{Bt.add(e),Yt.delete(e)});return Yt.set(e,t),t}return Bt.add(e),Promise.resolve()}}l(ui,"loadFont");I(ui,"loadFont");function fi(e){return!e||Bt.has(e)?!0:typeof document<"u"&&"fonts"in document?document.fonts.check(`12pt ${e}`):!0}l(fi,"isFontReady");I(fi,"isFontReady");function Wr(){Bt.clear(),Yt.clear()}l(Wr,"clearFontCache");I(Wr,"clearFontCache");var Hr={};xt(Hr,{drawMap:l(()=>rs,"drawMap")});var qr=I(e=>{let t=globalThis?.player?.runtime;if(!t)return null;let s=t.maps;if(s&&s[e])return s[e];let i=t.screen?.runtime?.maps;return i&&i[e]?i[e]:null},"resolveStringMap");function rs(e,t,s,i,r,n,a){let o=typeof s=="string"?qr(s):s??null;!o||!o.ready||!o.draw||(e.globalAlpha=t.alpha,e.imageSmoothingEnabled=!t.pixelated,Q(e,t,i,r)?(o.draw(e,-n/2-t.anchor_x*n/2,-a/2+t.anchor_y*a/2,n,a),X(e)):o.draw(e,i-n/2-t.anchor_x*n/2,r-a/2+t.anchor_y*a/2,n,a))}l(rs,"drawMap");I(rs,"drawMap");var J=null;function pi(e,t,s,i,r,n){J==null&&(J=e.createImageData(1,1)),typeof i=="object"?(J.data[0]=i.R,J.data[1]=i.G,J.data[2]=i.B):(J.data[0]=i,J.data[1]=r||0,J.data[2]=n||0),J.data[3]=255,e.putImageData(J,t,s)}l(pi,"setRGB");I(pi,"setRGB");function di(e,t,s,i,r,n,a){J==null&&(J=e.createImageData(1,1)),typeof i=="object"?(J.data[0]=i.R,J.data[1]=i.G,J.data[2]=i.B,J.data[3]=i.A!=null?i.A:255):(J.data[0]=i,J.data[1]=r||0,J.data[2]=n||0,J.data[3]=a??255),e.putImageData(J,t,s)}l(di,"setRGBA");I(di,"setRGBA");function mi(e,t,s,i={R:0,G:0,B:0}){let r=e.getImageData(t,s,1,1);return i.R=r.data[0],i.G=r.data[1],i.B=r.data[2],i}l(mi,"getRGB");I(mi,"getRGB");function _i(e,t,s,i={R:0,G:0,B:0,A:255}){let r=e.getImageData(t,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(_i,"getRGBA");I(_i,"getRGBA");var $r={};xt($r,{drawArc:l(()=>cs,"drawArc"),drawBezierCurve:l(()=>ls,"drawBezierCurve"),drawPolygon:l(()=>as,"drawPolygon"),drawPolyline:l(()=>ns,"drawPolyline"),drawQuadCurve:l(()=>hs,"drawQuadCurve"),fillArc:l(()=>us,"fillArc"),fillPolygon:l(()=>os,"fillPolygon")});function ns(e,t,s){if(Array.isArray(s[0])&&(s=s[0]),e.globalAlpha=t.alpha,e.lineWidth=t.line_width,s.length<4)return;let i=Math.floor(s.length/2),r=Q(e,t,0,0,!1);e.beginPath(),e.moveTo(s[0],s[1]);for(let n=1;n<=i-1;n++)e.lineTo(s[n*2],s[n*2+1]);e.stroke(),r&&X(e)}l(ns,"drawPolyline");I(ns,"drawPolyline");function as(e,t,s){if(Array.isArray(s[0])&&(s=s[0]),e.globalAlpha=t.alpha,e.lineWidth=t.line_width,s.length<4)return;let i=Math.floor(s.length/2),r=Q(e,t,0,0,!1);e.beginPath(),e.moveTo(s[0],s[1]);for(let n=1;n<=i-1;n++)e.lineTo(s[n*2],s[n*2+1]);e.closePath(),e.stroke(),r&&X(e)}l(as,"drawPolygon");I(as,"drawPolygon");function os(e,t,s){if(Array.isArray(s[0])&&(s=s[0]),e.globalAlpha=t.alpha,s.length<4)return;let i=Math.floor(s.length/2),r=Q(e,t,0,0,!1);e.beginPath(),e.moveTo(s[0],s[1]);for(let n=1;n<=i-1;n++)e.lineTo(s[n*2],s[n*2+1]);e.fill(),r&&X(e)}l(os,"fillPolygon");I(os,"fillPolygon");function hs(e,t,s){if(Array.isArray(s[0])&&(s=s[0]),e.globalAlpha=t.alpha,e.lineWidth=t.line_width,s.length<4)return;let i=Q(e,t,0,0,!1);e.beginPath(),e.moveTo(s[0],s[1]);let r=2;for(;r<=s.length-4;)e.quadraticCurveTo(s[r],s[r+1],s[r+2],s[r+3]),r+=4;e.stroke(),i&&X(e)}l(hs,"drawQuadCurve");I(hs,"drawQuadCurve");function ls(e,t,s){if(Array.isArray(s[0])&&(s=s[0]),e.globalAlpha=t.alpha,e.lineWidth=t.line_width,s.length<4)return;let i=Q(e,t,0,0,!1);e.beginPath(),e.moveTo(s[0],s[1]);let r=2;for(;r<=s.length-6;)e.bezierCurveTo(s[r],s[r+1],s[r+2],s[r+3],s[r+4],s[r+5]),r+=6;e.stroke(),i&&X(e)}l(ls,"drawBezierCurve");I(ls,"drawBezierCurve");function cs(e,t,s,i,r,n,a,o){e.globalAlpha=t.alpha,e.lineWidth=t.line_width,Q(e,t,s,i)?(e.beginPath(),e.arc(0,0,r,n/180*Math.PI,a/180*Math.PI,o),e.stroke(),X(e)):(e.beginPath(),e.arc(s,i,r,n/180*Math.PI,a/180*Math.PI,o),e.stroke())}l(cs,"drawArc");I(cs,"drawArc");function us(e,t,s,i,r,n,a,o){e.globalAlpha=t.alpha,Q(e,t,s,i)?(e.beginPath(),e.arc(0,0,r,n/180*Math.PI,a/180*Math.PI,o),e.fill(),X(e)):(e.beginPath(),e.arc(s,i,r,n/180*Math.PI,a/180*Math.PI,o),e.fill())}l(us,"fillArc");I(us,"fillArc");var Kr={};xt(Kr,{drawSprite:l(()=>fs,"drawSprite"),drawSpritePart:l(()=>ps,"drawSpritePart"),getSpriteFrame:l(()=>fe,"getSpriteFrame")});function fe(e){if(typeof e=="object"&&"canvas"in e&&!("frames"in e))return e.canvas||e.image||null;if(typeof e=="object"&&e.frames&&e.frames.length>0){if(!e.ready)return null;if(e.frames.length>1){(!e.animation_start||e.animation_start===0)&&(e.animation_start=Date.now());let t=1e3/(e.fps||5),s=Math.floor((Date.now()-e.animation_start)/t)%e.frames.length;return s>=0&&s<e.frames.length?e.frames[s].canvas:e.frames[0].canvas}return e.frames[0].canvas}return null}l(fe,"getSpriteFrame");I(fe,"getSpriteFrame");function fs(e,t,s,i,r,n,a){let o=fe(s);o!=null&&(n==null&&(n=o.width),a||(a=n/o.width*o.height),e.globalAlpha=t.alpha,e.imageSmoothingEnabled=!t.pixelated,Q(e,t,i,r)?(e.drawImage(o,-n/2-t.anchor_x*n/2,-a/2+t.anchor_y*a/2,n,a),X(e)):e.drawImage(o,i-n/2-t.anchor_x*n/2,r-a/2+t.anchor_y*a/2,n,a))}l(fs,"drawSprite");I(fs,"drawSprite");function ps(e,t,s,i,r,n,a,o,u,_,E){let A=fe(s);A!=null&&(_==null&&(_=A.width),E||(E=_/n*a),e.globalAlpha=t.alpha,e.imageSmoothingEnabled=!t.pixelated,Q(e,t,o,u)?(e.drawImage(A,i,r,n,a,-_/2-t.anchor_x*_/2,-E/2+t.anchor_y*E/2,_,E),X(e)):e.drawImage(A,i,r,n,a,o-_/2-t.anchor_x*_/2,u-E/2+t.anchor_y*E/2,_,E))}l(ps,"drawSpritePart");I(ps,"drawSpritePart");var Jr={};xt(Jr,{drawText:l(()=>ms,"drawText"),drawTextOutline:l(()=>_s,"drawTextOutline"),textWidth:l(()=>ds,"textWidth")});function ds(e,t,s,i){return e.font=`${i}pt ${t.font}`,e.measureText(s).width}l(ds,"textWidth");I(ds,"textWidth");function ms(e,t,s,i,r,n){e.globalAlpha=t.alpha,e.font=`${n}pt ${t.font}`,e.textAlign="center",e.textBaseline="middle";let a=e.measureText(s).width,o=n;Q(e,t,i,r)?(e.fillText(s,0-t.anchor_x*a/2,0+t.anchor_y*o/2),X(e)):e.fillText(s,i-t.anchor_x*a/2,r+t.anchor_y*o/2)}l(ms,"drawText");I(ms,"drawText");function _s(e,t,s,i,r,n){e.globalAlpha=t.alpha,e.font=`${n}pt ${t.font}`,e.lineWidth=t.line_width,e.textAlign="center",e.textBaseline="middle";let a=e.measureText(s).width,o=n;Q(e,t,i,r)?(e.strokeText(s,0-t.anchor_x*a/2,0+t.anchor_y*o/2),X(e)):e.strokeText(s,i-t.anchor_x*a/2,r+t.anchor_y*o/2)}l(_s,"drawTextOutline");I(_s,"drawTextOutline");var Qr={};xt(Qr,{setDrawAnchor:l(()=>Ts,"setDrawAnchor"),setDrawRotation:l(()=>ys,"setDrawRotation"),setDrawScale:l(()=>Os,"setDrawScale"),setRotation:l(()=>bs,"setRotation"),setScale:l(()=>Es,"setScale"),setTranslation:l(()=>gs,"setTranslation")});function gs(e,t,s){e.translation_x=t,e.translation_y=s,isFinite(e.translation_x)||(e.translation_x=0),isFinite(e.translation_y)||(e.translation_y=0),ue(e)}l(gs,"setTranslation");I(gs,"setTranslation");function Es(e,t,s){e.scale_x=t,e.scale_y=s,(!isFinite(e.scale_x)||e.scale_x===0)&&(e.scale_x=1),(!isFinite(e.scale_y)||e.scale_y===0)&&(e.scale_y=1),ue(e)}l(Es,"setScale");I(Es,"setScale");function bs(e,t){e.rotation=t,isFinite(e.rotation)||(e.rotation=0),ue(e)}l(bs,"setRotation");I(bs,"setRotation");function Ts(e,t,s){e.anchor_x=t,e.anchor_y=s,typeof e.anchor_x!="number"&&(e.anchor_x=0),typeof e.anchor_y!="number"&&(e.anchor_y=0)}l(Ts,"setDrawAnchor");I(Ts,"setDrawAnchor");function ys(e,t){e.object_rotation=t}l(ys,"setDrawRotation");I(ys,"setDrawRotation");function Os(e,t,s){e.object_scale_x=t,e.object_scale_y=s}l(Os,"setDrawScale");I(Os,"setDrawScale");function Ut(e){return e.length>0&&e.length%2===1&&typeof e[e.length-1]=="string"?{points:e.slice(0,-1),color:e[e.length-1]}:{points:e,color:void 0}}l(Ut,"splitColorArg");I(Ut,"splitColorArg");var mt=class{static{l(this,"Image")}static{I(this,"Image")}_canvas;_context=null;_image=null;_state;_centered;width;height;constructor(e,t,s=!1){this._centered=s,typeof e=="object"&&"naturalWidth"in e?(this._image=e,this.width=this._image.width,this.height=this._image.height):typeof e=="object"&&"getContext"in e?(this._canvas=e,this.width=this._canvas.width,this.height=this._canvas.height):(this._canvas=document.createElement("canvas"),this.width=Math.round(e),this.height=Math.round(t||e),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=ci(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(e,t,s,i,r){this.initContext(),pi(this._context,e,t,s,i,r)}setRGBA(e,t,s,i,r,n){this.initContext(),di(this._context,e,t,s,i,r,n)}getRGB(e,t,s){return this.initContext(),mi(this._context,e,t,s)}getRGBA(e,t,s){return this.initContext(),_i(this._context,e,t,s)}clear(e){this.initContext();let t=this._context.fillStyle,s=this._context.strokeStyle,i=this._context.globalCompositeOperation;this._context.globalAlpha=1,this._context.globalCompositeOperation="source-over",e!=null?this.setColor(e):this._context.fillStyle="#000",this._context.fillRect(0,0,this.width,this.height),this._context.fillStyle=t,this._context.strokeStyle=s,this._context.globalCompositeOperation=i}setColor(e){this.initContext(),$e(this._context,e)}setAlpha(e){this.initContext(),this._state.alpha=e}setPixelated(e){this.initContext(),this._state.pixelated=e}setBlending(e){this.initContext();let t=li[e||"normal"]||"source-over";this._context.globalCompositeOperation=t}setLineWidth(e){this.initContext(),this._state.line_width=e}setLineDash(e){this.initContext(),Array.isArray(e)?this._context.setLineDash(e):this._context.setLineDash([])}setLinearGradient(e,t,s,i,r,n){this.initContext(),Ke(this._context,e,t,s,i,r,n)}setRadialGradient(e,t,s,i,r){this.initContext(),Je(this._context,e,t,s,i,r)}setFont(e){this.initContext(),this._state.font=e||"Verdana",this.loadFont(this._state.font)}loadFont(e){return ui(e)}isFontReady(e){return fi(e||this._state?.font||"Verdana")}setTranslation(e,t){this.initContext(),gs(this._state,e,t)}setScale(e,t){this.initContext(),Es(this._state,e,t)}setRotation(e){this.initContext(),bs(this._state,e)}setDrawAnchor(e,t){this.initContext(),Ts(this._state,e,t)}setDrawRotation(e){this.initContext(),ys(this._state,e)}setDrawScale(e,t=e){this.initContext(),Os(this._state,e,t)}fillRect(e,t,s,i,r){this.initContext(),this.setColor(r),Qe(this._context,this._state,e,t,s,i)}fillRoundRect(e,t,s,i,r=10,n){this.initContext(),this.setColor(n),Xe(this._context,this._state,e,t,s,i,r)}fillRound(e,t,s,i,r){this.initContext(),this.setColor(r),Ze(this._context,this._state,e,t,s,i)}drawRect(e,t,s,i,r){this.initContext(),this.setColor(r),ts(this._context,this._state,e,t,s,i)}drawRoundRect(e,t,s,i,r=10,n){this.initContext(),this.setColor(n),es(this._context,this._state,e,t,s,i,r)}drawRound(e,t,s,i,r){this.initContext(),this.setColor(r),ss(this._context,this._state,e,t,s,i)}drawLine(e,t,s,i,r){this.initContext(),this.setColor(r),is(this._context,this._state,e,t,s,i)}drawPolyline(...e){this.initContext();let{points:t,color:s}=Ut(e);this.setColor(s),ns(this._context,this._state,t)}drawPolygon(...e){this.initContext();let{points:t,color:s}=Ut(e);this.setColor(s),as(this._context,this._state,t)}fillPolygon(...e){this.initContext();let{points:t,color:s}=Ut(e);this.setColor(s),os(this._context,this._state,t)}drawQuadCurve(...e){this.initContext();let{points:t,color:s}=Ut(e);this.setColor(s),hs(this._context,this._state,t)}drawBezierCurve(...e){this.initContext();let{points:t,color:s}=Ut(e);this.setColor(s),ls(this._context,this._state,t)}drawArc(e,t,s,i,r,n,a){this.initContext(),this.setColor(a),cs(this._context,this._state,e,t,s,i,r,n)}fillArc(e,t,s,i,r,n,a){this.initContext(),this.setColor(a),us(this._context,this._state,e,t,s,i,r,n)}textWidth(e,t){return this.initContext(),ds(this._context,this._state,e,t)}drawText(e,t,s,i,r){this.initContext(),this.setColor(r),ms(this._context,this._state,e,t,s,i)}drawTextOutline(e,t,s,i,r){this.initContext(),this.setColor(r),_s(this._context,this._state,e,t,s,i)}drawSprite(e,t,s,i,r){this.initContext(),fs(this._context,this._state,e,t,s,i,r)}drawImage(e,t,s,i,r){this.drawSprite(e,t,s,i,r)}drawSpritePart(e,t,s,i,r,n,a,o,u){this.initContext(),ps(this._context,this._state,e,t,s,i,r,n,a,o,u)}drawImagePart(e,t,s,i,r,n,a,o,u){this.drawSpritePart(e,t,s,i,r,n,a,o,u)}drawMap(e,t,s,i,r){this.initContext(),rs(this._context,this._state,e,t,s,i,r)}};var Xr=Object.defineProperty,pe=l((e,t)=>Xr(e,"name",{value:t,configurable:!0}),"__name"),jt=class{static{l(this,"Sprite")}static{pe(this,"Sprite")}name="";frames=[];animation_start=0;fps=5;ready=0;width;height;constructor(e,t){this.width=e,this.height=t,this.frames=[],this.animation_start=0,this.fps=5,this.width>0&&this.height>0&&(this.frames.push(new mt(this.width,this.height)),this.ready=1)}setFPS(e){let t=1e3/this.fps,s=(Date.now()-this.animation_start)/t%this.frames.length;this.fps=e;let i=1e3/e;return this.animation_start=Date.now()-s*i,e}setFrame(e){this.animation_start=Date.now()-1e3/this.fps*e}getFrame(){let e=1e3/this.fps;return Math.floor((Date.now()-this.animation_start)/e)%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 e=this.getFrame();return e>=0&&e<this.frames.length?this.frames[e].canvas:this.frames[0].canvas}return this.frames[0].canvas}};function As(e,t,s){if(e>0&&t%e===0){let i=t/e;return Math.min(s,i)}return s}l(As,"resolveFrameCount");pe(As,"resolveFrameCount");function Ps(e,t,s){let i=new jt(0,0);i.ready=0;let r=new window.Image;return location.protocol!=="file:"&&(r.crossOrigin="Anonymous"),r.src=e,r.onload=()=>{if(i.ready=1,r.width>0&&r.height>0){t?.fps&&(i.fps=t.fps),i.width=r.width;let n=As(r.width,r.height,t?.frames??1);i.height=Math.round(r.height/n),i.frames=[];for(let a=0;a<n;a++){let o=new mt(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(Ps,"LoadSprite");pe(Ps,"LoadSprite");function Zr(e,t,s){if(t.width>0&&t.height>0){s?.fps&&(e.fps=s.fps),e.width=t.width;let i=As(t.width,t.height,s?.frames??1);e.height=Math.round(t.height/i),e.frames=[];for(let r=0;r<i;r++){let n=new mt(e.width,e.height);n.initContext();let a=n.context;a.setTransform(1,0,0,1,0,0),a.drawImage(t,0,-r*e.height),e.frames.push(n)}e.ready=1}}l(Zr,"UpdateSprite");pe(Zr,"UpdateSprite");var gi=16.666666666666668,Ei=160,Ls=16,de=16,bi=3e4;function tn(e,t){return Promise.race([e,new Promise((s,i)=>setTimeout(()=>i(new Error(`Asset load timed out after ${t}ms`)),t))])}l(tn,"withTimeout");var Gt=class{static{l(this,"AssetLoader")}url;resources;collections;loadingBarTime=null;audioCore;listener;constructor(t,s,i,r){this.url=t,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(t,s,i,r,n){if(!t)return;let a=t.map(o=>new Promise(u=>{let _=o.file.split(".")[0].replace(/-/g,"/"),E=`${this.url}${s}/${o.file}?v=${o.version||0}`;try{let A=new Promise(b=>{this.collections[i][_]=r(E,o,b)});tn(A,bi).then(u).catch(b=>{this.listener?.log?.(`[AssetLoader] Failed to load ${i.slice(0,-1)} "${_}": ${String(b)}`),this.collections[i][_]=n(_,o),u()})}catch(A){this.listener?.log?.(`[AssetLoader] Failed to load ${i.slice(0,-1)} "${_}": ${String(A)}`),this.collections[i][_]=n(_,o),u()}}));await Promise.all(a)}async loadSprites(){await this.loadCallbackAssets(this.resources.images,"sprites","sprites",(t,s,i)=>Ps(t,s.properties,i),(t,s)=>({name:t,ready:!1,frames:[],fps:s.properties?.fps||5,width:0,height:0}))}async loadMaps(){await this.loadCallbackAssets(this.resources.maps,"maps","maps",(t,s,i)=>qe(t,this.collections.sprites,i),t=>({name:t,ready:!1,width:0,height:0,block_width:Ls,block_height:Ls,data:[]}))}async loadSounds(){if(!this.resources.sounds)return;let t=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 Ot(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 Ot(this.audioCore,n),i()}}));await Promise.all(t)}async loadMusic(){if(!this.resources.music)return;let t=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 We(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 We(this.audioCore,n),i()}}));await Promise.all(t)}async loadGenericAssets(){if(this.resources.assets)for(let t of this.resources.assets){let s=t.file.split(".")[0].replace(/-/g,"/");this.collections.assets[s]={name:s,file:t.file,version:t.version}}}isReady(){return this.countReady()===this.countTotal()}getProgress(){let t=this.countTotal();return t===0?1:this.countReady()/t}countTotal(){let t=0;return t+=Object.keys(this.collections.sprites).length,t+=Object.keys(this.collections.maps).length,t+=Object.keys(this.collections.sounds).length,t+=Object.keys(this.collections.music).length,t}countReady(){let t=0;for(let s of Object.values(this.collections.sprites))s.ready&&t++;for(let s of Object.values(this.collections.maps))s.ready&&t++;for(let s of Object.values(this.collections.sounds))s.ready&&t++;for(let s of Object.values(this.collections.music))s.ready&&t++;return t}showLoadingBar(t){if(this.loadingBarTime&&Date.now()<this.loadingBarTime+de)return;this.loadingBarTime=Date.now();let s=this.getProgress();t.clear("#000"),t.drawRect(0,0,100,10,"#DDD"),t.fillRect(-(1-s)*48,0,s*96,6,"#DDD")}getCollections(){return this.collections}};var en=Object.defineProperty,At=l((e,t)=>en(e,"name",{value:t,configurable:!0}),"__name"),Ti=class{static{l(this,"PlayerService")}static{At(this,"PlayerService")}delegate;interfaceCache=null;constructor(e){this.delegate=e}getInterface(){if(this.interfaceCache)return this.interfaceCache;let e={pause:At(()=>this.delegate.pause(),"pause"),resume:At(()=>this.delegate.resume(),"resume"),postMessage:At(t=>this.delegate.postMessage(t),"postMessage"),setFps:At(t=>{typeof t=="number"&&isFinite(t)&&t>0&&this.delegate.setUpdateRate(t)},"setFps")};return Object.defineProperty(e,"fps",{get:At(()=>this.delegate.getFps(),"get"),enumerable:!0}),Object.defineProperty(e,"update_rate",{get:At(()=>this.delegate.getUpdateRate(),"get"),set:At(t=>{typeof t=="number"&&isFinite(t)&&t>0&&this.delegate.setUpdateRate(t)},"set"),enumerable:!0}),this.interfaceCache=e,this.interfaceCache}};var sn=Object.defineProperty,k=l((e,t)=>sn(e,"name",{value:t,configurable:!0}),"__name"),rn=class{static{l(this,"ZBuffer")}static{k(this,"ZBuffer")}buffer;width;height;constructor(e,t){this.width=e,this.height=t,this.buffer=new Float32Array(e*t)}clear(){this.buffer.fill(0)}get(e,t){return this.buffer[t*this.width+e]||0}set(e,t,s){this.buffer[t*this.width+e]=s}resize(e,t){(this.width!==e||this.height!==t)&&(this.width=e,this.height=t,this.buffer=new Float32Array(e*t))}};function Jt(e,t,s){return(t.x-e.x)*(s.y-e.y)-(t.y-e.y)*(s.x-e.x)}l(Jt,"edgeFn");k(Jt,"edgeFn");function yi(e,t,s,i){let r=null;if(e&&typeof e=="object"&&e.canvas)r=e.canvas;else if(typeof e=="string"&&i?.sprites){let b=i.sprites[e];b?.frames?.[0]?.canvas&&(r=b.frames[0].canvas)}if(!r)return null;let n=r.width,a=r.height,o=Math.floor(t)%n,u=Math.floor(s)%a,_=o<0?o+n:o,E=u<0?u+a:u,A=r.getContext("2d");if(!A)return null;try{let b=A.getImageData(_,E,1,1);return{r:b.data[0],g:b.data[1],b:b.data[2],a:b.data[3]}}catch{return null}}l(yi,"getSpritePixel");k(yi,"getSpritePixel");function Oi(e,t,s,i){let r=null;if(e&&typeof e=="object"&&e.getCanvas?r=e:typeof e=="string"&&i?.maps&&(r=i.maps[e]),!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(t)%a,_=Math.floor(s)%o,E=u<0?u+a:u,A=_<0?_+o:_,b=n.getContext("2d");if(!b)return null;try{let O=b.getImageData(E,A,1,1);return{r:O.data[0],g:O.data[1],b:O.data[2],a:O.data[3]}}catch{return null}}l(Oi,"getMapPixel");k(Oi,"getMapPixel");function Ai(e,t,s,i,r,n="tiles",a,o=!1){let{context:u,width:_,height:E,runtime:A,pixelated:b}=e,O=Math.max(0,Math.floor(Math.min(t.x,s.x,i.x))),m=Math.max(0,Math.floor(Math.min(t.y,s.y,i.y))),M=Math.min(_,Math.ceil(Math.max(t.x,s.x,i.x))),z=Math.min(E,Math.ceil(Math.max(t.y,s.y,i.y)));if(O>=M||m>=z)return;let w=Jt(t,s,i);if(Math.abs(w)<.001||w<0)return;let S=o&&t.z>0&&s.z>0&&i.z>0,H=1,G=1,F=1,lt=t.u,bt=s.u,et=i.u,q=t.v,Rt=s.v,wt=i.v;S&&(H=1/t.z,G=1/s.z,F=1/i.z,lt*=H,bt*=G,et*=F,q*=H,Rt*=G,wt*=F);let Ct=u.getImageData(O,m,M-O,z-m),ft=Ct.data;for(let pt=m;pt<z;pt++)for(let $=O;$<M;$++){let Pt={x:$+.5,y:pt+.5},Y=Jt(s,i,Pt),D=Jt(i,t,Pt),nt=Jt(t,s,Pt);if(Y>=0&&D>=0&&nt>=0){let rt=Y/w,st=D/w,ct=nt/w;if(S&&a){let C=rt*t.z+st*s.z+ct*i.z,at=a.get($,pt);if(at>0&&at>=C)continue;a.set($,pt,C)}let R,dt;if(S){let C=rt*H+st*G+ct*F;R=(rt*lt+st*bt+ct*et)/C,dt=(rt*q+st*Rt+ct*wt)/C}else R=rt*t.u+st*s.u+ct*i.u,dt=rt*t.v+st*s.v+ct*i.v;let L=null;if(n==="map"?L=Oi(r,R,dt,A):L=yi(r,R,dt,A),L&&L.a>0){let C=((pt-m)*(M-O)+($-O))*4;ft[C]=L.r,ft[C+1]=L.g,ft[C+2]=L.b,ft[C+3]=L.a}}}u.imageSmoothingEnabled=!b,u.putImageData(Ct,O,m)}l(Ai,"drawTexturedTriangle");k(Ai,"drawTexturedTriangle");function Pi(e,t,s,i,r){e.fillStyle=r,e.beginPath(),e.moveTo(t.x,t.y),e.lineTo(s.x,s.y),e.lineTo(i.x,i.y),e.closePath(),e.fill()}l(Pi,"drawTriangle");k(Pi,"drawTriangle");function Li(e,t,s,i,r,n=1){e.strokeStyle=r,e.lineWidth=n,e.beginPath(),e.moveTo(t.x,t.y),e.lineTo(s.x,s.y),e.lineTo(i.x,i.y),e.closePath(),e.stroke()}l(Li,"drawTriangleOutline");k(Li,"drawTriangleOutline");var nn=class{static{l(this,"BaseScreen")}static{k(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(e={}){this.runtime=e.runtime,e.canvas?(this.canvas=e.canvas,(this.canvas.width===0||this.canvas.height===0)&&(this.canvas.width=e.width||1080,this.canvas.height=e.height||1920)):(this.canvas=document.createElement("canvas"),this.canvas.width=e.width||1080,this.canvas.height=e.height||1920),this.initContext(),this.blending={normal:"source-over",additive:"lighter"};let t=["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 t)this.blending[s]=s;this.loadFont(this.font),this.zBuffer=new rn(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 e=this.canvas.getContext("2d",{alpha:!1});if(!e){let s="Failed to get 2D rendering context";throw this.runtime?.listener?.reportError?.({code:"E7001",message:s,data:{}}),new Error(s)}e!==this.context?this.context=e:this.context.restore(),this.context.save(),this.context.translate(this.canvas.width/2,this.canvas.height/2);let t=Math.min(this.canvas.width/200,this.canvas.height/200);this.context.scale(t,t),this.width=this.canvas.width/t,this.height=this.canvas.height/t,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(e){this.context.globalAlpha=1,this.context.globalCompositeOperation="source-over",this.context.fillStyle=e||"#000",this.context.strokeStyle=e||"#000",this.context.fillRect(-this.width/2,-this.height/2,this.width,this.height),this.zBuffer.clear()}setColor(e){if(e)if(Number.isNaN(Number.parseInt(String(e)))){if(typeof e=="string"){if(!(/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(e)||/^rgb\(|^rgba\(|^hsl\(|^hsla\(/.test(e)||/^(red|green|blue|yellow|cyan|magenta|black|white|gray|grey|orange|pink|purple|brown|transparent)$/i.test(e))){this.runtime?.listener?.reportError?.({code:"E7003",message:"Invalid color",data:{color:e}});return}this.context.fillStyle=e,this.context.strokeStyle=e}}else{let t=Number.parseInt(String(e)),s=Math.floor(t/100)%10/9*255,i=Math.floor(t/10)%10/9*255,r=t%10/9*255,a="#"+(4278190080+(s<<16)+(i<<8)+r).toString(16).substring(2,8);this.context.fillStyle=a,this.context.strokeStyle=a}}setAlpha(e){this.alpha=e}setPixelated(e){this.pixelated=e}setBlending(e){let t=this.blending[e||"normal"];if(!t){this.runtime?.listener?.reportError?.({code:"E7007",message:"Invalid blend mode",data:{blendMode:e}}),this.context.globalCompositeOperation="source-over";return}this.context.globalCompositeOperation=t}setLineWidth(e){this.line_width=e}setLineDash(e){Array.isArray(e)?this.context.setLineDash(e):this.context.setLineDash([])}setLinearGradient(e,t,s,i,r,n){let a=this.context.createLinearGradient(e,-t,s,-i);a.addColorStop(0,r),a.addColorStop(1,n),this.context.fillStyle=a,this.context.strokeStyle=a}setRadialGradient(e,t,s,i,r){let n=this.context.createRadialGradient(e,-t,0,e,-t,s);n.addColorStop(0,i),n.addColorStop(1,r),this.context.fillStyle=n,this.context.strokeStyle=n}setFont(e){this.font=e||"Verdana",this.loadFont(this.font)}loadFont(e="BitCell"){if(!this.font_load_requested[e]){this.font_load_requested[e]=!0;try{document.fonts?.load?.(`16pt ${e}`).catch(()=>{this.runtime?.listener?.reportError?.({code:"E7006",message:"Font loading failed",data:{font:e}})})}catch{this.runtime?.listener?.reportError?.({code:"E7006",message:"Font loading failed",data:{font:e}})}}}isFontReady(e=this.font){if(this.font_loaded[e])return 1;try{let t=document.fonts?.check?.(`16pt ${e}`)??!0;return t&&(this.font_loaded[e]=!0),t?1:0}catch{return 1}}setTranslation(e,t){this.translation_x=isFinite(e)?e:0,this.translation_y=isFinite(t)?t:0,this.updateScreenTransform()}setScale(e,t){this.scale_x=isFinite(e)&&e!==0?e:1,this.scale_y=isFinite(t)&&t!==0?t:1,this.updateScreenTransform()}setRotation(e){this.rotation=isFinite(e)?e: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(e,t){this.anchor_x=typeof e=="number"?e:0,this.anchor_y=typeof t=="number"?t:0}setDrawRotation(e){this.object_rotation=e}setDrawScale(e,t=e){this.object_scale_x=e,this.object_scale_y=t}initDrawOp(e,t,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(e,t)),s&&(this.object_rotation!==0||this.object_scale_x!==1||this.object_scale_y!==1)&&(i||(this.context.save(),i=!0,this.context.translate(e,t)),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(e){this.cursor_visibility=e?"default":"none",e?(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(e,t){if(e&&t){if(e<=0||t<=0||!isFinite(e)||!isFinite(t)){this.runtime?.listener?.reportError?.({code:"E7002",message:"Invalid resize dimensions",data:{width:e,height:t}});return}this.canvas.width=e,this.canvas.height=t,this.initContext(),this.zBuffer.resize(e,t),this.updateInterface()}}},an=class extends nn{static{l(this,"PrimitiveScreen")}static{k(this,"PrimitiveScreen")}fillRect(e,t,s,i,r){if(!this.context){this.runtime?.listener?.reportError?.({code:"E7092",message:"Drawing context not available",data:{}});return}if(!isFinite(e)||!isFinite(t)||!isFinite(s)||!isFinite(i)||s<=0||i<=0){this.runtime?.listener?.reportError?.({code:"E7093",message:"Invalid draw parameters",data:{error:`Invalid parameters: x=${e}, y=${t}, w=${s}, h=${i}`}});return}r&&this.setColor(r),this.context.globalAlpha=this.alpha,this.initDrawOp(e,-t)?(this.context.fillRect(-s/2-this.anchor_x*s/2,-i/2+this.anchor_y*i/2,s,i),this.closeDrawOp()):this.context.fillRect(e-s/2-this.anchor_x*s/2,-t-i/2+this.anchor_y*i/2,s,i)}fillRoundRect(e,t,s,i,r=10,n){n&&this.setColor(n),this.context.globalAlpha=this.alpha;let a=this.initDrawOp(e,-t),o=(a?-s/2:e-s/2)-this.anchor_x*s/2,u=(a?-i/2:-t-i/2)+this.anchor_y*i/2;if(this.context.beginPath(),this.context.roundRect)this.context.roundRect(o,u,s,i,r);else{let _=Math.min(r,s/2,i/2);this.context.moveTo(o+_,u),this.context.lineTo(o+s-_,u),this.context.quadraticCurveTo(o+s,u,o+s,u+_),this.context.lineTo(o+s,u+i-_),this.context.quadraticCurveTo(o+s,u+i,o+s-_,u+i),this.context.lineTo(o+_,u+i),this.context.quadraticCurveTo(o,u+i,o,u+i-_),this.context.lineTo(o,u+_),this.context.quadraticCurveTo(o,u,o+_,u),this.context.closePath()}this.context.fill(),a&&this.closeDrawOp()}fillRound(e,t,s,i,r){r&&this.setColor(r),this.context.globalAlpha=this.alpha,s=Math.abs(s),i=Math.abs(i),this.initDrawOp(e,-t)?(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(e-this.anchor_x*s/2,-t+this.anchor_y*i/2,s/2,i/2,0,0,Math.PI*2,!1),this.context.fill())}drawRect(e,t,s,i,r){r&&this.setColor(r),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width,this.initDrawOp(e,-t)?(this.context.strokeRect(-s/2-this.anchor_x*s/2,-i/2+this.anchor_y*i/2,s,i),this.closeDrawOp()):this.context.strokeRect(e-s/2-this.anchor_x*s/2,-t-i/2+this.anchor_y*i/2,s,i)}drawRoundRect(e,t,s,i,r=10,n){n&&this.setColor(n),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width;let a=this.initDrawOp(e,-t),o=(a?-s/2:e-s/2)-this.anchor_x*s/2,u=(a?-i/2:-t-i/2)+this.anchor_y*i/2;if(this.context.beginPath(),this.context.roundRect)this.context.roundRect(o,u,s,i,r);else{let _=Math.min(r,s/2,i/2);this.context.moveTo(o+_,u),this.context.lineTo(o+s-_,u),this.context.quadraticCurveTo(o+s,u,o+s,u+_),this.context.lineTo(o+s,u+i-_),this.context.quadraticCurveTo(o+s,u+i,o+s-_,u+i),this.context.lineTo(o+_,u+i),this.context.quadraticCurveTo(o,u+i,o,u+i-_),this.context.lineTo(o,u+_),this.context.quadraticCurveTo(o,u,o+_,u),this.context.closePath()}this.context.stroke(),a&&this.closeDrawOp()}drawRound(e,t,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(e,-t)?(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(e-this.anchor_x*s/2,-t+this.anchor_y*i/2,s/2,i/2,0,0,Math.PI*2,!1),this.context.stroke())}drawLine(e,t,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(e,-t),this.context.lineTo(s,-i),this.context.stroke(),n&&this.closeDrawOp()}drawPolygon(e){let{color:t,points:s}=this.extractPoints(e);if(!s||s.length<4)return;t&&this.setColor(t),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(e){let{color:t,points:s}=this.extractPoints(e);if(!s||s.length<4)return;t&&this.setColor(t),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(e){let{color:t,points:s}=this.extractPoints(e);if(!s||s.length<4)return;t&&this.setColor(t),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(e){let{color:t,points:s}=this.extractPoints(e);if(!s||s.length<4)return;t&&this.setColor(t),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(e){let{color:t,points:s}=this.extractPoints(e);if(!s||s.length<4)return;t&&this.setColor(t),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(e,t,s,i,r,n,a){a&&this.setColor(a),this.context.globalAlpha=this.alpha,this.context.lineWidth=this.line_width,this.initDrawOp(e,-t)?(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(e,-t,s,-i/180*Math.PI,-r/180*Math.PI,n),this.context.stroke())}fillArc(e,t,s,i,r,n,a){a&&this.setColor(a),this.context.globalAlpha=this.alpha,this.initDrawOp(e,-t)?(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(e,-t,s,-i/180*Math.PI,-r/180*Math.PI,n),this.context.fill())}extractPoints(e){let t,s;return e.length>0&&e.length%2===1&&typeof e[e.length-1]=="string"?(t=e[e.length-1],s=e.slice(0,-1)):Array.isArray(e[0])?(e[1]&&typeof e[1]=="string"&&(t=e[1]),s=e[0]):s=e,{color:t,points:s}}},on=class extends an{static{l(this,"SpriteScreen")}static{k(this,"SpriteScreen")}_lastImageSmoothing=!0;_frameTime=0;initDraw(){super.initDraw(),this._frameTime=performance.now()}setImageSmoothing(){let e=!this.pixelated;e!==this._lastImageSmoothing&&(this.context.imageSmoothingEnabled=e,this._lastImageSmoothing=e)}getSpriteFrame(e){let t=null;if(typeof e=="string"){let i=e,r=null;if(this.runtime&&this.runtime.sprites&&(r=this.runtime.sprites[e]),!r){let n=e.split(".");n.length>1&&this.runtime&&this.runtime.sprites&&(r=this.runtime.sprites[n[0]],t=Number.parseInt(n[1])||0)}if(!r)return this.runtime?.listener?.reportError?.({code:"E7004",message:"Sprite not found",data:{spriteName:i}}),null;e=r}else if(e&&typeof e=="object"&&e.canvas&&!e.frames)return e.canvas||e.image||null;if(!e||!e.ready){let i=typeof e=="string"?e:"unknown";return this.runtime?.listener?.reportError?.({code:"E7005",message:"Sprite not ready",data:{spriteName:i}}),null}let s=e;if(s.frames&&s.frames.length>1){if(t===null){s.animation_start===0&&(s.animation_start=this._frameTime);let i=1e3/s.fps;t=Math.floor((this._frameTime-s.animation_start)/i)%s.frames.length}return t>=0&&t<s.frames.length?s.frames[t].canvas:s.frames[0].canvas}else if(s.frames&&s.frames[0])return s.frames[0].canvas;return null}drawSprite(e,t,s,i,r){let n=this.getSpriteFrame(e);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=t-i/2-this.anchor_x*i/2,o=-s-r/2+this.anchor_y*r/2,u=this.width/2,_=this.height/2;if(a>u||a+i<-u||o>_||o+r<-_)return}this.context.globalAlpha=this.alpha,this.setImageSmoothing(),this.initDrawOp(t,-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,t-i/2-this.anchor_x*i/2,-s-r/2+this.anchor_y*r/2,i,r)}}drawSpritePart(e,t,s,i,r,n,a,o,u){let _=this.getSpriteFrame(e);if(_){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 E=n-o/2-this.anchor_x*o/2,A=-a-u/2+this.anchor_y*u/2,b=this.width/2,O=this.height/2;if(E>b||E+o<-b||A>O||A+u<-O)return}this.context.globalAlpha=this.alpha,this.setImageSmoothing(),this.initDrawOp(n,-a)?(this.context.drawImage(_,t,s,i,r,-o/2-this.anchor_x*o/2,-u/2+this.anchor_y*u/2,o,u),this.closeDrawOp()):this.context.drawImage(_,t,s,i,r,n-o/2-this.anchor_x*o/2,-a-u/2+this.anchor_y*u/2,o,u)}}drawMap(e,t,s,i,r){let n=null;typeof e=="string"?this.runtime&&this.runtime.maps&&(n=this.runtime.maps[e]):n=e,n&&n.ready&&(this.context.globalAlpha=this.alpha,this.setImageSmoothing(),this.initDrawOp(t,-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,t-i/2-this.anchor_x*i/2,-s-r/2+this.anchor_y*r/2,i,r))}},hn=class extends on{static{l(this,"TextScreen")}static{k(this,"TextScreen")}_cachedFontSize=-1;_cachedFontName="";_cachedFontString="";getFontString(e){return(e!==this._cachedFontSize||this.font!==this._cachedFontName)&&(this._cachedFontSize=e,this._cachedFontName=this.font,this._cachedFontString=`${e}pt ${this.font}`),this._cachedFontString}textWidth(e,t){return this.context.font=this.getFontString(t),this.context.measureText(e).width}drawText(e,t,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(e).width,a=i;this.initDrawOp(t,-s)?(this.context.fillText(e,0-this.anchor_x*n/2,0+this.anchor_y*a/2),this.closeDrawOp()):this.context.fillText(e,t-this.anchor_x*n/2,-s+this.anchor_y*a/2)}drawTextOutline(e,t,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(e).width,a=i;this.initDrawOp(t,-s)?(this.context.strokeText(e,0-this.anchor_x*n/2,0+this.anchor_y*a/2),this.closeDrawOp()):this.context.strokeText(e,t-this.anchor_x*n/2,-s+this.anchor_y*a/2)}},ln=class extends hn{static{l(this,"TriangleScreen")}static{k(this,"TriangleScreen")}tri(e,t,s,i,r,n,a){a&&this.setColor(a),this.context.globalAlpha=this.alpha;let o={x:e,y:-t},u={x:s,y:-i},_={x:r,y:-n};Pi(this.context,o,u,_,this.context.fillStyle)}trib(e,t,s,i,r,n,a){a&&this.setColor(a),this.context.globalAlpha=this.alpha;let o={x:e,y:-t},u={x:s,y:-i},_={x:r,y:-n};Li(this.context,o,u,_,this.context.strokeStyle,this.line_width)}ttri(e,t,s,i,r,n,a,o,u,_,E,A,b,O="tiles",m=1,M=1,z=1,w=!1){this.context.globalAlpha=this.alpha;let S=this.canvas.width,H=this.canvas.height,G=Math.min(S/200,H/200),F=k(et=>S/2+et*G,"toCanvasX"),lt=k(et=>H/2-et*G,"toCanvasY"),bt={context:this.context,width:S,height:H,runtime:this.runtime,pixelated:this.pixelated===1};Ai(bt,{x:F(e),y:lt(t),u:a,v:o,z:m},{x:F(s),y:lt(i),u,v:_,z:M},{x:F(r),y:lt(n),u:E,v:A,z},b,O,this.zBuffer,w)}},xi=class extends ln{static{l(this,"Screen")}static{k(this,"Screen")}getInterface(){if(this.interfaceCache)return this.interfaceCache;let e=this;return this.interfaceCache={width:e.width,height:e.height,clear:k(t=>e.clear(t),"clear"),setColor:k(t=>e.setColor(t),"setColor"),setAlpha:k(t=>e.setAlpha(t),"setAlpha"),setPixelated:k(t=>e.setPixelated(t),"setPixelated"),setBlending:k(t=>e.setBlending(t),"setBlending"),setLinearGradient:k((t,s,i,r,n,a)=>e.setLinearGradient(t,s,i,r,n,a),"setLinearGradient"),setRadialGradient:k((t,s,i,r,n)=>e.setRadialGradient(t,s,i,r,n),"setRadialGradient"),setFont:k(t=>e.setFont(t),"setFont"),setTranslation:k((t,s)=>e.setTranslation(t,s),"setTranslation"),setScale:k((t,s)=>e.setScale(t,s),"setScale"),setRotation:k(t=>e.setRotation(t),"setRotation"),setDrawAnchor:k((t,s)=>e.setDrawAnchor(t,s),"setDrawAnchor"),setDrawRotation:k(t=>e.setDrawRotation(t),"setDrawRotation"),setDrawScale:k((t,s)=>e.setDrawScale(t,s),"setDrawScale"),fillRect:k((t,s,i,r,n)=>e.fillRect(t,s,i,r,n),"fillRect"),fillRoundRect:k((t,s,i,r,n,a)=>e.fillRoundRect(t,s,i,r,n,a),"fillRoundRect"),fillRound:k((t,s,i,r,n)=>e.fillRound(t,s,i,r,n),"fillRound"),drawRect:k((t,s,i,r,n)=>e.drawRect(t,s,i,r,n),"drawRect"),drawRoundRect:k((t,s,i,r,n,a)=>e.drawRoundRect(t,s,i,r,n,a),"drawRoundRect"),drawRound:k((t,s,i,r,n)=>e.drawRound(t,s,i,r,n),"drawRound"),drawSprite:k((t,s,i,r,n)=>e.drawSprite(t,s,i,r,n),"drawSprite"),drawSpritePart:k((t,s,i,r,n,a,o,u,_)=>e.drawSpritePart(t,s,i,r,n,a,o,u,_),"drawSpritePart"),drawMap:k((t,s,i,r,n)=>e.drawMap(t,s,i,r,n),"drawMap"),drawText:k((t,s,i,r,n)=>e.drawText(t,s,i,r,n),"drawText"),drawTextOutline:k((t,s,i,r,n)=>e.drawTextOutline(t,s,i,r,n),"drawTextOutline"),textWidth:k((t,s)=>e.textWidth(t,s),"textWidth"),setLineWidth:k(t=>e.setLineWidth(t),"setLineWidth"),setLineDash:k(t=>e.setLineDash(t),"setLineDash"),drawLine:k((t,s,i,r,n)=>e.drawLine(t,s,i,r,n),"drawLine"),drawPolygon:k((...t)=>e.drawPolygon(t),"drawPolygon"),drawPolyline:k((...t)=>e.drawPolyline(t),"drawPolyline"),fillPolygon:k((...t)=>e.fillPolygon(t),"fillPolygon"),drawQuadCurve:k((...t)=>e.drawQuadCurve(t),"drawQuadCurve"),drawBezierCurve:k((...t)=>e.drawBezierCurve(t),"drawBezierCurve"),drawArc:k((t,s,i,r,n,a,o)=>e.drawArc(t,s,i,r,n,a,o),"drawArc"),fillArc:k((t,s,i,r,n,a,o)=>e.fillArc(t,s,i,r,n,a,o),"fillArc"),setCursorVisible:k(t=>e.setCursorVisible(t),"setCursorVisible"),loadFont:k(t=>e.loadFont(t),"loadFont"),isFontReady:k(t=>e.isFontReady(t),"isFontReady"),tri:k((t,s,i,r,n,a,o)=>e.tri(t,s,i,r,n,a,o),"tri"),trib:k((t,s,i,r,n,a,o)=>e.trib(t,s,i,r,n,a,o),"trib"),ttri:k((t,s,i,r,n,a,o,u,_,E,A,b,O,m,M,z,w,S)=>e.ttri(t,s,i,r,n,a,o,u,_,E,A,b,O,m,M,z,w,S),"ttri")},this.interfaceCache}};var cn=Object.defineProperty,me=l((e,t)=>cn(e,"name",{value:t,configurable:!0}),"__name"),vi=1800,Si=240;function Qt(e,t){if(e==null)return e;if(t&&t.includes(e))return null;if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e)){let s=[];for(let i=0;i<e.length;i++)s[i]=Qt(e[i],t);return s}if(typeof e=="object"){let s={};for(let i in e)Object.hasOwn(e,i)&&(s[i]=Qt(e[i],t));return s}return t?null:e}l(Qt,"deepCopy");me(Qt,"deepCopy");var xs=class{static{l(this,"StatePlayer")}static{me(this,"StatePlayer")}looping=!1;loopStart=0;loopIndex=0;loopLength;loopCallback=null;constructor(e=Si){this.loopLength=e}isLooping(){return this.looping}startLoop(e,t){this.looping=!0,this.loopStart=Math.max(e,1),this.loopIndex=0,this.loopCallback=t}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(e,t){if(!(!t||!e)){for(let s in e)Object.hasOwn(e,s)&&!this.isProtectedKey(s)&&delete e[s];for(let s in t)Object.hasOwn(t,s)&&(e[s]=Qt(t[s]))}}isProtectedKey(e){return["screen","audio","keyboard","mouse","touch","gamepad","system","storage","sprites","maps","sounds","music","assets","host","session","memory"].includes(e)}},un=class{static{l(this,"StateRecorder")}static{me(this,"StateRecorder")}history=[];recordIndex=0;recordLength=0;maxLength;excluded=[];constructor(e=vi){this.maxLength=e}setExcluded(e){this.excluded=e}record(e){let t=this.makeStorableState(e);this.history[this.recordIndex++]=t,this.recordLength=Math.min(this.recordLength+1,this.maxLength),this.recordIndex>=this.maxLength&&(this.recordIndex=0)}getState(e){if(e>=this.recordLength)return null;let t=(this.recordIndex-e-1+this.maxLength)%this.maxLength;return this.history[t]}getLength(){return this.recordLength}getMaxLength(){return this.maxLength}clear(){this.history=[],this.recordIndex=0,this.recordLength=0}trimTo(e){if(e>=this.recordLength)return;let t=[],s=this.recordLength,i=e+1;for(let r=s;r>=i;r--){let n=(this.recordIndex-r+this.maxLength)%this.maxLength;t.push(this.history[n])}this.history=t,this.recordIndex=this.history.length,this.recordLength=this.history.length}makeStorableState(e){return Qt(e,this.excluded)}},ki=class{static{l(this,"TimeMachine")}static{me(this,"TimeMachine")}runtime;recorder;player;recording=!1;replayPosition=0;statusCallback;constructor(e){this.runtime=e,this.recorder=new un(vi),this.player=new xs(Si),this.setupExclusions()}setupExclusions(){let e=[];if(this.runtime.vm?.context?.global){let t=this.runtime.vm.context.global;t.random&&e.push(t.random),t.screen&&e.push(t.screen),t.audio&&e.push(t.audio),t.keyboard&&e.push(t.keyboard),t.mouse&&e.push(t.mouse),t.touch&&e.push(t.touch),t.gamepad&&e.push(t.gamepad),t.system&&e.push(t.system),t.storage&&e.push(t.storage),t.host&&e.push(t.host),t.session&&e.push(t.session),t.memory&&e.push(t.memory)}this.recorder.setExcluded(e)}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(e){this.runtime?.listener?.reportError?.({code:"E7082",message:"Time machine step error",data:{error:String(e)}})}}messageReceived(e){switch(e.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":e.position!=null&&this.setReplayPosition(e.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(e){this.recording=!1,this.runtime?.listener?.reportError?.({code:"E7083",message:"Time machine recording error",data:{error:String(e)}})}}stopRecording(){if(this.recording)try{this.recording=!1,this.sendStatus()}catch(e){this.runtime?.listener?.reportError?.({code:"E7083",message:"Time machine recording error",data:{error:String(e)}})}}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(e){if(!isFinite(e)||e<0){this.runtime?.listener?.reportError?.({code:"E7081",message:"Invalid replay position",data:{value:String(e)}});return}let t=Math.round(e);this.replayPosition=Math.max(2,Math.min(this.recorder.getLength()-1,t)),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 e=Math.max(this.replayPosition,1);this.player.startLoop(e,()=>this.loopCallback())}stopLooping(){this.player.isLooping()&&(this.replayPosition=this.player.stopLoop(),this.sendStatus())}replay(e=!1){if(this.replayPosition>=this.recorder.getLength())return;let t=this.recorder.getState(this.replayPosition);t&&this.runtime.vm?.context?.global&&this.player.restoreState(this.runtime.vm.context.global,t),e||this.runtime.drawCall?.()}loopCallback(){let e=this.player.updateLoop();e!==null&&(this.replayPosition=e,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(e){this.statusCallback=e}isRecording(){return this.recording}isLooping(){return this.player.isLooping()}};var fn=Object.defineProperty,T=l((e,t)=>fn(e,"name",{value:t,configurable:!0}),"__name"),Ri={encode:T(e=>{try{return JSON.stringify(e)}catch{return""}},"encode"),decode:T(e=>{try{return JSON.parse(e)}catch{return null}},"decode"),pretty:T((e,t=2)=>{try{return JSON.stringify(e,null,t)}catch{return""}},"pretty")},wi={map:T((e,t)=>e.map(t),"map"),filter:T((e,t)=>e.filter(t),"filter"),reduce:T((e,t,s)=>e.reduce(t,s),"reduce"),find:T((e,t)=>e.find(t)??null,"find"),findIndex:T((e,t)=>e.findIndex(t),"findIndex"),some:T((e,t)=>e.some(t),"some"),every:T((e,t)=>e.every(t),"every"),reverse:T(e=>e.slice().reverse(),"reverse"),sort:T((e,t)=>e.slice().sort(t),"sort"),slice:T((e,t,s)=>e.slice(t,s),"slice"),concat:T((...e)=>[].concat(...e),"concat"),flat:T((e,t=1)=>e.flat(t),"flat"),flatMap:T((e,t)=>e.flatMap(t),"flatMap"),indexOf:T((e,t,s)=>e.indexOf(t,s),"indexOf"),lastIndexOf:T((e,t,s)=>e.lastIndexOf(t,s),"lastIndexOf"),includes:T((e,t,s)=>e.includes(t,s),"includes"),length:T(e=>e.length,"length"),first:T(e=>e[0]??null,"first"),last:T(e=>e[e.length-1]??null,"last"),at:T((e,t)=>{let s=t<0?e.length+t:t;return e[s]??null},"at"),push:T((e,...t)=>(e.push(...t),e),"push"),pop:T(e=>e.pop()??null,"pop"),shift:T(e=>e.shift()??null,"shift"),unshift:T((e,...t)=>(e.unshift(...t),e),"unshift"),splice:T((e,t,s,...i)=>e.splice(t,s??e.length-t,...i),"splice"),fill:T((e,t,s,i)=>e.fill(t,s,i),"fill"),join:T((e,t=",")=>e.join(t),"join"),unique:T(e=>[...new Set(e)],"unique"),shuffle:T(e=>{let t=[...e];for(let s=t.length-1;s>0;s--){let i=Math.floor(Math.random()*(s+1));[t[s],t[i]]=[t[i],t[s]]}return t},"shuffle"),chunk:T((e,t)=>{let s=[];for(let i=0;i<e.length;i+=t)s.push(e.slice(i,i+t));return s},"chunk"),sum:T(e=>{let t=0;for(let s=0;s<e.length;s++)t+=e[s];return t},"sum"),average:T(e=>{if(e.length===0)return 0;let t=0;for(let s=0;s<e.length;s++)t+=e[s];return t/e.length},"average"),min:T(e=>{if(e.length===0)return 0;let t=e[0];for(let s=1;s<e.length;s++)e[s]<t&&(t=e[s]);return t},"min"),max:T(e=>{if(e.length===0)return 0;let t=e[0];for(let s=1;s<e.length;s++)e[s]>t&&(t=e[s]);return t},"max")},Ci={abs:T(e=>Math.abs(e),"abs"),sqrt:T(e=>Math.sqrt(e),"sqrt"),floor:T(e=>Math.floor(e),"floor"),ceil:T(e=>Math.ceil(e),"ceil"),round:T(e=>Math.round(e),"round"),min:T((...e)=>Math.min(...e),"min"),max:T((...e)=>Math.max(...e),"max"),pow:T((e,t)=>e**t,"pow"),exp:T(e=>Math.exp(e),"exp"),log:T(e=>Math.log(e),"log"),log10:T(e=>Math.log10(e),"log10"),sin:T(e=>Math.sin(e),"sin"),cos:T(e=>Math.cos(e),"cos"),tan:T(e=>Math.tan(e),"tan"),asin:T(e=>Math.asin(e),"asin"),acos:T(e=>Math.acos(e),"acos"),atan:T(e=>Math.atan(e),"atan"),atan2:T((e,t)=>Math.atan2(e,t),"atan2"),random:T(()=>Math.random(),"random"),randomInt:T((e,t)=>Math.floor(Math.random()*(t-e+1))+e,"randomInt"),randomFloat:T((e,t)=>Math.random()*(t-e)+e,"randomFloat"),PI:Math.PI,E:Math.E,clamp:T((e,t,s)=>Math.min(Math.max(e,t),s),"clamp"),lerp:T((e,t,s)=>e+(t-e)*s,"lerp"),distance:T((e,t,s,i)=>Math.sqrt((s-e)**2+(i-t)**2),"distance"),distance3D:T((e,t,s,i,r,n)=>Math.sqrt((i-e)**2+(r-t)**2+(n-s)**2),"distance3D"),angleBetween:T((e,t,s,i)=>Math.atan2(i-t,s-e),"angleBetween"),degToRad:T(e=>e*(Math.PI/180),"degToRad"),radToDeg:T(e=>e*(180/Math.PI),"radToDeg"),sign:T(e=>Math.sign(e),"sign"),mod:T((e,t)=>(e%t+t)%t,"mod")},Ii={split:T((e,t="")=>e.split(t),"split"),join:T((e,t="")=>e.join(t),"join"),trim:T(e=>e.trim(),"trim"),trimStart:T(e=>e.trimStart(),"trimStart"),trimEnd:T(e=>e.trimEnd(),"trimEnd"),replace:T((e,t,s)=>e.replace(t,s),"replace"),replaceAll:T((e,t,s)=>e.split(t).join(s),"replaceAll"),startsWith:T((e,t)=>e.startsWith(t),"startsWith"),endsWith:T((e,t)=>e.endsWith(t),"endsWith"),contains:T((e,t)=>e.includes(t),"contains"),toLowerCase:T(e=>e.toLowerCase(),"toLowerCase"),toUpperCase:T(e=>e.toUpperCase(),"toUpperCase"),charAt:T((e,t)=>e.charAt(t),"charAt"),charCodeAt:T((e,t)=>e.charCodeAt(t),"charCodeAt"),fromCharCode:T((...e)=>String.fromCharCode(...e),"fromCharCode"),substring:T((e,t,s)=>e.substring(t,s),"substring"),slice:T((e,t,s)=>e.slice(t,s),"slice"),indexOf:T((e,t,s)=>e.indexOf(t,s),"indexOf"),lastIndexOf:T((e,t,s)=>e.lastIndexOf(t,s),"lastIndexOf"),repeat:T((e,t)=>e.repeat(t),"repeat"),padStart:T((e,t,s=" ")=>e.padStart(t,s),"padStart"),padEnd:T((e,t,s=" ")=>e.padEnd(t,s),"padEnd"),length:T(e=>e.length,"length"),parseInt:T((e,t)=>{let s=Number.parseInt(e,t);return isNaN(s)?0:s},"parseInt"),parseFloat:T(e=>{let t=Number.parseFloat(e);return isNaN(t)?0:t},"parseFloat"),format:T((e,...t)=>e.replace(/{(\d+)}/g,(s,i)=>{let r=Number.parseInt(i);return typeof t[r]<"u"?String(t[r]):s}),"format")};var pn=Object.defineProperty,y=l((e,t)=>pn(e,"name",{value:t,configurable:!0}),"__name"),Vt=class Ss{static{l(this,"_Random")}static{y(this,"Random")}_seed;a=13971;b=12345;size=1<<30;mask;norm;constructor(t,s=!0){this._seed=t??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(t){return Math.floor(this.next()*t)}nextSeed(){return this._seed=this._seed*this.a+this.b&this.mask}seed(t){return this._seed=t??Math.random(),this._seed<1&&(this._seed*=1<<30),this.nextSeed(),this.nextSeed(),this.nextSeed()}clone(t){return t!=null?new Ss(t):new Ss(this._seed,!1)}},d=class U{static{l(this,"_Token")}static{y(this,"Token")}tokenizer;type;value;string_value;line;column;start;length;index;reserved_keyword;is_binary_operator;constructor(t,s,i,r){this.tokenizer=t,this.type=s,this.value=i,this.string_value=r,this.line=t.line,this.column=t.column,this.start=t.token_start,this.length=t.index-this.start,this.index=t.index,this.type===U.TYPE_IDENTIFIER&&Object.hasOwn(U.predefined,String(this.value))&&(this.type=U.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:U.TYPE_RETURN,break:U.TYPE_BREAK,continue:U.TYPE_CONTINUE,function:U.TYPE_FUNCTION,for:U.TYPE_FOR,to:U.TYPE_TO,by:U.TYPE_BY,in:U.TYPE_IN,while:U.TYPE_WHILE,if:U.TYPE_IF,then:U.TYPE_THEN,else:U.TYPE_ELSE,elsif:U.TYPE_ELSIF,end:U.TYPE_END,object:U.TYPE_OBJECT,class:U.TYPE_CLASS,extends:U.TYPE_EXTENDS,new:U.TYPE_NEW,and:U.TYPE_AND,or:U.TYPE_OR,not:U.TYPE_NOT,after:U.TYPE_AFTER,every:U.TYPE_EVERY,do:U.TYPE_DO,sleep:U.TYPE_SLEEP,delete:U.TYPE_DELETE,local:U.TYPE_LOCAL,var:U.TYPE_LOCAL,let:U.TYPE_LOCAL}},dn=class{static{l(this,"Tokenizer")}static{y(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(e,t){this.input=e,this.filename=t,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(e){return this.buffer.splice(0,0,e),e}peek(){if(this.buffer.length>0)return this.buffer[0];let e=this.next();return e&&this.pushBack(e),e}finished(){return this.index>=this.input.length&&this.buffer.length===0}nextChar(e=!1){let t,s;if(t=this.input.charAt(this.index++),t===`
124
+ `)this.line+=1,this.last_column=this.column,this.column=0;else if(t==="/"&&!e){if(this.input.charAt(this.index)==="/"){for(;t=this.input.charAt(this.index++),!(t===`
125
+ `||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(t=this.input.charAt(this.index++),t===`
126
+ `)this.line+=1,this.last_column=this.column,this.column=0,s=0;else if(t==="*")s=1;else{if(t==="/"&&s===1)break;s=0}if(this.index>=this.input.length)break}return this.nextChar()}}else this.column+=1;return t}rewind(){this.index-=1,this.column-=1,this.input.charAt(this.index)===`
127
+ `&&(this.line-=1,this.column=this.last_column)}next(){let e,t;if(this.buffer.length>0)return this.buffer.splice(0,1)[0];for(;;){if(this.index>=this.input.length)return null;if(e=this.nextChar(),t=e.charCodeAt(0),t>32&&t!==160)break}return this.token_start=this.index-1,this.doubles[e]!=null?this.parseDouble(e,this.doubles[e]):this.chars[e]!=null?new d(this,this.chars[e],e):e==="!"?this.parseUnequals(e):t>=48&&t<=57?this.parseNumber(e):t>=65&&t<=90||t>=97&&t<=122||t===95||this.letter_regex.test(e)?this.parseIdentifier(e):e==='"'?this.parseString(e,'"'):e==="'"?this.parseString(e,"'"):e==="`"?this.parseString(e,"`"):this.error("Syntax Error")}changeNumberToIdentifier(){let e,t,s,i=[];if(t=this.next(),t!=null&&t.type===d.TYPE_NUMBER){for(s=(t.string_value||String(t.value)).split("."),e=s.length-1;e>=0;e--)s[e].length>0&&this.pushBack(new d(this,d.TYPE_IDENTIFIER,s[e])),e>0&&i.push(this.pushBack(new d(this,d.TYPE_DOT,".")));return i}else return t!=null&&t.type===d.TYPE_STRING?this.pushBack(new d(this,d.TYPE_IDENTIFIER,t.value)):t?this.pushBack(t):void 0}parseDouble(e,t){let s=this.input.charAt(this.index);return e==="="&&s===">"?(this.nextChar(),new d(this,d.TYPE_ARROW,"=>")):this.shifts[e]!=null&&this.index<this.input.length&&s===e?(this.nextChar(),new d(this,this.shifts[e],e+e)):t&&this.index<this.input.length&&s==="="?(this.nextChar(),new d(this,t[1],e+"=")):new d(this,t?t[0]:this.chars[e],e)}parseUnequals(e){return this.index<this.input.length&&this.input.charAt(this.index)==="="?(this.nextChar(),new d(this,d.TYPE_UNEQUALS,"!=")):this.error("Expected inequality !=")}parseIdentifier(e){let t,s;for(;;){if(this.index>=this.input.length)return new d(this,d.TYPE_IDENTIFIER,e);if(t=this.nextChar(),s=t.charCodeAt(0),s>=65&&s<=90||s>=97&&s<=122||s===95||s>=48&&s<=57||this.letter_regex.test(t))e+=t;else return this.rewind(),new d(this,d.TYPE_IDENTIFIER,e)}}parseNumber(e){let t,s,i=!1,r=!1;for(;;){if(this.index>=this.input.length)return new d(this,d.TYPE_NUMBER,Number.parseFloat(e),e);if(t=this.nextChar(),s=t.charCodeAt(0),t==="."&&!r&&!i)r=!0,e+=t;else if(s>=48&&s<=57)e+=t;else if((t==="e"||t==="E")&&!i&&this.index<this.input.length)i=!0,e+=t,t=this.nextChar(),t==="+"||t==="-"?e+=t:this.rewind();else return(t==="x"||t==="X")&&e==="0"?this.parseHexNumber("0x"):(this.rewind(),new d(this,d.TYPE_NUMBER,Number.parseFloat(e),e))}}parseHexNumber(e){let t;for(;;){if(this.index>=this.input.length)return new d(this,d.TYPE_NUMBER,Number.parseInt(e),e);if(t=this.nextChar(),/[a-fA-F0-9]/.test(t))e+=t;else return this.rewind(),new d(this,d.TYPE_NUMBER,Number.parseInt(e),e)}}parseString(e,t){let s,i=0,r;for(t==null&&(t='"'),t==='"'&&this.input.charAt(this.index)==='"'&&this.input.charAt(this.index+1)==='"'&&this.input.charAt(this.index+2)!=='"'&&(t='"""',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":e+=`
128
+ `;break;case"\\":e+="\\";break;case t:e+=t;break;default:e+="\\"+r}else if(s===t)if(r=this.nextChar(!0),r===t)e+=s;else return this.rewind(),e+=s,new d(this,t==="`"?d.TYPE_TEMPLATE:d.TYPE_STRING,e.substring(1,e.length-1));else{if(t==='"""'&&s==='"'){if(i+=1,i===3)return new d(this,d.TYPE_STRING,e.substring(1,e.length-2))}else i=0;e+=s}}}error(e){throw new Error(e)}},mn=class{static{l(this,"OPCODES_CLASS2")}static{y(this,"OPCODES_CLASS")}table={};set(t,s){return this[t]=s,this[s]=t,this.table[t]=s,this.table[s]=t,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)}},g=new mn,W=class _e{static{l(this,"_Routine")}static{y(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;source;ics;constructor(t=0){this.num_args=t,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 t=new _e(this.num_args);return t.opcodes=[...this.opcodes],t.arg1=[...this.arg1],t.ref=[...this.ref],t.locals_size=this.locals_size,t.uses_arguments=this.uses_arguments,t.source=this.source,t}createLabel(t="label"){return":"+t+"_"+this.label_count++}setLabel(t){return this.labels[t]=this.opcodes.length}optimize(){this.transpile&&new Transpiler().transpile(this)}removeable(t){let s=this.labels;for(let i in s)if(s[i]===t)return!1;return!0}remove(t){let s=this.labels;for(let i in s){let r=s[i];if(r===t)return!1;r>t&&(this.labels[i]-=1)}return this.opcodes.splice(t,1),this.arg1.splice(t,1),this.ref.splice(t,1),!0}resolveLabels(){for(let t=0;t<this.opcodes.length;t++){let s=this.opcodes[t];if(s===g.JUMP||s===g.JUMPY||s===g.JUMPN||s===g.JUMPY_NOPOP||s===g.JUMPN_NOPOP)this.labels[this.arg1[t]]&&(this.arg1[t]=this.labels[this.arg1[t]]);else if(s===g.FORLOOP_CONTROL||s===g.FORLOOP_INIT||s===g.FORIN_CONTROL||s===g.FORIN_INIT){let i=this.arg1[t];i&&this.labels[i[1]]&&(i[1]=this.labels[i[1]])}}}OP(t,s,i=0){return this.opcodes.push(t),this.arg1.push(i),this.ref.push(s)}OP_INSERT(t,s,i=0,r){this.opcodes.splice(r,0,t),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(t){return this.OP(g.TYPE,t)}VARIABLE_TYPE(t,s){return this.OP(g.VARIABLE_TYPE,s,t)}PROPERTY_TYPE(t){return this.OP(g.PROPERTY_TYPE,t)}LOAD_THIS(t){return this.OP(g.LOAD_THIS,t)}LOAD_GLOBAL(t){return this.OP(g.LOAD_GLOBAL,t)}LOAD_VALUE(t,s){return this.OP(g.LOAD_VALUE,s,t)}LOAD_LOCAL(t,s){return this.OP(g.LOAD_LOCAL,s,t)}LOAD_VARIABLE(t,s){return this.OP(g.LOAD_VARIABLE,s,t)}LOAD_LOCAL_OBJECT(t,s){return this.OP(g.LOAD_LOCAL_OBJECT,s,t)}LOAD_VARIABLE_OBJECT(t,s){return this.OP(g.LOAD_VARIABLE_OBJECT,s,t)}POP(t){return this.OP(g.POP,t)}LOAD_PROPERTY(t){return this.OP(g.LOAD_PROPERTY,t)}LOAD_PROPERTY_OBJECT(t){return this.OP(g.LOAD_PROPERTY_OBJECT,t)}CREATE_OBJECT(t){return this.OP(g.CREATE_OBJECT,t)}MAKE_OBJECT(t){return this.OP(g.MAKE_OBJECT,t)}CREATE_ARRAY(t){return this.OP(g.CREATE_ARRAY,t)}CREATE_CLASS(t,s){return this.OP(g.CREATE_CLASS,s,t)}UPDATE_CLASS(t,s){return this.OP(g.UPDATE_CLASS,s,t)}NEW_CALL(t,s){return this.OP(g.NEW_CALL,s,t)}ADD(t,s=0){return this.OP(g.ADD,t,s)}SUB(t,s=0){return this.OP(g.SUB,t,s)}MUL(t){return this.OP(g.MUL,t)}DIV(t){return this.OP(g.DIV,t)}MODULO(t){return this.OP(g.MODULO,t)}BINARY_AND(t){return this.OP(g.BINARY_AND,t)}BINARY_OR(t){return this.OP(g.BINARY_OR,t)}SHIFT_LEFT(t){return this.OP(g.SHIFT_LEFT,t)}SHIFT_RIGHT(t){return this.OP(g.SHIFT_RIGHT,t)}NEGATE(t){return this.OP(g.NEGATE,t)}LOAD_PROPERTY_ATOP(t){return this.OP(g.LOAD_PROPERTY_ATOP,t)}EQ(t){return this.OP(g.EQ,t)}NEQ(t){return this.OP(g.NEQ,t)}LT(t){return this.OP(g.LT,t)}GT(t){return this.OP(g.GT,t)}LTE(t){return this.OP(g.LTE,t)}GTE(t){return this.OP(g.GTE,t)}NOT(t){return this.OP(g.NOT,t)}FORLOOP_INIT(t,s){return this.OP(g.FORLOOP_INIT,s,t)}FORLOOP_CONTROL(t,s){return this.OP(g.FORLOOP_CONTROL,s,t)}FORIN_INIT(t,s){return this.OP(g.FORIN_INIT,s,t)}FORIN_CONTROL(t,s){return this.OP(g.FORIN_CONTROL,s,t)}JUMP(t,s){return this.OP(g.JUMP,s,t)}JUMPY(t,s){return this.OP(g.JUMPY,s,t)}JUMPN(t,s){return this.OP(g.JUMPN,s,t)}JUMPY_NOPOP(t,s){return this.OP(g.JUMPY_NOPOP,s,t)}JUMPN_NOPOP(t,s){return this.OP(g.JUMPN_NOPOP,s,t)}STORE_LOCAL(t,s){return this.OP(g.STORE_LOCAL,s,t)}STORE_VARIABLE(t,s){return this.OP(g.STORE_VARIABLE,s,t)}CREATE_PROPERTY(t){return this.OP(g.CREATE_PROPERTY,t)}STORE_PROPERTY(t){return this.OP(g.STORE_PROPERTY,t)}LOAD_ROUTINE(t,s){return this.OP(g.LOAD_ROUTINE,s,t)}FUNCTION_CALL(t,s){return this.OP(g.FUNCTION_CALL,s,t)}FUNCTION_APPLY_VARIABLE(t,s){return this.OP(g.FUNCTION_APPLY_VARIABLE,s,t)}FUNCTION_APPLY_PROPERTY(t,s){return this.OP(g.FUNCTION_APPLY_PROPERTY,s,t)}SUPER_CALL(t,s){return this.OP(g.SUPER_CALL,s,t)}RETURN(t){return this.OP(g.RETURN,t)}AFTER(t){return this.OP(g.AFTER,t)}EVERY(t){return this.OP(g.EVERY,t)}DO(t){return this.OP(g.DO,t)}SLEEP(t){return this.OP(g.SLEEP,t)}DELETE(t){return this.OP(g.DELETE,t)}UNARY_OP(t,s){return this.OP(g.UNARY_OP,s,t)}BINARY_OP(t,s){return this.OP(g.BINARY_OP,s,t)}toString(){let t="";for(let s=0;s<this.opcodes.length;s++){let i=this.opcodes[s];t+=g[i],this.arg1[s]!=null&&(t+=` ${this.arg1[s]}`),t+=`
129
+ `}return t}exportArg(t){return t==null?0:t instanceof _e?t.export():typeof t=="function"?t.name:t}export(){let t=[];for(let s=0;s<this.arg1.length;s++)t[s]=this.exportArg(this.arg1[s]);return{num_args:this.num_args,ops:this.opcodes,args:t,import_refs:this.import_refs,import_values:this.import_values,import_self:this.import_self,locals_size:this.locals_size}}import(t){this.num_args=t.num_args,this.opcodes=t.ops,this.arg1=t.args,this.import_refs=t.import_refs,this.import_values=t.import_values,this.import_self=t.import_self,this.locals_size=t.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 _e(0).import(this.arg1[r])),this.ref[r]=i;return this}},j=class{static{l(this,"Expression")}static{y(this,"Expression")}nowarning;nopop;constructor(){}},gt=class Xt{static{l(this,"_Program")}static{y(this,"Program")}statements=[];static Field;static Variable;static Assignment;constructor(){this.statements=[]}add(t){return this.statements.push(t)}isAssignment(){return this.statements.length>0&&this.statements[this.statements.length-1]instanceof _t}static toString(t,s=0){let i,r,n,a,o;if(t instanceof W)return s===0&&t.source||"[function]";if(typeof t=="function")return"[native function]";if(typeof t=="string")return`"${t}"`;if(Array.isArray(t)){if(s>=1)return"[list]";for(a="[",i=0;i<t.length;i++)o=t[i],a+=Xt.toString(o,s+1)+(i<t.length-1?",":"");return a+"]"}else if(typeof t=="object"&&t!==null){if(s>=1)return"[object]";for(a=`object
130
+ `,n="",i=1;i<=s;i++)n+=" ";for(r in t)o=t[r],a+=n+` ${r} = ${Xt.toString(o,s+1)}
131
+ `;return a+n+"end"}return t||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(t,s,i){return s instanceof ut?(s.appendField(i),s):new ut(t,s,[i])}static BuildOperations(t,s){let i,r,n,a,o,u;for(;t.length>1;){for(i=0;i<t.length-1&&(n=t[i],a=t[i+1],!(Xt.Precedence[a.operation]<=Xt.Precedence[n.operation]));)i++;o=s[i],u=s[i+1],r=new ie(t[i].token,t[i].operation,o,u),s.splice(i,2,r),t.splice(i,1)}return new ie(t[0].token,t[0].operation,s[0],s[1])}},_t=class extends j{static{l(this,"Assignment")}static{y(this,"Assignment")}token;field;expression;local;constructor(e,t,s,i){super(),this.token=e,this.field=t,this.expression=s,this.local=i}},Yi=class extends j{static{l(this,"SelfAssignment")}static{y(this,"SelfAssignment")}token;field;operation;expression;constructor(e,t,s,i){super(),this.token=e,this.field=t,this.operation=s,this.expression=i}},N=class extends j{static{l(this,"Value")}static{y(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(e,t,s){super(),this.token=e,this.type=t,this.value=s}},K=class extends j{static{l(this,"Variable")}static{y(this,"Variable")}token;identifier;constructor(e,t){super(),this.token=e,this.identifier=t}},ut=class extends j{static{l(this,"Field")}static{y(this,"Field")}token;expression;chain;constructor(e,t,s){super(),this.token=e,this.expression=t,this.chain=s,this.token=t instanceof j?t.token:e}appendField(e){return this.chain.push(e)}},ie=class extends j{static{l(this,"Operation")}static{y(this,"Operation")}token;operation;term1;term2;constructor(e,t,s,i){super(),this.token=e,this.operation=t,this.term1=s,this.term2=i}},Ui=class extends j{static{l(this,"Negate")}static{y(this,"Negate")}token;expression;constructor(e,t){super(),this.token=e,this.expression=t}},Bi=class extends j{static{l(this,"Not")}static{y(this,"Not")}token;expression;constructor(e,t){super(),this.token=e,this.expression=t}},ks=class extends j{static{l(this,"Braced")}static{y(this,"Braced")}token;expression;constructor(e,t){super(),this.token=e,this.expression=t}},ee=class extends j{static{l(this,"Return")}static{y(this,"Return")}token;expression;constructor(e,t){super(),this.token=e,this.expression=t}},ji=class extends j{static{l(this,"Condition")}static{y(this,"Condition")}token;chain;constructor(e,t){super(),this.token=e,this.chain=t}},Gi=class extends j{static{l(this,"For")}static{y(this,"For")}token;iterator;range_from;range_to;range_by;sequence;constructor(e,t,s,i,r,n){super(),this.token=e,this.iterator=t,this.range_from=s,this.range_to=i,this.range_by=r,this.sequence=n}},Vi=class extends j{static{l(this,"ForIn")}static{y(this,"ForIn")}token;iterator;list;sequence;constructor(e,t,s,i){super(),this.token=e,this.iterator=t,this.list=s,this.sequence=i}},zi=class extends j{static{l(this,"While")}static{y(this,"While")}token;condition;sequence;constructor(e,t,s){super(),this.token=e,this.condition=t,this.sequence=s}},ge=class extends j{static{l(this,"Break")}static{y(this,"Break")}token;nopop=!0;constructor(e){super(),this.token=e,this.nopop=!0}},Ee=class extends j{static{l(this,"Continue")}static{y(this,"Continue")}token;nopop=!0;constructor(e){super(),this.token=e,this.nopop=!0}},se=class extends j{static{l(this,"Function2")}static{y(this,"Function")}token;args;sequence;source;constructor(e,t,s,i){super(),this.token=e,this.args=t,this.sequence=s,this.source="function"+e.tokenizer.input.substring(e.index,i.index+2)}},St=class extends j{static{l(this,"FunctionCall")}static{y(this,"FunctionCall")}token;expression;args;constructor(e,t,s){super(),this.token=e,this.expression=t,this.args=s}},Wi=class extends j{static{l(this,"CreateObject")}static{y(this,"CreateObject")}token;fields;constructor(e,t){super(),this.token=e,this.fields=t}},Rs=class extends j{static{l(this,"CreateClass")}static{y(this,"CreateClass")}token;ext;fields;constructor(e,t,s){super(),this.token=e,this.ext=t,this.fields=s}},Hi=class extends j{static{l(this,"NewCall")}static{y(this,"NewCall")}token;expression;constructor(e,t){super(),this.token=e,this.expression=t,this.expression instanceof St||(this.expression=new St(this.token,this.expression,[]))}},ws=class extends j{static{l(this,"After")}static{y(this,"After")}token;delay;sequence;multiplier;source;constructor(e,t,s,i,r){super(),this.token=e,this.delay=t,this.sequence=s,this.multiplier=r,this.source="after "+e.tokenizer.input.substring(e.index,i.index+2)}},Cs=class extends j{static{l(this,"Every")}static{y(this,"Every")}token;delay;sequence;multiplier;source;constructor(e,t,s,i,r){super(),this.token=e,this.delay=t,this.sequence=s,this.multiplier=r,this.source="every "+e.tokenizer.input.substring(e.index,i.index+2)}},Is=class extends j{static{l(this,"Do")}static{y(this,"Do")}token;sequence;source;constructor(e,t,s){super(),this.token=e,this.sequence=t,this.source="do "+e.tokenizer.input.substring(e.index,s.index+2)}},qi=class extends j{static{l(this,"Sleep")}static{y(this,"Sleep")}token;delay;multiplier;constructor(e,t,s){super(),this.token=e,this.delay=t,this.multiplier=s}},$i=class extends j{static{l(this,"Delete")}static{y(this,"Delete")}token;field;constructor(e,t){super(),this.token=e,this.field=t}};gt.Field=ut;gt.Variable=K;gt.Assignment=_t;var _n={E1001:"E1001",E1002:"E1002",E1004:"E1004"},vs=_n,gn=class extends Error{static{l(this,"LootiScriptError")}static{y(this,"LootiScriptError")}file;line;column;stackTrace;constructor(e,t,s,i,r){super(e),this.file=t,this.line=s,this.column=i,this.stackTrace=r,this.name="LootiScriptError"}toString(){let e=`${this.name}: ${this.message}
132
+ `;return e+=` at ${this.file}:${this.line}:${this.column}
133
+ `,e}},Di=class extends gn{static{l(this,"LootiSyntaxError")}static{y(this,"LootiSyntaxError")}context;code;suggestions;related;constructor(e,t,s,i,r,n,a,o){super(e,t,s,i),this.context=r,this.code=n,this.suggestions=a,this.related=o,this.name="SyntaxError"}toString(){let e="";return this.code&&(e+=`[${this.code}] `),e+=`${this.name}: ${this.message}
134
+ `,e+=` at ${this.file}:${this.line}:${this.column}
135
+ `,this.context&&(e+=`
148
136
  ${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=`
137
+ `),e}};function Zt(e,t,s,i=3,r=1){let n=e.split(`
138
+ `),a=Math.max(0,t-i-1),o=Math.min(n.length-1,t+i-1),u=`
151
139
  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("""
140
+ `;for(let _=a;_<=o;_++){let E=_+1,A=E===t?">":" ",b=String(E).padStart(4," "),O=n[_]||"";if(u+=`${A} ${b} | ${O}
141
+ `,E===t){let M=" ".repeat(8+Math.max(0,s-1))+"^".repeat(Math.max(1,r));u+=`${M}
142
+ `}}return u}l(Zt,"formatSourceContext");y(Zt,"formatSourceContext");var Ki=class te{static{l(this,"_Parser")}static{y(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(t,s=""){this.input=t,this.filename=s,/^\s*\/\/\s*javascript\s*\n/.test(this.input)&&(this.input=`system.javascript("""
155
143
 
156
144
  `+this.input.replace(/\\/g,"\\\\")+`
157
145
 
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+`
146
+ """)`),this.tokenizer=new dn(this.input,this.filename),this.program=new gt,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 t=this.tokenizer.next();if(t==null)throw this.unexpected_eof=!0,"Unexpected end of file";return this.current=t}nextTokenOptional(){let t=this.tokenizer.next();return t!=null&&(this.current=t),t}parse(){let t,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=Zt(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:vs.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(t=n,t instanceof Di)return this.error_info={error:t.message,line:t.line,column:t.column,context:t.context};if(this.not_terminated.length>0&&t==="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 M=this.function_stack[m];if(M.token===i){a=M.name,o=M.line,u=M.column;break}}let _=typeof i.value=="string"?i.value.length:1,E=Zt(i.tokenizer.input,i.line,i.column,3,_),A,b=[],O;return i.value==="function"&&a?(A=`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"],O={file:this.filename,line:o,column:u,message:`Function '${a}' started here`}):(A=`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:A,line:i.line,column:i.column,context:E,code:vs.E1001,suggestions:b,related:O}}else{let a=Zt(this.input,this.current.line,this.current.column,3,1);return this.error_info={error:typeof t=="string"?t:t.message||String(t),line:this.current.line,column:this.current.column,context:a,code:vs.E1004}}}}parseLine(){let t=this.nextTokenOptional();if(t==null)return null;switch(t.type){case d.TYPE_RETURN:return new ee(t,this.parseExpression());case d.TYPE_BREAK:return new ge(t);case d.TYPE_CONTINUE:return new Ee(t);case d.TYPE_LOCAL:return this.parseLocalAssignment(t);default:return this.tokenizer.pushBack(t),this.parseExpression()}}parseExpression(t,s=!1){let i,r;if(r=this.parseExpressionStart(),r==null)return null;for(;;){if(i=this.parseExpressionSuffix(r,t),i==null)return r;if(s&&i instanceof St)return i;r=i}}assertExpression(t,s=!1){let i=this.parseExpression(t,s);if(i==null)throw"Expression expected";return i}parseExpressionSuffix(t,s){let i,r,n=this.nextTokenOptional();if(n==null)return s==="self"?t:null;switch(n.type){case d.TYPE_DOT:return t instanceof N&&t.type===N.TYPE_NUMBER?(this.tokenizer.pushBack(n),null):(this.tokenizer.changeNumberToIdentifier(),r=this.assertBroadIdentifier("Expected identifier"),gt.CreateFieldAccess(n,t,new N(r,N.TYPE_STRING,r.value)));case d.TYPE_OPEN_BRACKET:return i=this.assertExpression(),this.assert(d.TYPE_CLOSED_BRACKET,"Expected ']'"),gt.CreateFieldAccess(n,t,i);case d.TYPE_OPEN_BRACE:return this.parseFunctionCall(n,t);case d.TYPE_EQUALS:return this.parseAssignment(n,t);case d.TYPE_PLUS_EQUALS:return this.parseSelfAssignment(n,t,n.type);case d.TYPE_MINUS_EQUALS:return this.parseSelfAssignment(n,t,n.type);case d.TYPE_MULTIPLY_EQUALS:return this.parseSelfAssignment(n,t,n.type);case d.TYPE_DIVIDE_EQUALS:return this.parseSelfAssignment(n,t,n.type);case d.TYPE_MODULO_EQUALS:case d.TYPE_AND_EQUALS:case d.TYPE_OR_EQUALS:return this.parseSelfAssignment(n,t,n.type);default:return s==="self"?(this.tokenizer.pushBack(n),t):n.is_binary_operator&&s!=="noop"?this.parseBinaryOperation(n,t):(this.tokenizer.pushBack(n),null)}}parseExpressionStart(){let t,s=this.nextTokenOptional();if(s==null)return null;switch(s.type){case d.TYPE_IDENTIFIER:return new K(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 Ui(s,this.assertExpression("noop")),"self");case d.TYPE_NOT:return this.parseExpressionSuffix(new Bi(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(t=this.assert(d.TYPE_NUMBER,"malformed number"),!Number.isInteger(t.value))throw"malformed number";return new N(s,N.TYPE_NUMBER,Number.parseFloat(`.${t.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(t){return new N(t,N.TYPE_NUMBER,t.value)}parseStringExpression(t){let s=this.nextTokenOptional();return s!=null&&this.tokenizer.pushBack(s),new N(t,N.TYPE_STRING,t.value)}parseArray(t){let s=[];for(;;){let i=this.nextToken();if(i.type===d.TYPE_CLOSED_BRACKET)return new N(t,N.TYPE_ARRAY,s);i.type===d.TYPE_COMMA||(this.tokenizer.pushBack(i),s.push(this.assertExpression()))}}parseBinaryOperation(t,s){let i=[{token:t,operation:t.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 gt.BuildOperations(i,r)}parseAssignment(t,s){let i;if(!(s instanceof K||s instanceof ut))throw"Expected variable identifier or property";this.object_nesting===0&&s instanceof K&&this.api_reserved[s.identifier]&&this.warnings.push({type:"assigning_api_variable",identifier:s.identifier,line:t.line,column:t.column});let r=this.tokenizer.peek(),n=null;s instanceof K&&(n=s.identifier),r&&(r.type,d.TYPE_FUNCTION);let a=this.assertExpression();if(a instanceof se&&n&&this.function_stack.length>0){let o=a.token;for(let u=this.function_stack.length-1;u>=0;u--){let _=this.function_stack[u];if(_.token===o&&_.name==="anonymous"){_.name=n;break}}}return s instanceof ut?(this.object_nesting+=1,i=new _t(t,s,a,!1),this.object_nesting-=1):i=new _t(t,s,a,!1),i}parseSelfAssignment(t,s,i){if(!(s instanceof K||s instanceof ut))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 Yi(t,s,r,this.assertExpression())}parseLocalAssignment(t){let s=this.assert(d.TYPE_IDENTIFIER,"Expected identifier");return this.parseOptionalType(),this.assert(d.TYPE_EQUALS,"Expected '='"),new _t(t,new K(s,s.value),this.assertExpression(),!0)}parseBracedExpression(t){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 ks(t,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(t,s){let i=[];for(let a of s)if(a instanceof K)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 N||n instanceof K||n instanceof ie||n instanceof St||n instanceof _t||n instanceof ks?r.push(new ee(t,n)):r.push(n)),new se(t,i,r,t)}parseFunctionCall(t,s){let i=[];for(this.last_function_call=new St(t,s,i);;){let r=this.nextTokenOptional();if(r==null)return this.error("missing closing parenthese");if(r.type===d.TYPE_CLOSED_BRACE)return new St(r,s,i);r.type===d.TYPE_COMMA||(this.tokenizer.pushBack(r),i.push(this.assertExpression()))}}addTerminable(t){return this.not_terminated.push(t)}endTerminable(){this.not_terminated.length>0&&this.not_terminated.splice(this.not_terminated.length-1,1)}parseFunction(t){let s,i=this.parseFunctionArgs(),r=[];this.nesting+=1;let n={name:"anonymous",line:t.line,column:t.column,token:t};this.function_stack.push(n),this.addTerminable(t);try{for(;;){let a=this.nextToken();if(a.type===d.TYPE_END)return this.nesting-=1,this.endTerminable(),this.function_stack.pop(),new se(t,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===t&&this.function_stack.pop(),a}}parseFunctionArgs(){let t=[],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 t;if(i.type===d.TYPE_COMMA)s=null;else if(i.type===d.TYPE_EQUALS&&s==="argument"){let r=this.assertExpression();t.length>0&&(t[t.length-1].default=r)}else if(i.type===d.TYPE_IDENTIFIER)s="argument",t.push({name:i.value}),this.parseOptionalType();else return this.error("Unexpected token")}}warningAssignmentCondition(t){t instanceof _t&&this.warnings.push({type:"assignment_as_condition",line:t.token.line,column:t.token.column})}parseIf(t){let s,i,r=[],n={condition:this.assertExpression(),sequence:[]};if(this.addTerminable(t),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 ji(t,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(t,s){let i=this.nextToken();if(i.type!==t)throw s;return i}assertBroadIdentifier(t){let s=this.nextToken();if(s.type!==d.TYPE_IDENTIFIER&&s.reserved_keyword&&(s.type=d.TYPE_IDENTIFIER),s.type!==d.TYPE_IDENTIFIER)throw t;return s}error(t){let s=this.current,i=Zt(s.tokenizer.input,s.line,s.column,2);throw new Di(t,s.tokenizer.filename,s.line,s.column,i)}parseOptionalType(){let t=this.nextTokenOptional();if(t!=null)if(t.type===d.TYPE_COLON)for(this.assert(d.TYPE_IDENTIFIER,"Expected type identifier");;)if(t=this.nextTokenOptional(),t&&t.type===d.TYPE_OPEN_BRACKET)this.assert(d.TYPE_CLOSED_BRACKET,"Expected ']'");else{t&&this.tokenizer.pushBack(t);break}else this.tokenizer.pushBack(t)}parseFor(t){let s,i,r,n,a,o=this.assertExpression();if(o instanceof _t){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 K?new Gi(t,u.identifier,r,n,i,this.parseSequence(t)):this.error("Malformed for loop"))}else return o instanceof K?(this.assert(d.TYPE_IN,"Error expected keyword 'in'"),s=this.assertExpression(),new Vi(t,o.identifier,s,this.parseSequence(t))):this.error("Malformed for loop")}parseWhile(t){let s=this.assertExpression();return new zi(t,s,this.parseSequence(t))}parseSequence(t){let s,i=[];for(t!=null&&this.addTerminable(t),this.nesting+=1;;){let r=this.nextToken();if(r.type===d.TYPE_END)return t!=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(t){let s,i=[];for(this.nesting+=1,this.object_nesting+=1,this.addTerminable(t);;){let r=this.nextToken();if(r.type===d.TYPE_END)return this.nesting-=1,this.object_nesting-=1,this.endTerminable(),new Wi(t,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(t){let s,i=null,r=[];this.nesting+=1,this.object_nesting+=1,this.addTerminable(t);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 Rs(t,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(t){let s=this.assertExpression(null,!0);return new Hi(t,s)}tryParseMultiplier(){let t=null,s=this.nextToken();return s.type===d.TYPE_IDENTIFIER&&te.multipliers[s.value]&&(t=te.multipliers[s.value],s=this.nextToken()),{multiplier:t,token:s}}parseBlock(t){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 ${t}`)}}parseAfter(t){this.nesting+=1,this.addTerminable(t);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 ws(t,s,n,a,i)}parseEvery(t){this.nesting+=1,this.addTerminable(t);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 Cs(t,s,n,a,i)}parseDo(t){this.nesting+=1,this.addTerminable(t);let{sequence:s,endToken:i}=this.parseBlock("do");return new Is(t,s,i)}parseSleep(t){let s=null,i=this.assertExpression(),r=this.nextToken();return r!=null&&(r.type===d.TYPE_IDENTIFIER&&te.multipliers[r.value]?s=te.multipliers[r.value]:this.tokenizer.pushBack(r)),new qi(t,i,s)}parseDelete(t){let s=this.parseExpression();return s==null||!(s instanceof K||s instanceof ut)?this.error("expecting variable name or property access after keyword `delete`"):new $i(t,s)}parseTemplate(t){let s=t.value,i=0,r=[];for(;i<s.length;){let a=s.indexOf("${",i);if(a===-1){i<s.length&&r.push(new N(t,N.TYPE_STRING,s.substring(i)));break}a>i&&r.push(new N(t,N.TYPE_STRING,s.substring(i,a)));let o=1,u=a+2,_=!1,E="";for(;u<s.length&&o>0;){let m=s[u];_?m===E&&s[u-1]!=="\\"&&(_=!1):m==='"'||m==="'"||m==="`"?(_=!0,E=m):m==="{"?o++:m==="}"&&o--,o>0&&u++}if(o>0)throw this.error("Unclosed template interpolation");let A=s.substring(a+2,u),O=new this.constructor(A,t.tokenizer.filename).parseExpression();O&&r.push(O),i=u+1}if(r.length===0)return new N(t,N.TYPE_STRING,"");let n=r[0];for(let a=1;a<r.length;a++)n=new ie(t,"+",n,r[a]);return n}};function Ns(e,t,s){let i=e.main_thread.processor.constructor,r=new i(e);return function(){let n=Math.min(t.num_args,arguments.length);r.load(t);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,t.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(Ns,"routineAsFunction");y(Ns,"routineAsFunction");function Pe(e,t,s){let i=e.main_thread.processor.constructor,r=new i(e);return function(){let n=t.num_args;r.load(t),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,t.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(Pe,"routineAsApplicableFunction");y(Pe,"routineAsApplicableFunction");function Ji(e,t,s){return t instanceof W?Ns(e,t,s):t??0}l(Ji,"argToNative");y(Ji,"argToNative");var vt={UNINITIALIZED:0,MONOMORPHIC:1,POLYMORPHIC:2,MEGAMORPHIC:3},Qi=1e3,Oe=[],Ae=[];function Xi(){if(Oe.length>0){let e=Oe.pop();return e.length=0,e}return[]}l(Xi,"getPooledArray");y(Xi,"getPooledArray");function Zi(e){Oe.length<Qi&&Oe.push(e)}l(Zi,"recycleArray");y(Zi,"recycleArray");function tr(){return Ae.length>0?Ae.pop():{}}l(tr,"getPooledObject");y(tr,"getPooledObject");function er(e){if(Ae.length<Qi){for(let t in e)delete e[t];Ae.push(e)}}l(er,"recycleObject");y(er,"recycleObject");function Ms(e,t,s){return t instanceof W?(t.as_function==null&&(t.as_function=Pe(e,t,s)),t.as_function):typeof t=="function"?t:null}l(Ms,"resolveCallable");y(Ms,"resolveCallable");function kt(e,t,s,i,r,n,a){let o;if(Array.isArray(i))o=t.global.List;else if(typeof i=="string"){if(a&&isFinite(i)){let _=a(i,r);return isFinite(_)?_:0}o=t.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=t.global.Object[s]),u!=null){let _=Ms(e,u,t);if(_)return _.call(t.global,i,r,n)}return 0}l(kt,"dispatchBinaryOp");y(kt,"dispatchBinaryOp");function be(e,t,s,i,r){return kt(e,t,"+",s,i,r)}l(be,"operatorAdd");y(be,"operatorAdd");function Te(e,t,s,i,r){return kt(e,t,"-",s,i,r,(n,a)=>n-a)}l(Te,"operatorSub");y(Te,"operatorSub");function ye(e,t,s,i,r){return kt(e,t,"*",s,i,r,(n,a)=>n*a)}l(ye,"operatorMul");y(ye,"operatorMul");function Ds(e,t,s,i,r){return kt(e,t,"/",s,i,r,(n,a)=>n/a)}l(Ds,"operatorDiv");y(Ds,"operatorDiv");function sr(e,t,s,i,r){return kt(e,t,"&",s,i,r,(n,a)=>n&a)}l(sr,"operatorBand");y(sr,"operatorBand");function ir(e,t,s,i,r){return kt(e,t,"|",s,i,r,(n,a)=>n|a)}l(ir,"operatorBor");y(ir,"operatorBor");function rr(e,t,s,i){let r;if(Array.isArray(s))r=t.global.List;else if(typeof s=="string"){if(isFinite(s)){let a=s%i;return isFinite(a)?a:0}r=t.global.String}else r=s;let n=r["%"];for(;n==null&&r.class!=null;)r=r.class,n=r["%"];return n==null&&(n=t.global.Object["%"]),n!=null&&n instanceof W?(n.as_function==null&&(n.as_function=Pe(e,n,t)),n=n.as_function,n.call(t.global,s,i)):0}l(rr,"operatorModulo");y(rr,"operatorModulo");function nr(e,t,s){let i;if(Array.isArray(s))i=t.global.List;else if(typeof s=="string"){if(isFinite(s))return-s;i=t.global.String}else i=s;let r=i["-"];for(;r==null&&i.class!=null;)i=i.class,r=i["-"];if(r==null&&(r=t.global.Object["-"]),r!=null){let n=Ms(e,r,t);if(n)return n.call(t.global,0,s)}return 0}l(nr,"operatorNegate");y(nr,"operatorNegate");var ar=class{static{l(this,"Processor")}static{y(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(e){this.runner=e,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(e){typeof this.runner?.reportNativeError=="function"?this.runner.reportNativeError(e):console.error(e)}getArray(){return Xi()}recycleArray(e){Zi(e)}getObject(){return tr()}recycleObject(e){er(e)}load(e){this.routine=e,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 e=this.generateStackTrace();return e.length===0?"":e.map(t=>` at ${t.functionName} (${t.file}:${t.line}:${t.column})`).join(`
147
+ `)}resolveParentClass(e,t){if(e.class!=null&&typeof e.class=="string"){if(t[e.class]!=null&&(e.class=t[e.class],typeof e.class!="string"))return this.resolveParentClass(e.class,t)}else if(e.class!=null&&typeof e.class!="string")return this.resolveParentClass(e.class,t)}applyFunction(e){}resolvePropertyIC(e,t,s){if(e==null)return null;if(s.state===vt.MONOMORPHIC){let i=e.class||e.constructor;if(i===s.shape)return s.hits++,e[t];s.misses++,s.state=vt.POLYMORPHIC,s.shapes=[s.shape,i],s.offsets=[0,0]}else if(s.state===vt.POLYMORPHIC){let i=e.class||e.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++,e[t];s.shapes.push(i),s.misses++}else s.state=vt.MEGAMORPHIC}return s.state===vt.UNINITIALIZED&&(s.state=vt.MONOMORPHIC,s.shape=e.class||e.constructor,s.property=t,s.hits=1),e[t]}routineAsFunction(e,t){return Ns(this.runner,e,t)}routineAsApplicableFunction(e,t){return Pe(this.runner,e,t)}argToNative(e,t){return Ji(this.runner,e,t)}run(e){let t,s,i,r,n,a,o,u,_,E,A,b,O,m,M,z,w,S,H,G,F,lt,bt,et,q,Rt,wt,Ct,ft,pt,$,Pt,Y,D,nt,rt,st,ct,R,dt,L,C,at,f,Z,Ne,Me,Fe,oe,It,$s,Ks,Ye,Dt,Js,Qs,Xs,Zs,ti,ei,Tt,Lt,x,Ue,si,Be,c,h,tt,Nt,P,je,p,yt,Ge;x=this.routine,Z=this.routine.opcodes,s=this.routine.arg1,$=Z.length,f=this.op_index,c=this.stack,h=this.stack_index,Y=this.locals,Pt=this.local_index,w=this.global||e.global,C=this.object||w,o=this.call_stack,u=this.call_stack_index,_=this.call_super||w,E=this.call_supername||"",D=this.locals_offset,at=0,Lt=-1;let he=this.profilingEnabled;for(;f<$;)switch(he&&this.metrics.ops++,Z[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 W?c[h]="function":c[h]="object"}f++;break;case 2:if(p=C[s[f]],p==null&&(p=w[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 W?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 W?c[--h]="function":c[--h]="object"}f++;break;case 4:c[++h]=x.import_values[s[f++]];break;case 5:c[++h]=C,f++;break;case 6:c[++h]=w,f++;break;case 10:c[++h]=s[f++];break;case 11:c[++h]=Y[D+s[f++]];break;case 12:if(R=s[f],p=C[R],p==null&&C.class!=null)for(L=C;p==null&&L.class!=null;)L=L.class,p=L[R];p==null&&(p=w[R]),p==null&&!x.ref[f].nowarning&&(P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.using_undefined_variable[F]||(e.warnings.using_undefined_variable[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:R})),c[++h]=p??0,f++;break;case 13:dt=Y[D+s[f]],typeof dt!="object"&&(dt=Y[D+s[f]]={},P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.assigning_field_to_undefined[F]||(e.warnings.assigning_field_to_undefined[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:P.value})),c[++h]=dt,f++;break;case 14:for(R=s[f],L=C,p=L[R];p==null&&L.class!=null;)L=L.class,p=L[R];p==null&&w[R]!=null&&(L=w,p=w[R]),(p==null||typeof p!="object")&&(p=L[R]={},P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.assigning_field_to_undefined[F]||(e.warnings.assigning_field_to_undefined[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:s[f]})),c[++h]=p,f++;break;case 15:h--,f++;break;case 16:{L=c[h-1],R=c[h];let v=x.ics[f];if(v||(v=x.ics[f]={state:vt.UNINITIALIZED,hits:0,misses:0,property:R}),p=this.resolvePropertyIC(L,R,v),p==null&&L.class!=null){let le=L;for(;p==null&&le.class!=null;)le=le.class,p=le[R]}p==null&&(p=0,x.ref[f].nowarning||(x.ref[f].nowarning=!0,Array.isArray(L)||(P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.using_undefined_variable[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:R}))),c[--h]=p,f++;break}case 17:p=c[h-1][c[h]],typeof p!="object"&&(p=c[h-1][c[h]]={},P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.assigning_field_to_undefined[F]||(e.warnings.assigning_field_to_undefined[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:c[h]})),c[--h]=p,f++;break;case 18:he&&this.metrics.allocations++,c[++h]=this.getObject(),f++;break;case 19:typeof c[h]!="object"&&(he&&this.metrics.allocations++,c[h]=this.getObject()),f++;break;case 20:he&&this.metrics.allocations++,c[++h]=this.getArray(),f++;break;case 21:Y[D+s[f]]=c[h],f++;break;case 22:Y[D+s[f]]=c[h--],f++;break;case 23:C[s[f++]]=c[h];break;case 24:L=c[h-2],z=c[h-1],L[z]=c[h],h-=2,f++;break;case 25:L=c[h-2],z=c[h-1],c[h-2]=L[z]=c[h],h-=2,f++;break;case 26:L=c[h-1],z=c[h],delete L[z],c[h-=1]=0,f++;break;case 27:if(R=s[f],C[R]!=null&&typeof C[R]=="object"){L=C[R],Be=c[h];for(Ct in Be)yt=Be[Ct],L[Ct]=yt}else C[R]=c[h];f++;break;case 28:Tt={},Me=c[h],Me?Tt.class=Me:s[f]&&(Tt.class=s[f]),c[h]=Tt,f++;break;case 29:if(a=c[h],i=s[f],typeof a=="function"){for(t=[],S=Rt=0,$s=i-1;Rt<=$s;S=Rt+=1)t.push(c[h-i+S]);h-=i,c[h-1]=new a(...t),f++}else{for(this.resolveParentClass(a,w),Tt={class:a},A=a.constructor;!A&&a.class!=null;)a=a.class,A=a.constructor;if(A!=null&&A instanceof W){if(c[h-i-1]=Tt,h--,b=o[u]||(o[u]={}),u++,b.routine=x,b.object=C,b.super=_,b.supername=E,b.op_index=f+1,D+=x.locals_size,x=A,Z=A.opcodes,s=A.arg1,f=0,$=Z.length,C=Tt,_=a,E="constructor",x.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<A.num_args)for(S=wt=i+1,Ks=A.num_args;wt<=Ks;S=wt+=1)c[++h]=0;else i>A.num_args&&(h-=i-A.num_args);c[++h]=i,x.uses_arguments&&(c[++h]=r)}else h-=i,c[h-1]=Tt,f++}break;case 30:n=c[h--],t=c[h],typeof t=="number"?(t+=n,c[h]=isFinite(t)||typeof n=="string"?t:0):c[h]=be(this.runner,e,t,n,s[f]),f++;break;case 31:n=c[h--],t=c[h],typeof t=="number"?(t-=n,c[h]=isFinite(t)?t:0):c[h]=Te(this.runner,e,t,n,s[f]),f++;break;case 32:n=c[h--],t=c[h],typeof t=="number"?(t*=n,c[h]=isFinite(t)?t:0):c[h]=ye(this.runner,e,t,n,0),f++;break;case 33:n=c[h--],t=c[h],typeof t=="number"?(t/=n,c[h]=isFinite(t)?t:0):c[h]=Ds(this.runner,e,t,n,0),f++;break;case 34:n=c[h--],t=c[h],typeof t=="number"&&typeof n=="number"?(t%=n,c[h]=isFinite(t)?t:0):c[h]=rr(this.runner,e,t,n),f++;break;case 35:n=c[h--],t=c[h],typeof t=="number"?(t&=n,c[h]=isFinite(t)?t:0):c[h]=sr(this.runner,e,t,n,0),f++;break;case 36:n=c[h--],t=c[h],typeof t=="number"?(t|=n,c[h]=isFinite(t)?t:0):c[h]=ir(this.runner,e,t,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:t=c[h],typeof t=="number"?c[h]=-t:c[h]=nr(this.runner,e,t),f++;break;case 50:c[h]=c[h]?0:1,f++;break;case 68:for(L=c[h-1],R=c[h],p=L[R];p==null&&L.class!=null;)L=L.class,p=L[R];p==null&&(p=0,x.ref[f].nowarning||(x.ref[f].nowarning=!0,Array.isArray(L)||(P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.using_undefined_variable[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:R}))),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:et=s[f][0],rt=Y[D+et+1]=c[h-1],nt=c[h],q=Y[D+et],c[--h]=0,nt===0?(Y[D+et+2]=rt>q?1:-1,f++):(Y[D+et+2]=nt,nt>0&&q>rt||nt<0&&q<rt?f=s[f][1]:f++);break;case 96:et=s[f][0],nt=Y[D+et+2],rt=Y[D+et+1],q=Y[D+et],q+=nt,nt>0&&q>rt||nt<0&&q<rt?f++:(Y[D+et]=q,f=s[f][1]),at++>500&&(at=0,performance.now()>this.time_limit&&(Lt=f,f=$));break;case 97:p=c[h],c[h]=0,q=s[f][0],typeof p=="object"?Array.isArray(p)?Y[D+q+1]=p:p=Y[D+q+1]=Object.keys(p):typeof p=="string"?p=Y[D+q+1]=p.split(""):p=Y[D+q+1]=[],p.length===0?f=s[f][1]:(yt=p[0],Y[D+s[f][0]]=yt??0,Y[D+q+2]=0,f++);break;case 98:q=s[f][0],lt=Y[D+q+2]+=1,p=Y[D+q+1],lt<p.length?(yt=p[lt],Y[D+q]=yt??0,f=s[f][1]):f++,at++>500&&(at=0,performance.now()>this.time_limit&&(Lt=f,f=$));break;case 80:f=s[f],at++>500&&(at=0,performance.now()>this.time_limit&&(Lt=f,f=$));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(oe=s[f++],It=oe.clone(),Ye=oe.import_refs,ft=0,pt=Ye.length;ft<pt;ft++)bt=Ye[ft],bt===oe.import_self?It.import_values.push(It):It.import_values.push(Y[D+bt]);It.object=C,c[++h]=It;break;case 90:if(i=s[f],m=c[h],m instanceof W){h--,b=o[u]||(o[u]={}),u++,b.routine=x,b.object=C,b.super=_,b.supername=E,b.op_index=f+1;let v=x.ref[f]?.token;if(v&&this.call_stack_frames.push({functionName:m.source||"[anonymous function]",file:v.tokenizer.filename,line:v.line,column:v.column}),D+=x.locals_size,x=m,Z=m.opcodes,s=m.arg1,f=0,$=Z.length,C=x.object!=null?x.object:w,_=w,E="",x.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(S=st=i+1,Dt=m.num_args;st<=Dt;S=st+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,x.uses_arguments&&(c[++h]=r)}else if(typeof m=="function"){switch(i){case 0:try{p=m()}catch(v){O=v,this.reportNativeError(O),p=0}c[h]=p??0;break;case 1:try{p=m(this.argToNative(c[h-1],e))}catch(v){O=v,this.reportNativeError(O),p=0}c[h-1]=p??0,h-=1;break;case 2:try{p=m(this.argToNative(c[h-2],e),this.argToNative(c[h-1],e))}catch(v){O=v,this.reportNativeError(O),p=0}c[h-2]=p??0,h-=2;break;case 3:try{p=m(this.argToNative(c[h-3],e),this.argToNative(c[h-2],e),this.argToNative(c[h-1],e))}catch(v){O=v,this.reportNativeError(O),p=0}c[h-3]=p??0,h-=3;break;default:for(r=this._argv,r.length=0,h-=i,S=ct=0,Js=i-1;ct<=Js;S=ct+=1)r[S]=this.argToNative(c[h+S],e);try{p=m.apply(null,r)}catch(v){O=v,this.reportNativeError(O),p=0}c[h]=p??0}f++}else h-=i,c[h]=m??0,P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.invoking_non_function[F]||(M=x.ref[f],H=M.expression.token.start,G=M.token.start+M.token.length,e.warnings.invoking_non_function[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:M.token.tokenizer.input.substring(H,G)}),f++;break;case 91:if(R=c[h],tt=L=C,m=L[R],m==null){for(;m==null&&tt.class!=null;)tt=tt.class,m=tt[R];m==null&&(m=w.Object[R]),m==null&&(m=w[R],tt=w,L=w)}if(i=s[f],m instanceof W){if(h-=1,b=o[u]||(o[u]={}),u++,b.routine=x,b.object=C,b.super=_,b.supername=E,b.op_index=f+1,D+=x.locals_size,x=m,Z=m.opcodes,s=m.arg1,f=0,$=Z.length,C=L,_=tt,E=R,x.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(S=Ne=i+1,Qs=m.num_args;Ne<=Qs;S=Ne+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,x.uses_arguments&&(c[++h]=r)}else if(typeof m=="function"){switch(i){case 0:try{p=m.call(L)}catch(v){O=v,this.reportNativeError(O),p=0}c[h]=p??0;break;case 1:try{p=m.call(L,this.argToNative(c[h-1],e))}catch(v){O=v,this.reportNativeError(O),p=0}c[--h]=p??0;break;case 2:try{p=m.call(L,this.argToNative(c[h-2],e),this.argToNative(c[h-1],e))}catch(v){O=v,this.reportNativeError(O),p=0}c[h-2]=p??0,h-=2;break;case 3:try{p=m.call(L,this.argToNative(c[h-3],e),this.argToNative(c[h-2],e),this.argToNative(c[h-1],e))}catch(v){O=v,this.reportNativeError(O),p=0}c[h-3]=p??0,h-=3;break;default:for(r=this._argv,r.length=0,h-=i,S=Fe=0,Xs=i-1;Fe<=Xs;S=Fe+=1)r[S]=this.argToNative(c[h+S],e);try{p=m.apply(L,r)}catch(v){O=v,this.reportNativeError(O),p=0}c[h]=p??0}f++}else h-=i,c[h]=m??0,P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.invoking_non_function[F]||(M=x.ref[f],H=M.expression.token.start,G=M.token.start+M.token.length,e.warnings.invoking_non_function[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:M.token.tokenizer.input.substring(H,G)}),f++;break;case 92:for(L=c[h-1],tt=L,R=c[h],m=L[R];m==null&&tt.class!=null;)tt=tt.class,m=tt[R];if(i=s[f],m==null&&(L instanceof W?m=w.Function[R]:typeof L=="string"?m=w.String[R]:typeof L=="number"?m=w.Number[R]:Array.isArray(L)?m=w.List[R]:typeof L=="object"&&(m=w.Object[R])),m instanceof W){if(h-=2,b=o[u]||(o[u]={}),u++,b.object=C,b.super=_,b.supername=E,b.routine=x,b.op_index=f+1,D+=x.locals_size,x=m,Z=m.opcodes,s=m.arg1,f=0,$=Z.length,C=L,_=tt,E=R,x.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(S=Ue=i+1,Zs=m.num_args;Ue<=Zs;S=Ue+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,x.uses_arguments&&(c[++h]=r)}else if(typeof m=="function"){switch(i){case 0:try{p=m.call(L)}catch(v){O=v,this.reportNativeError(O),p=0}c[--h]=p??0;break;case 1:try{p=m.call(L,this.argToNative(c[h-2],e))}catch(v){O=v,this.reportNativeError(O),p=0}c[h-2]=p??0,h-=2;break;case 2:try{p=m.call(L,this.argToNative(c[h-3],e),this.argToNative(c[h-2],e))}catch(v){O=v,this.reportNativeError(O),p=0}c[h-3]=p??0,h-=3;break;case 3:try{p=m.call(L,this.argToNative(c[h-4],e),this.argToNative(c[h-3],e),this.argToNative(c[h-2],e))}catch(v){O=v,this.reportNativeError(O),p=0}c[h-4]=p??0,h-=4;break;default:for(r=this._argv,r.length=0,h-=i+1,S=je=0,ti=i-1;je<=ti;S=je+=1)r[S]=this.argToNative(c[h+S],e);try{p=m.apply(L,r)}catch(v){O=v,this.reportNativeError(O),p=0}c[h]=p??0}f++}else h-=i+1,c[h]=m??0,P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.invoking_non_function[F]||(M=x.ref[f],H=M.expression.token.start,G=M.token.start+M.token.length,e.warnings.invoking_non_function[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:M.token.tokenizer.input.substring(H,G)}),f++;break;case 93:if(_!=null&&E!=null){for(tt=_,m=null;m==null&&tt.class!=null;)tt=tt.class,m=tt[E];if(m!=null&&m instanceof W){if(i=s[f],b=o[u]||(o[u]={}),u++,b.object=C,b.super=_,b.supername=E,b.routine=x,b.op_index=f+1,D+=x.locals_size,x=m,Z=m.opcodes,s=m.arg1,f=0,$=Z.length,_=tt,x.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(S=Ge=i+1,ei=m.num_args;Ge<=ei;S=Ge+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,x.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:Pt-=s[f],u<=0?f=$:(b=o[--u],C=b.object,_=b.super,E=b.supername,x=b.routine,f=b.op_index,Z=x.opcodes,s=x.arg1,D-=x.locals_size,$=Z.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:Nt=this.runner.createThread(c[h-1],c[h],!1),c[--h]=Nt,f+=1;break;case 111:Nt=this.runner.createThread(c[h-1],c[h],!0),c[--h]=Nt,f+=1;break;case 112:Nt=this.runner.createThread(c[h],0,!1),c[h]=Nt,f+=1;break;case 113:si=isFinite(c[h])?c[h]:0,this.runner.sleep(si),f+=1,Lt=f,f=$;break;case 120:if(R=s[f].name,i=s[f].args,p=C[R],p==null&&C.class!=null)for(L=C;p==null&&L.class!=null;)L=L.class,p=L[R];if(p==null&&(p=w[R]),p==null&&!x.ref[f].nowarning&&(P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.using_undefined_variable[F]||(e.warnings.using_undefined_variable[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:R})),m=p??0,m instanceof W){b=o[u]||(o[u]={}),u++,b.routine=x,b.object=C,b.super=_,b.supername=E,b.op_index=f+1;let v=x.ref[f]?.token;if(v&&this.call_stack_frames.push({functionName:m.source||"[anonymous function]",file:v.tokenizer.filename,line:v.line,column:v.column}),D+=x.locals_size,x=m,Z=m.opcodes,s=m.arg1,f=0,$=Z.length,C=x.object!=null?x.object:w,_=w,E="",x.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(S=st=i+1,Dt=m.num_args;st<=Dt;S=st+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,x.uses_arguments&&(c[++h]=r)}else if(typeof m=="function"){switch(i){case 0:try{p=m()}catch(v){this.reportNativeError(v),p=0}c[++h]=p??0;break;case 1:try{p=m(this.argToNative(c[h],e))}catch(v){this.reportNativeError(v),p=0}c[h]=p??0;break;case 2:try{p=m(this.argToNative(c[h-1],e),this.argToNative(c[h],e))}catch(v){this.reportNativeError(v),p=0}c[--h]=p??0;break;case 3:try{p=m(this.argToNative(c[h-2],e),this.argToNative(c[h-1],e),this.argToNative(c[h],e))}catch(v){this.reportNativeError(v),p=0}c[h-2]=p??0,h-=2;break;default:for(r=this._argv,r.length=0,h-=i-1,S=0;S<i;S++)r[S]=this.argToNative(c[h+S],e);try{p=m.apply(null,r)}catch(v){this.reportNativeError(v),p=0}c[h]=p??0}f++}else h-=i,c[++h]=m??0,f++;break;case 121:for(i=s[f],L=c[h-1],R=c[h],p=L[R];p==null&&L.class!=null;)L=L.class,p=L[R];if(p==null&&(p=0,x.ref[f].nowarning||(x.ref[f].nowarning=!0,Array.isArray(L)||(P=x.ref[f].token,F=P.tokenizer.filename+"-"+P.line+"-"+P.column,e.warnings.using_undefined_variable[F]={file:P.tokenizer.filename,line:P.line,column:P.column,expression:R}))),m=p,c[--h]=m,m instanceof W){h--,b=o[u]||(o[u]={}),u++,b.routine=x,b.object=C,b.super=_,b.supername=E,b.op_index=f+1;let v=x.ref[f]?.token;if(v&&this.call_stack_frames.push({functionName:m.source||"[anonymous function]",file:v.tokenizer.filename,line:v.line,column:v.column}),D+=x.locals_size,x=m,Z=m.opcodes,s=m.arg1,f=0,$=Z.length,C=x.object!=null?x.object:w,_=w,E="",x.uses_arguments&&(r=c.slice(h-i+1,h+1)),i<m.num_args)for(S=st=i+1,Dt=m.num_args;st<=Dt;S=st+=1)c[++h]=0;else i>m.num_args&&(h-=i-m.num_args);c[++h]=i,x.uses_arguments&&(c[++h]=r)}else if(typeof m=="function"){switch(i){case 0:try{p=m()}catch(v){this.reportNativeError(v),p=0}c[h]=p??0;break;case 1:try{p=m(this.argToNative(c[h-1],e))}catch(v){this.reportNativeError(v),p=0}c[h-1]=p??0,h--;break;case 2:try{p=m(this.argToNative(c[h-2],e),this.argToNative(c[h-1],e))}catch(v){this.reportNativeError(v),p=0}c[h-2]=p??0,h-=2;break;case 3:try{p=m(this.argToNative(c[h-3],e),this.argToNative(c[h-2],e),this.argToNative(c[h-1],e))}catch(v){this.reportNativeError(v),p=0}c[h-3]=p??0,h-=3;break;default:for(r=this._argv,r.length=0,h-=i,S=0;S<i;S++)r[S]=this.argToNative(c[h+S],e);try{p=m.apply(null,r)}catch(v){this.reportNativeError(v),p=0}c[h]=p??0}f++}else h-=i,c[h]=m??0,f++;break;case 122:t=s[f],n=c[h],typeof n=="number"?(n+=t,c[h]=isFinite(n)?n:0):c[h]=be(this.runner,e,n,t,0),f++;break;case 123:t=s[f],n=c[h],typeof n=="number"?(n-=t,c[h]=isFinite(n)?n:0):c[h]=Te(this.runner,e,n,t,0),f++;break;case 124:t=s[f],n=c[h],typeof n=="number"?(n*=t,c[h]=isFinite(n)?n:0):c[h]=ye(this.runner,e,n,t,0),f++;break;case 125:t=Y[D+s[f]],n=c[h],typeof n=="number"&&typeof t=="number"?(n+=t,c[h]=isFinite(n)?n:0):c[h]=be(this.runner,e,n,t,0),f++;break;case 126:t=Y[D+s[f]],n=c[h],typeof n=="number"&&typeof t=="number"?(n-=t,c[h]=isFinite(n)?n:0):c[h]=Te(this.runner,e,n,t,0),f++;break;case 127:t=Y[D+s[f]],n=c[h],typeof n=="number"&&typeof t=="number"?(n*=t,c[h]=isFinite(n)?n:0):c[h]=ye(this.runner,e,n,t,0),f++;break;case 128:t=s[f],n=c[h],typeof n=="number"?(n/=t,c[h]=isFinite(n)?n:0):c[h]=Ds(this.runner,e,n,t,0),f++;break;case 129:t=Y[D+s[f]],c[h]=c[h]<t?1:0,f++;break;case 130:t=Y[D+s[f]],c[h]=c[h]>t?1:0,f++;break;case 131:t=Y[D+s[f]],c[h]=c[h]===t?1:0,f++;break;case 200:h=s[f](c,h,Y,D,C,w),f++;break;default:throw`Unsupported operation: ${Z[f]}`}return Lt>=0?(this.op_index=Lt,this.routine=x,this.stack_index=h,this.local_index=Pt,this.object=C,this.call_stack_index=u,this.call_super=_,this.call_supername=E,this.locals_offset=D,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: "+at),console.info(`stack_index: ${h}`),console.info(`result: ${c[h]}`)),c[h]}},or=class ht{static{l(this,"_Compiler")}static{y(this,"Compiler")}program;code_saves;code;routine;locals;count;break_label;continue_label;processor;constructor(t){let s,i,r,n,a;for(this.program=t,this.code_saves=[],this.code=[""],this.routine=new W(0),this.locals=new Ni(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 ee||a instanceof ge||a instanceof Ee));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 t=this.routine.opcodes,s=this.routine.arg1,i=this.routine.ref,r=0;for(;r<t.length-1;){if(t[r]===g.LOAD_VARIABLE&&t[r+1]===g.FUNCTION_CALL){let n=s[r],a=s[r+1],o=i[r+1];t[r]=g.LOAD_VAR_CALL,s[r]={name:n,args:a},i[r]=o,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_PROPERTY&&t[r+1]===g.FUNCTION_CALL){let n=s[r+1],a=i[r+1];t[r]=g.LOAD_PROP_CALL,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_VALUE&&typeof s[r]=="number"&&t[r+1]===g.ADD){let n=s[r],a=i[r+1];t[r]=g.LOAD_CONST_ADD,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_VALUE&&typeof s[r]=="number"&&t[r+1]===g.SUB){let n=s[r],a=i[r+1];t[r]=g.LOAD_CONST_SUB,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_VALUE&&typeof s[r]=="number"&&t[r+1]===g.MUL){let n=s[r],a=i[r+1];t[r]=g.LOAD_CONST_MUL,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_LOCAL&&t[r+1]===g.ADD){let n=s[r],a=i[r+1];t[r]=g.LOAD_LOCAL_ADD,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_LOCAL&&t[r+1]===g.SUB){let n=s[r],a=i[r+1];t[r]=g.LOAD_LOCAL_SUB,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_LOCAL&&t[r+1]===g.MUL){let n=s[r],a=i[r+1];t[r]=g.LOAD_LOCAL_MUL,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_VALUE&&typeof s[r]=="number"&&t[r+1]===g.DIV){let n=s[r],a=i[r+1];t[r]=g.LOAD_CONST_DIV,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_LOCAL&&t[r+1]===g.LT){let n=s[r],a=i[r+1];t[r]=g.LOAD_LOCAL_LT,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_LOCAL&&t[r+1]===g.GT){let n=s[r],a=i[r+1];t[r]=g.LOAD_LOCAL_GT,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}if(t[r]===g.LOAD_LOCAL&&t[r+1]===g.EQ){let n=s[r],a=i[r+1];t[r]=g.LOAD_LOCAL_EQ,s[r]=n,i[r]=a,t.splice(r+1,1),s.splice(r+1,1),i.splice(r+1,1);continue}r++}}compile(t){if(t instanceof N)this.compileValue(t);else if(t instanceof ie)this.compileOperation(t);else if(t instanceof _t)this.compileAssignment(t);else if(t instanceof K)this.compileVariable(t);else if(t instanceof se)this.compileFunction(t);else if(t instanceof St)this.compileFunctionCall(t);else if(t instanceof zi)this.compileWhile(t);else if(t instanceof Yi)this.compileSelfAssignment(t);else if(t instanceof ks)this.compileBraced(t);else if(t instanceof Wi)this.compileCreateObject(t);else if(t instanceof ut)this.compileField(t);else if(t instanceof Ui)this.compileNegate(t);else if(t instanceof Gi)this.compileFor(t);else if(t instanceof Vi)this.compileForIn(t);else if(t instanceof Bi)this.compileNot(t);else if(t instanceof ee)this.compileReturn(t);else if(t instanceof ji)this.compileCondition(t);else if(t instanceof ge)this.compileBreak(t);else if(t instanceof Ee)this.compileContinue(t);else if(t instanceof Rs)this.compileCreateClass(t);else if(t instanceof Hi)this.compileNewCall(t);else if(t instanceof ws)this.compileAfter(t);else if(t instanceof Cs)this.compileEvery(t);else if(t instanceof Is)this.compileDo(t);else if(t instanceof qi)this.compileSleep(t);else if(t instanceof $i)this.compileDelete(t);else throw console.info(t),"Not implemented"}compileAssignment(t){let s,i,r,n,a,o;if(t.local)if(t.field instanceof K)t.expression instanceof se?(n=this.locals.register(t.field.identifier),this.compile(t.expression),this.routine.arg1[this.routine.arg1.length-1].import_self=n,this.routine.STORE_LOCAL(n,t)):t.expression instanceof ws||t.expression instanceof Is||t.expression instanceof Cs?(n=this.locals.register(t.field.identifier),s=this.routine.arg1.length,this.compile(t.expression),this.routine.arg1[s].import_self=n,this.routine.STORE_LOCAL(n,t)):(this.compile(t.expression),n=this.locals.register(t.field.identifier),this.routine.STORE_LOCAL(n,t));else throw"illegal";else if(t.field instanceof K)this.locals.get(t.field.identifier)!=null?(this.compile(t.expression),n=this.locals.get(t.field.identifier),this.routine.STORE_LOCAL(n,t)):t.expression instanceof Rs?this.compileUpdateClass(t.expression,t.field.identifier):(this.compile(t.expression),this.routine.STORE_VARIABLE(t.field.identifier,t));else{for(i=t.field,i.expression instanceof K?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,t):(this.compile(i.expression),this.routine.MAKE_OBJECT(t)),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(t.expression),this.routine.STORE_PROPERTY(t)}}compileSelfAssignment(t){let s,i,r,n,a,o;switch(t.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: "+t.operation}if(t.field instanceof K)this.locals.get(t.field.identifier)!=null?(r=this.locals.get(t.field.identifier),this.routine.LOAD_LOCAL(r,t),this.compile(t.expression),this.routine[a](t),this.routine.STORE_LOCAL(r,t)):(this.routine.LOAD_VARIABLE(t.field.identifier,t),this.compile(t.expression),this.routine[a](t),this.routine.STORE_VARIABLE(t.field.identifier,t));else{for(s=t.field,s.expression instanceof K?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,t)):s.expression.identifier==="global"?this.routine.LOAD_GLOBAL(s):this.routine.LOAD_VARIABLE_OBJECT(s.expression.identifier,t):(this.compile(s.expression),this.routine.MAKE_OBJECT(t)),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(t),this.compile(t.expression),this.routine[a](t),this.routine.STORE_PROPERTY(t)}}compileOperation(t){let s,i,r;if((i=t.operation)==="+"||i==="-"||i==="*"||i==="/"||i==="%"||i==="&"||i==="|"||i==="<<"||i===">>"){if(t.term1 instanceof N&&t.term1.type===N.TYPE_NUMBER&&t.term2 instanceof N&&t.term2.type===N.TYPE_NUMBER){let n,a=t.term1.value,o=t.term2.value;switch(t.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,t);return}switch(this.compile(t.term1),this.compile(t.term2),t.operation){case"+":this.routine.ADD(t);break;case"-":this.routine.SUB(t);break;case"*":this.routine.MUL(t);break;case"/":this.routine.DIV(t);break;case"%":this.routine.MODULO(t);break;case"&":this.routine.BINARY_AND(t);break;case"|":this.routine.BINARY_OR(t);break;case"<<":this.routine.SHIFT_LEFT(t);break;case">>":this.routine.SHIFT_RIGHT(t)}}else if((r=t.operation)==="=="||r==="!="||r==="<"||r===">"||r==="<="||r===">="){if(t.term1 instanceof N&&t.term1.type===N.TYPE_NUMBER&&t.term2 instanceof N&&t.term2.type===N.TYPE_NUMBER){let n=t.term1.value,a=t.term2.value,o;switch(t.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,t);return}switch(this.compile(t.term1),this.compile(t.term2),t.operation){case"==":this.routine.EQ(t);break;case"!=":this.routine.NEQ(t);break;case"<":this.routine.LT(t);break;case">":this.routine.GT(t);break;case"<=":this.routine.LTE(t);break;case">=":this.routine.GTE(t)}}else t.operation==="and"?(s=this.routine.createLabel("and"),t.term1.nowarning=!0,t.term2.nowarning=!0,this.compile(t.term1),this.routine.JUMPN_NOPOP(s,t),this.routine.POP(t),this.compile(t.term2),this.routine.setLabel(s)):t.operation==="or"?(s=this.routine.createLabel("or"),t.term1.nowarning=!0,t.term2.nowarning=!0,this.compile(t.term1),this.routine.JUMPY_NOPOP(s,t),this.routine.POP(t),this.compile(t.term2),this.routine.setLabel(s)):t.operation==="^"&&(this.compile(t.term1),this.compile(t.term2),this.routine.BINARY_OP(ht.predefined_binary_functions.pow,t))}compileBraced(t){this.compile(t.expression)}compileNegate(t){t.expression instanceof N&&t.expression.type===N.TYPE_NUMBER?this.routine.LOAD_VALUE(-t.expression.value,t):(this.compile(t.expression),this.routine.NEGATE(t))}compileNot(t){if(t.expression instanceof N&&t.expression.type===N.TYPE_NUMBER){this.routine.LOAD_VALUE(t.expression.value?0:1,t);return}t.expression.nowarning=!0,this.compile(t.expression),this.routine.NOT(t)}compileValue(t){let s,i,r;switch(t.type){case N.TYPE_NUMBER:this.routine.LOAD_VALUE(t.value,t);break;case N.TYPE_STRING:this.routine.LOAD_VALUE(t.value,t);break;case N.TYPE_ARRAY:for(this.routine.CREATE_ARRAY(t),s=i=0,r=t.value.length-1;i<=r;s=i+=1)this.routine.LOAD_VALUE(s,t),this.compile(t.value[s]),this.routine.CREATE_PROPERTY(t)}}compileVariable(t){let s,i;i=t.identifier,i==="this"?this.routine.LOAD_THIS(t):i==="global"?this.routine.LOAD_GLOBAL(t):ht.predefined_values[i]!=null?this.routine.LOAD_VALUE(ht.predefined_values[i],t):this.locals.get(i)!=null?(s=this.locals.get(i),this.routine.LOAD_LOCAL(s,t)):this.routine.LOAD_VARIABLE(i,t)}compileField(t){var s,i,r,n,a,o,u,_,E;if((t.expression.identifier==="keyboard"||t.expression.identifier==="gamepad")&&(t.nowarning=!0),s=t.chain[t.chain.length-1],s instanceof N&&s.value==="type")if(t.chain.length===1)t.expression instanceof K?(r=t.expression.identifier,this.locals.get(r)!=null?(n=this.locals.get(r),this.routine.LOAD_LOCAL(n,t),this.routine.TYPE(t)):ht.predefined_values[r]!=null?this.routine.LOAD_VALUE("number",t):ht.predefined_unary_functions[r]!=null||ht.predefined_binary_functions[r]?this.routine.LOAD_VALUE("function",t):this.routine.VARIABLE_TYPE(r,t.expression)):(this.compile(t.expression),this.routine.TYPE(t));else{for(this.compile(t.expression),i=a=0,_=t.chain.length-3;a<=_;i=a+=1)this.compile(t.chain[i]),this.routine.LOAD_PROPERTY(t);this.compile(t.chain[t.chain.length-2]),this.routine.PROPERTY_TYPE(t.expression)}else for(this.compile(t.expression),E=t.chain,o=0,u=E.length;o<u;o++)s=E[o],this.compile(s),this.routine.LOAD_PROPERTY(t)}compileFieldParent(t){var s,i,r,n;for(this.compile(t.expression),i=r=0,n=t.chain.length-2;r<=n;i=r+=1)s=t.chain[i],this.compile(s),this.routine.LOAD_PROPERTY(t)}compileFunctionCall(t){var s,i,r,n,a,o,u,_,E,A,b,O,m,M,z,w,S,H,G;if(t.expression instanceof ut){for(z=t.args,r=a=0,_=z.length;a<_;r=++a)s=z[r],this.compile(s);this.compileFieldParent(t.expression),this.compile(t.expression.chain[t.expression.chain.length-1]),this.routine.FUNCTION_APPLY_PROPERTY(t.args.length,t)}else if(t.expression instanceof K)if(ht.predefined_unary_functions[t.expression.identifier]!=null)i=ht.predefined_unary_functions[t.expression.identifier],t.args.length>0?this.compile(t.args[0]):this.routine.LOAD_VALUE(0,t),this.routine.UNARY_OP(i,t);else if(ht.predefined_binary_functions[t.expression.identifier]!=null)i=ht.predefined_binary_functions[t.expression.identifier],t.args.length>0?this.compile(t.args[0]):this.routine.LOAD_VALUE(0,t),t.args.length>1?this.compile(t.args[1]):this.routine.LOAD_VALUE(0,t),this.routine.BINARY_OP(i,t);else if(t.expression.identifier==="super"){for(w=t.args,r=o=0,E=w.length;o<E;r=++o)s=w[r],this.compile(s);this.routine.SUPER_CALL(t.args.length,t)}else if(this.locals.get(t.expression.identifier)!=null){for(S=t.args,r=u=0,A=S.length;u<A;r=++u)s=S[r],this.compile(s);n=this.locals.get(t.expression.identifier),this.routine.LOAD_LOCAL(n,t),this.routine.FUNCTION_CALL(t.args.length,t)}else{for(H=t.args,r=m=0,b=H.length;m<b;r=++m)s=H[r],this.compile(s);this.routine.LOAD_VALUE(t.expression.identifier,t),this.routine.FUNCTION_APPLY_VARIABLE(t.args.length,t)}else{for(G=t.args,M=0,O=G.length;M<O;M++)s=G[M],this.compile(s);this.compile(t.expression),this.routine.FUNCTION_CALL(t.args.length,t)}}compileFor(t){if(t.range_from instanceof N&&t.range_from.type===N.TYPE_NUMBER&&t.range_to instanceof N&&t.range_to.type===N.TYPE_NUMBER&&(t.range_by==null||t.range_by instanceof N&&t.range_by.type===N.TYPE_NUMBER)){let u=t.range_from.value,_=t.range_to.value,E=t.range_by instanceof N?t.range_by.value:1,A=0;if(E>0&&_>=u?A=Math.floor((_-u)/E)+1:E<0&&_<=u&&(A=Math.floor((u-_)/Math.abs(E))+1),A>0&&A<=5){let b=this.locals.register(t.iterator);this.locals.push();for(let O=0;O<A;O++){let m=u+O*E;this.routine.LOAD_VALUE(m,t),this.routine.STORE_LOCAL(b,t),this.routine.POP(t),this.compileSequence(t.sequence)}this.locals.pop();return}}var s,i,r,n,a,o;n=this.locals.register(t.iterator),this.locals.allocate(),this.locals.allocate(),this.compile(t.range_from),this.routine.STORE_LOCAL(n,t),this.routine.POP(t),this.compile(t.range_to),t.range_by!=null?this.compile(t.range_by):this.routine.LOAD_VALUE(0,t),r=this.routine.createLabel("for_start"),s=this.routine.createLabel("for_continue"),i=this.routine.createLabel("for_end"),this.routine.FORLOOP_INIT([n,i],t),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(t.sequence),this.break_label=a,this.continue_label=o,this.routine.setLabel(s),this.routine.FORLOOP_CONTROL([n,r],t),this.routine.setLabel(i),this.locals.pop()}compileForIn(t){var s,i,r,n,a,o;n=this.locals.register(t.iterator),this.locals.allocate(),this.locals.allocate(),this.compile(t.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],t),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(t.sequence),this.break_label=a,this.continue_label=o,this.routine.setLabel(s),this.routine.FORIN_CONTROL([n,r],t),this.routine.setLabel(i),this.locals.pop()}compileSequence(t){var s,i,r;for(s=i=0,r=t.length-1;i<=r&&(t[s].nopop||this.routine.POP(t[s]),this.compile(t[s]),!(t[s]instanceof ee||t[s]instanceof ge||t[s]instanceof Ee));s=i+=1);}compileWhile(t){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,t),this.routine.setLabel(n),this.compile(t.condition),this.routine.JUMPN(s),i=this.break_label,r=this.continue_label,this.break_label=s,this.continue_label=n,this.compileSequence(t.sequence),this.routine.JUMP(n,t),this.break_label=i,this.continue_label=r,this.routine.setLabel(s),this.locals.pop()}compileBreak(t){this.break_label!=null&&this.routine.JUMP(this.break_label,t)}compileContinue(t){this.continue_label!=null&&this.routine.JUMP(this.continue_label,t)}compileFunction(t){var s;s=this.compileFunctionBody(t),this.routine.LOAD_ROUTINE(s,t)}compileFunctionBody(t){let s="args"in t&&t.args!=null;var i,r,n,a,o,u,_,E,A,b,O,m,M,z,w,S,H;if(H=this.routine,b=this.locals,this.routine=new W(s?t.args.length:0),this.locals=new Ni(this,b),this.routine.uses_arguments=!0,s){let G=t.args;for(this.routine.uses_arguments&&(r=this.locals.register("arguments"),this.routine.STORE_LOCAL(r,t),this.routine.POP(t)),m=this.locals.register("+numargs"),this.routine.STORE_LOCAL(m,t),this.routine.POP(t),n=o=z=G.length-1;o>=0;n=o+=-1)i=G[n],a=this.locals.register(i.name),this.routine.STORE_LOCAL(a,t),this.routine.POP(t);for(n=u=0,z=G.length-1;u<=z;n=u+=1)i=G[n],i.default!=null&&(a=this.locals.get(i.name),E=this.routine.createLabel("default_arg"),this.routine.LOAD_VALUE(n,t),this.routine.LOAD_LOCAL(m,t),this.routine.LT(t),this.routine.JUMPY(E,t),this.compile(i.default),this.routine.STORE_LOCAL(a,t),this.routine.POP(t),this.routine.setLabel(E))}if(t.sequence.length>0)for(n=_=0,w=t.sequence.length-1;_<=w;n=_+=1)this.compile(t.sequence[n]),n<t.sequence.length-1?this.routine.POP(t.sequence[n]):this.routine.RETURN(t.sequence[n]);else this.routine.LOAD_VALUE(0,t),this.routine.RETURN(t);for(s&&!this.locals.arguments_used&&(this.routine.uses_arguments=!1,this.routine.remove(0),this.routine.remove(0)),a=0,S=this.locals.imports,O=0,A=S.length;O<A;O++){let G=S[O];this.routine.OP_INSERT(g.LOAD_IMPORT,t,a,a*3),this.routine.OP_INSERT(g.STORE_LOCAL,t,G.index,a*3+1),this.routine.OP_INSERT(g.POP,t,0,a*3+2),this.routine.import_refs.push(G.source),a+=1}return this.routine.optimize(),this.routine.resolveLabels(),this.routine.source=t.source,this.count+=this.routine.opcodes.length,M=this.routine,this.routine.locals_size=this.locals.max_index,this.routine=H,this.locals=b,M}compileReturn(t){t.expression!=null?(this.compile(t.expression),this.routine.RETURN(t)):(this.routine.LOAD_VALUE(0,t),this.routine.RETURN(t))}compileCondition(t){var s,i,r,n,a,o,u;for(i=t.chain,this.routine.LOAD_VALUE(0,t),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,t),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(t){return t==="constructor"&&(t="_constructor"),String(t).replace(/"/g,'\\"')}compileCreateObject(t){let s,i,r,n;for(this.routine.CREATE_OBJECT(t),n=t.fields,i=0,r=n.length;i<r;i++)s=n[i],this.routine.LOAD_VALUE(s.field,t),this.compile(s.value),this.routine.CREATE_PROPERTY(t)}compileCreateClass(t){let s,i,r,n,a;for(t.ext!=null?(t.ext.nowarning=!0,this.compile(t.ext)):this.routine.LOAD_VALUE(0,t),a=t.ext!=null&&t.ext instanceof K?t.ext.identifier:0,this.routine.CREATE_CLASS(a,t),n=t.fields,i=0,r=n.length;i<r;i++)s=n[i],this.routine.LOAD_VALUE(s.field,t),this.compile(s.value),this.routine.CREATE_PROPERTY(t)}compileUpdateClass(t,s){this.compileCreateClass(t),this.routine.UPDATE_CLASS(s,t)}compileNewCall(t){let s,i,r,n,a,o;for(i=t.expression,this.routine.LOAD_VALUE(0,t),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,t),this.routine.POP(t)}compileAfter(t){let s;s=this.compileFunctionBody(t),this.routine.LOAD_ROUTINE(s,t),this.compile(t.delay),t.multiplier!=null&&t.multiplier!==1&&(this.routine.LOAD_VALUE(t.multiplier,t),this.routine.MUL(t)),this.routine.AFTER(t)}compileEvery(t){let s;s=this.compileFunctionBody(t),this.routine.LOAD_ROUTINE(s,t),this.compile(t.delay),t.multiplier!=null&&t.multiplier!==1&&(this.routine.LOAD_VALUE(t.multiplier,t),this.routine.MUL(t)),this.routine.EVERY(t)}compileDo(t){let s;s=this.compileFunctionBody(t),this.routine.LOAD_ROUTINE(s,t),this.routine.DO(t)}compileSleep(t){this.compile(t.delay),t.multiplier!=null&&t.multiplier!==1&&(this.routine.LOAD_VALUE(t.multiplier,t),this.routine.MUL(t)),this.routine.SLEEP(t)}compileDelete(t){let s,i,r,n;if(t.field instanceof K)this.routine.LOAD_THIS(t),this.routine.LOAD_VALUE(t.field.identifier,t),this.routine.DELETE(t);else if(t.field instanceof ut){for(this.compile(t.field.expression),s=t.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(t);this.routine.DELETE(t)}else throw"Delete expects variable or field access"}exec(t){if(this.processor||(this.processor=new ar(null)),!this.routine)throw new Error("No routine to execute");return this.processor.load(this.routine),this.processor.run(t)}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:y(t=>Math.sin(t*Math.PI/180),"sind"),cosd:y(t=>Math.cos(t*Math.PI/180),"cosd"),tand:y(t=>Math.tan(t*Math.PI/180),"tand"),asind:y(t=>Math.asin(t)/Math.PI*180,"asind"),acosd:y(t=>Math.acos(t)/Math.PI*180,"acosd"),atand:y(t=>Math.atan(t)/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:y((t,s)=>Math.atan2(t,s)/Math.PI*180,"atan2d")};static predefined_values={PI:Math.PI,true:1,false:0}},Ni=class{static{l(this,"Locals")}static{y(this,"Locals")}compiler;parent;layers;index;max_index;imports;arguments_used;constructor(e,t=null){this.compiler=e,this.parent=t,this.layers=[],this.index=0,this.max_index=0,this.imports=[],this.push()}increment(){let e=this.index++;return this.max_index=Math.max(this.index,this.max_index),e}push(){return this.layers.push(new En(this))}pop(){return this.layers.splice(this.layers.length-1,1)}register(e){return this.layers[this.layers.length-1].register(e)}allocate(){return this.layers[this.layers.length-1].allocate()}get(e){let t,s,i,r;for(e==="arguments"&&(this.arguments_used=!0),t=i=this.layers.length-1;i>=0;t=i-=1)if(r=this.layers[t].get(e),r!=null)return r;return this.parent!=null&&(r=this.parent.get(e),r!=null)?(s=this.register(e),this.imports.push({name:e,index:s,source:r}),s):null}},En=class{static{l(this,"LocalLayer")}static{y(this,"LocalLayer")}locals;start_index;registered;constructor(e){this.locals=e,this.start_index=this.locals.index,this.registered={}}register(e){return this.registered[e]=this.locals.increment()}allocate(){return this.locals.increment()}get(e){return this.registered[e]!=null?this.registered[e]:null}},bn=100,Mi=class{static{l(this,"VMProfiler")}static{y(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(e){this.processor=e}start(){this.startTime=performance.now(),this.startOps=this.processor.metrics?.ops||0,this.startAllocations=this.processor.metrics?.allocations||0,this.frameCount=0}stop(){let t=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/t*1e3,o=t/(this.frameCount||1),u={ops:r,time:t,allocations:n,frames:this.frameCount,samples:this.sampleCount+1,opsPerSec:a,avgFrameTime:o};return this.sampleCount<bn&&(this.totalOps+=r,this.totalTime+=t,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}},Fi=class{static{l(this,"Thread")}static{y(this,"Thread")}runner;loop;processor;paused;terminated;next_calls;interface;routine;start_time;delay;repeat;sleep_until;constructor(e){this.runner=e,this.loop=!1,this.processor=new ar(this.runner),this.paused=!1,this.terminated=!1,this.next_calls=[],this.interface={pause:y(()=>this.pause(),"pause"),resume:y(()=>this.resume(),"resume"),stop:y(()=>this.stop(),"stop"),status:"running"}}addCall(e){this.next_calls.indexOf(e)<0&&this.next_calls.push(e)}loadNext(){let e,t,s,i;return this.next_calls.length>0?(t=this.next_calls.splice(0,1)[0],t instanceof W?this.processor.load(t):(s=new Ki(t,""),s.parse(),i=s.program,e=new or(i),this.processor.load(e.routine),(t==="update()"||t==="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}},hr=class{static{l(this,"Runner")}static{y(this,"Runner")}l8bvm;initialized;system;main_thread;threads;current_thread;thread_index;fps;fps_max;cpu_load;triggers_controls_update;updateControls;onNativeError;profiler;constructor(e){this.l8bvm=e,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 Mi(null)}reportNativeError(e){this.onNativeError?this.onNativeError(e):console.error(e)}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 Fi(this),this.threads=[this.main_thread],this.current_thread=this.main_thread,this.thread_index=0,this.profiler=new Mi(this.main_thread.processor),this.system.profiler={start:y(()=>{this.main_thread.processor.profilingEnabled=!0,this.profiler.start()},"start"),stop:y(()=>(this.main_thread.processor.profilingEnabled=!1,this.profiler.stop()),"stop"),getMetrics:y(()=>this.profiler.getAverageMetrics(),"getMetrics")},this.l8bvm.context.global.print=this.l8bvm.context.meta.print,this.l8bvm.context.global.random=new Vt(0),this.l8bvm.context.global.Function={bind:y(function(e){let t;return this instanceof W?(t=this.clone(),t.object=e,t):this},"bind")},this.l8bvm.context.global.Math=Ci,this.l8bvm.context.global.JSON=Ri,this.l8bvm.context.global.List=wi,this.l8bvm.context.global.Function={bind:y((...e)=>e[0].bind.apply(e[0],e.slice(1)),"bind")},this.l8bvm.context.global.String={...Ii,fromCharCode:y(function(){return String.fromCharCode.apply(null,arguments)},"fromCharCode")},this.l8bvm.context.global.Number={parse:y(e=>{let t=Number.parseFloat(e);return isFinite(t)?t:0},"parse"),toString:y(function(){return this.toString()},"toString")},this.l8bvm.context.global.Object={"+":y((e,t)=>e!=null?e+t:t,"+"),"-":y((e,t)=>e-t,"-"),"*":y((e,t)=>e*t,"*"),"/":y((e,t)=>e/t,"/"),"%":y((e,t)=>e%t,"%")},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(e,t="",s){let i,r,n,a,o,u,_,E,A=null,b;if(this.initialized||this.init(),u=new Ki(e,t),u.parse(),u.error_info!=null)throw r=u.error_info,r.type="compile",r;if(u.warnings.length>0)for(E=u.warnings,a=0,o=E.length;a<o;a++)switch(b=E[a],n=t+"-"+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:t,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:t,line:b.line,column:b.column})}return _=u.program,i=new or(_),A=null,i.routine.callback=O=>s!=null?s(gt.toString(O)):A=O,this.main_thread.addCall(i.routine),this.tick(),A}call(e,t){let s,i;if(e==="draw"||e==="update"||e==="serverUpdate"){this.l8bvm.context.global[e]!=null&&this.main_thread.addCall(`${e}()`);return}if(this.l8bvm.context.global[e]!=null)if(t==null||!t.length)this.main_thread.addCall(`${e}()`);else{if(i=this.l8bvm.context.global[e],i instanceof W)return s=this.main_thread.processor.routineAsFunction(i,this.l8bvm.context),s(...t);if(typeof i=="function")return i(...t)}else return 0}toString(e){return gt.toString(e)}getFunctionSource(e){let t=this.l8bvm.context.global[e];if(t instanceof W)return t.source}process(e,t){let s;return s=e.processor,s.time_limit=t,this.current_thread=e,s.run(this.l8bvm.context)}tick(){let e,t,s,i,r,n,a,o,u,_,E,A,b,O;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),A=performance.now(),b=A+100,O=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,O)):this.process(this.main_thread,O));u.done&&performance.now()<O&&this.main_thread.loadNext();)this.process(this.main_thread,O);for(b=A+a,O=this.system.preemptive?b:1/0,this.main_thread.processor.profilingEnabled&&this.profiler.frame(),o=!0;o;){for(o=!1,_=this.threads,i=0,r=_.length;i<r;i++)if(E=_[i],E!==this.main_thread){if(E.paused||E.terminated)continue;if(u=E.processor,!u.done)E.sleep_until!=null?performance.now()>=E.sleep_until&&(delete E.sleep_until,this.process(E,O),o=!0):(this.process(E,O),o=!0);else if(E.start_time!=null)if(E.repeat)for(;A>=E.start_time&&!(E.paused||E.terminated);)A>=E.start_time+150?E.start_time=A+(E.delay||0):E.start_time+=E.delay||0,u.load(E.routine),this.process(E,O),o=!0;else A>=E.start_time&&(delete E.start_time,u.load(E.routine),this.process(E,O),o=!0);else E.terminated=!0}if(performance.now()>b)break}let m=1;for(t=1;t<this.threads.length;t++)if(E=this.threads[t],E.terminated){if(s=this.system.threads.indexOf(E.interface),s>=0){let z=this.system.threads.length-1;s!==z&&(this.system.threads[s]=this.system.threads[z]),this.system.threads.length--}}else this.threads[m++]=this.threads[t];this.threads.length=m,E=this.threads[0],e=performance.now()-A;let M=b-A;n=e/M*100,this.cpu_load=this.cpu_load*.9+n*.1,this.system.cpu_load=Math.min(100,Math.round(this.cpu_load))}createThread(e,t,s){let i,r;for(r=new Fi(this),r.routine=e,this.threads.push(r),r.start_time=performance.now()+t-1e3/this.fps,s&&(r.repeat=s,r.delay=t),this.system.threads.push(r.interface),i=0;i<e.import_values.length;i++)e.import_values[i]===e&&(e.import_values[i]=r.interface);return r.interface}sleep(e){this.current_thread!=null&&(this.current_thread.sleep_until=performance.now()+Math.max(0,e))}};function lr(){let e=globalThis;return e.process?.env?.NODE_ENV==="development"||e.Bun?.env?.NODE_ENV==="development"}l(lr,"isDevelopmentMode");y(lr,"isDevelopmentMode");var Tn=class{static{l(this,"Stack2")}static{y(this,"Stack")}stack;index;touched;constructor(){this.stack=["stack[stack_index]"],this.index=0,this.touched={}}push(t){return this.stack[++this.index]=t,this.touched[this.index]=!0}pop(){let t;return this.index>=0?t=this.stack.splice(this.index,1)[0]:this.stack[this.index]!=null?t=this.stack[this.index]:t="stack[stack_index-"+this.index+"]",this.index-=1,t}get(t=0){let s;return t==null&&(t=0),s=this.index+t,s>=0?this.stack[s]:this.stack[s]!=null?this.stack[s]:"stack[stack_index-"+-s+"]"}},Ma=class{static{l(this,"Transpiler2")}static{y(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(e){for(let t=0;t<e.opcodes.length;t++){let s=g[e.opcodes[t]];if(this.transpilable(s,e.arg1[t])){let i=t+1;for(;i<e.opcodes.length&&e.removeable(i)&&this.transpilable(g[e.opcodes[i]],e.arg1[i]);)i+=1;i-=1,i-t>=2&&this.transpileSegment(e,t,i)}}}transpileSegment(e,t,s){let i,r,n,a,o;for(this.vcount=0,this.stack=new Tn,this.locals={},this.variables={},o="",a=t;a<=s;a++){let u=g[e.opcodes[a]],_=this.opcodeHandlers[u];_?i=_(e.arg1[a]):i=void 0,i&&(o+=i+`
160
148
  `)}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
149
  `:u>0?o+="stack[stack_index+"+n+"] = "+this.stack.stack[u]+` ;
162
150
  `:o+="stack[stack_index] = "+this.stack.stack[u]+` ;
163
151
  `}this.stack.index<0?o+="stack_index -= "+Math.abs(this.stack.index)+` ;
164
152
  `:this.stack.index>0&&(o+="stack_index += "+this.stack.index+` ;
165
153
  `),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&&lt(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);})();
154
+ `,lr()&&console.info(`Transpiled body:
155
+ `+o);try{let u=new Function("stack","stack_index","locals","locals_offset","object","global",o);e.opcodes[t]=g.COMPILED,e.arg1[t]=u}catch(u){r=u,console.error("Transpilation failed:"),console.error(o),console.error(r)}for(a=t+1;a<=s;a++)e.remove(t+1)}createVariable(){return"v"+this.vcount++}transpilable(e,t){return e==="LOAD_VALUE"?typeof t=="string"||typeof t=="number":this.opcodeHandlers[e]!=null}LOAD_VALUE(e){return typeof e=="string"?this.stack.push(' "'+e.replace(/"/g,'\\"')+'" '):typeof e=="number"&&this.stack.push(e+""),""}LOAD_LOCAL(e){let t=this.createVariable();return this.stack.push(t),"let "+t+" = locals[locals_offset+"+e+"] ; // LOAD_LOCAL"}LOAD_LOCAL_OBJECT(e){let t,s;return this.locals[e]!=null?(s=this.locals[e],this.stack.push(s),"if (typeof "+s+' != "object") { '+s+" = locals[locals_offset+"+e+"] = {} } ;"):(s=this.createVariable(),t="let "+s+" = locals[locals_offset+"+e+`] ;
156
+ if (typeof `+s+' != "object") { '+s+" = locals[locals_offset+"+e+"] = {} } ;",this.stack.push(s),this.locals[e]=s,t)}STORE_LOCAL(e){let t=this.stack.get();return"locals[locals_offset+"+e+"] = "+t+" ; // STORE_LOCAL"}POP(){return this.stack.pop(),""}CREATE_PROPERTY(e){let t=this.stack.get(-2)+"["+this.stack.get(-1)+"] = "+this.stack.get()+" ;";return this.stack.pop(),this.stack.pop(),t}LOAD_PROPERTY(e){let t,s;return s=this.createVariable(),t="let "+s+" = "+this.stack.get(-1)+"["+this.stack.get()+`] ; // LOAD_PROPERTY
157
+ if (`+s+" == null) { "+s+" = 0 ; }",this.stack.pop(),this.stack.pop(),this.stack.push(s),t}LOAD_PROPERTY_ATOP(e){let t,s;return s=this.createVariable(),t="let "+s+" = "+this.stack.get(-1)+"["+this.stack.get()+`] ; // LOAD_PROPERTY_ATOP
158
+ if (`+s+" == null) { "+s+" = 0 ; }",this.stack.push(s),t}NEW_OBJECT(){let e=this.createVariable();return this.stack.push(e),"let "+e+" = {} ;"}NEW_ARRAY(){let e=this.createVariable();return this.stack.push(e),"let "+e+" = [] ;"}MAKE_OBJECT(){let e,t;return t=this.createVariable(),e="let "+t+" = "+this.stack.get()+` ;
159
+ if (typeof `+t+' != "object") '+t+" = {} ; ",this.stack.pop(),this.stack.push(t),e}STORE_VARIABLE(e){return this.variables[e]!=null?this.variables[e]+' = object["'+e+'"] = '+this.stack.get()+" ; // STORE_VARIABLE":'object["'+e+'"] = '+this.stack.get()+" ; // STORE_VARIABLE"}STORE_PROPERTY(e){let t,s;return s=this.createVariable(),t="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),t}};var yn=Object.defineProperty,Le=l((e,t)=>yn(e,"name",{value:t,configurable:!0}),"__name"),xe=class{static{l(this,"StorageService")}static{Le(this,"StorageService")}namespace;cache=new Map;pendingWrites=new Map;writeTimer=null;runtime;constructor(e="/l8b",t=!1,s){this.namespace=e,this.runtime=s,!t&&typeof localStorage<"u"&&this.clear()}get(e){if(!e||typeof e!="string"||e.trim()==="")return this.runtime?.listener?.reportError?.({code:"E7063",message:`Invalid storage key: ${e}`}),null;if(this.cache.has(e))return this.cache.get(e);if(typeof localStorage<"u")try{let t=`${this.namespace}.${e}`,s=localStorage.getItem(t);if(s!==null){let i=JSON.parse(s);return this.cache.set(e,i),i}}catch(t){this.runtime?.listener?.reportError?.({code:"E7062",message:`Get operation failed: ${String(t)}`})}return null}set(e,t){if(!e||typeof e!="string"||e.trim()===""){this.runtime?.listener?.reportError?.({code:"E7063",message:`Invalid storage key: ${e}`});return}if(this.cache.set(e,t),this.pendingWrites.set(e,t),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[e,t]of this.pendingWrites)try{let s=`${this.namespace}.${e}`,i=JSON.stringify(this.sanitize(t));localStorage.setItem(s,i)}catch(s){s.name==="QuotaExceededError"||s.code===22?this.runtime?.listener?.reportError?.({code:"E7061",message:"Storage quota exceeded"}):this.runtime?.listener?.reportError?.({code:"E7062",message:`Set operation failed: ${String(s)}`})}this.pendingWrites.clear()}check(){this.pendingWrites.size>0&&this.flush()}delete(e){if(!e||typeof e!="string"||e.trim()===""){this.runtime?.listener?.reportError?.({code:"E7063",message:`Invalid storage key: ${e}`});return}if(this.cache.delete(e),this.pendingWrites.delete(e),typeof localStorage<"u")try{localStorage.removeItem(`${this.namespace}.${e}`)}catch(t){this.runtime?.listener?.reportError?.({code:"E7062",message:`Delete operation failed: ${String(t)}`})}}clear(){if(typeof localStorage>"u")return;let e=`${this.namespace}.`,t=[];for(let s=0;s<localStorage.length;s++){let i=localStorage.key(s);i&&i.startsWith(e)&&t.push(i)}for(let s of t)localStorage.removeItem(s);this.cache.clear(),this.pendingWrites.clear()}sanitize(e,t=new WeakSet){if(e==null)return e;if(typeof e!="object")return typeof e=="function"?void 0:e;if(t.has(e))return;if(t.add(e),Array.isArray(e))return e.map(i=>this.sanitize(i,t)).filter(i=>i!==void 0);let s={};for(let i in e)if(Object.hasOwn(e,i)){let r=this.sanitize(e[i],t);r!==void 0&&(s[i]=r)}return s}interfaceCache=null;getInterface(){return this.interfaceCache?this.interfaceCache:(this.interfaceCache={set:Le((e,t)=>this.set(e,t),"set"),get:Le(e=>this.get(e),"get"),delete:Le(e=>this.delete(e),"delete")},this.interfaceCache)}};var On=Object.defineProperty,B=l((e,t)=>On(e,"name",{value:t,configurable:!0}),"__name"),cr={round:B(e=>Math.round(e),"round"),floor:B(e=>Math.floor(e),"floor"),ceil:B(e=>Math.ceil(e),"ceil"),abs:B(e=>Math.abs(e),"abs"),min:B((e,t)=>Math.min(e,t),"min"),max:B((e,t)=>Math.max(e,t),"max"),sqrt:B(e=>Math.sqrt(e),"sqrt"),pow:B((e,t)=>e**t,"pow"),sin:B(e=>Math.sin(e),"sin"),cos:B(e=>Math.cos(e),"cos"),tan:B(e=>Math.tan(e),"tan"),asin:B(e=>Math.asin(e),"asin"),acos:B(e=>Math.acos(e),"acos"),atan:B(e=>Math.atan(e),"atan"),atan2:B((e,t)=>Math.atan2(e,t),"atan2"),sind:B(e=>Math.sin(e/180*Math.PI),"sind"),cosd:B(e=>Math.cos(e/180*Math.PI),"cosd"),tand:B(e=>Math.tan(e/180*Math.PI),"tand"),asind:B(e=>Math.asin(e)*180/Math.PI,"asind"),acosd:B(e=>Math.acos(e)*180/Math.PI,"acosd"),atand:B(e=>Math.atan(e)*180/Math.PI,"atand"),atan2d:B((e,t)=>Math.atan2(e,t)*180/Math.PI,"atan2d"),log:B(e=>Math.log(e),"log"),exp:B(e=>Math.exp(e),"exp"),random:new Vt(0),PI:Math.PI,true:1,false:0},ur=B(e=>console.log(e),"_defaultPrint");function Fs(e){return{...cr,print:e??ur}}l(Fs,"createMetaFunctions");B(Fs,"createMetaFunctions");function Se(e,t){return{meta:{...cr,print:e.print??ur,...e},global:t,local:t,object:t,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(Se,"createVMContext");B(Se,"createVMContext");function ke(){Array.prototype.insert||(Array.prototype.insert=function(e){return this.splice(0,0,e),e}),Array.prototype.insertAt||(Array.prototype.insertAt=function(e,t){return t>=0&&t<this.length?this.splice(t,0,e):this.push(e),e}),Array.prototype.remove||(Array.prototype.remove=function(e){return e>=0&&e<this.length?this.splice(e,1)[0]:0}),Array.prototype.removeElement||(Array.prototype.removeElement=function(e){let t=this.indexOf(e);return t>=0?this.splice(t,1)[0]:0}),Array.prototype.contains||(Array.prototype.contains=function(e){return this.indexOf(e)>=0?1:0}),Array.prototype.sortList||(Array.prototype.sortList=function(e){return e?this.sort(e):this.sort()})}l(ke,"setupArrayExtensions");B(ke,"setupArrayExtensions");function ve(e,t,s,i){let r=typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="string"?e.error:e?.message??String(e),n=e?.stackTrace;return!n&&i?.main_thread?.processor?.generateStackTrace&&(n=i.main_thread.processor.generateStackTrace()),{error:r,type:e?.type??s,line:e?.line,column:e?.column,file:e?.file??t,stack:e?.stack,stackTrace:n}}l(ve,"extractErrorInfo");B(ve,"extractErrorInfo");var Re=class{static{l(this,"L8BVM")}static{B(this,"L8BVM")}context;runner;storage_service;error_info=null;constructor(e={},t={},s="/l8b",i=!1){this.context=Se(e,t),this.storage_service=new xe(s,i),this.context.global.storage=this.storage_service.getInterface(),this.runner=new hr(this),this.runner.init(),ke()}run(e,t=3e3,s=""){this.error_info=null,this.context.timeout=Date.now()+t,this.context.stack_size=0;try{let i=this.runner.run(e,s);return this.storage_service.check(),i!=null?this.runner.toString(i):null}catch(i){throw this.error_info=ve(i,s,"runtime",this.runner),i}}call(e,t=[],s=3e3){this.error_info=null,this.context.timeout=Date.now()+s,this.context.stack_size=0;try{let i=this.runner.call(e,...t);return this.storage_service.check(),i}catch(i){throw this.error_info=ve(i,e,"call",this.runner),i}}loadRoutine(e,t=""){this.error_info=null;try{let s;e instanceof W?s=e:s=new W(0).import(fr(e)),this.runner.main_thread.addCall(s),this.runner.tick()}catch(s){throw this.error_info=ve(s,t,"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(e){return this.runner.toString(e)}};function fr(e){return pr(e)?e.routine:e}l(fr,"normalizeSerializedRoutine");B(fr,"normalizeSerializedRoutine");function pr(e){return typeof e=="object"&&e!==null&&"format"in e&&e.format==="l8b-compiled-routine"&&"routine"in e}l(pr,"isCompiledModuleArtifact");B(pr,"isCompiledModuleArtifact");var zt=class{static{l(this,"SourceUpdater")}vm;listener;audio;screen;reportWarnings;emitBridgeEvent;updateMemory={};previousInit=null;constructor(t,s,i,r,n,a){this.vm=t,this.listener=s,this.audio=i,this.screen=r,this.reportWarnings=n,this.emitBridgeEvent=a}updateSource(t,s,i=!1){if(!this.vm||s===this.updateMemory[t])return!1;this.updateMemory[t]=s,this.audio&&this.audio.cancelBeeps(),this.screen&&this.screen.clear();try{if(this.vm.run(s,3e3,t),this.emitBridgeEvent&&this.emitBridgeEvent("compile_success",{file:t}),this.reportWarnings&&this.reportWarnings(),this.vm.error_info){let r=Object.assign({},this.vm.error_info);return r.type="init",r.file=t,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=t,this.listener.reportError?.(r),!1}}};var An=Object.defineProperty,it=l((e,t)=>An(e,"name",{value:t,configurable:!0}),"__name"),Ys=it(()=>({press:{},release:{}}),"createState"),dr={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"},mr={6:"LT",7:"RT"},_r=it(e=>e?(e.press??={},e.release??={},e):Ys(),"ensureState"),Us=class{static{l(this,"GamepadInput")}static{it(this,"GamepadInput")}status;previous;count=0;constructor(){this.status=Ys(),this.previous={global:Ys()}}update(){let e=this.getGamepads();if(!e){this.count=0;return}let t=0;for(let s=0;s<e.length;s++){let i=e[s];if(!i)break;t++,this.status[s]=_r(this.status[s]),this.previous[s]=_r(this.previous[s]);for(let[r,n]of Object.entries(dr)){let a=Number(r),o=i.buttons[a];o&&(this.status[s][n]=o.pressed?1:0)}for(let[r,n]of Object.entries(mr)){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(e,t),this.count=t,this.updateChanges(this.status,this.previous.global);for(let s=0;s<t;s++)this.updateChanges(this.status[s],this.previous[s]);for(let s=t;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(e,t,s,i){let r=Math.sqrt(e*e+t*t),n=Math.floor((Math.atan2(t,e)+Math.PI*2)%(Math.PI*2)/(Math.PI*2)*360);s[`${i}_STICK_ANGLE`]=n,s[`${i}_STICK_AMOUNT`]=r,s[`${i}_STICK_UP`]=t>.5?1:0,s[`${i}_STICK_DOWN`]=t<-.5?1:0,s[`${i}_STICK_LEFT`]=e<-.5?1:0,s[`${i}_STICK_RIGHT`]=e>.5?1:0}aggregateStatus(e,t){for(let[s,i]of Object.entries(dr)){this.status[i]=0;let r=Number(s);for(let n of e){if(!n)break;if(n.buttons[r]?.pressed){this.status[i]=1;break}}}for(let[s,i]of Object.entries(mr)){this.status[i]=0;let r=Number(s);for(let n of e){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<t;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(e,t){for(let s in e.press)e.press[s]=0;for(let s in e.release)e.release[s]=0;for(let s in t)s==="press"||s==="release"||t[s]&&!e[s]&&(e.release[s]=1);for(let s in e)s==="press"||s==="release"||e[s]&&!t[s]&&(e.press[s]=1);for(let s in t)s==="press"||s==="release"||(t[s]=0);for(let s in e)s==="press"||s==="release"||(t[s]=e[s])}},gr=200,Er=-1e4,Pn=/Escape|(F\d+)/,br="mouse",Bs=typeof document<"u",re=it((e,t,s)=>{let i=e.getBoundingClientRect(),r=Math.min(e.clientWidth,e.clientHeight)||1,n=(t-i.left-e.clientWidth/2)/r*gr,a=(e.clientHeight/2-(s-i.top))/r*gr;return{x:n,y:a}},"computeRelativePosition"),js=class{static{l(this,"KeyboardInput")}static{it(this,"KeyboardInput")}state={press:{},release:{},UP:0,DOWN:0,LEFT:0,RIGHT:0};previous={};dirtyKeys=new Set;constructor(e=Bs?document:void 0){e&&(e.addEventListener("keydown",t=>this.handleKeyDown(t)),e.addEventListener("keyup",t=>this.handleKeyUp(t)))}convertCode(e){let t="",s=!1;for(let i=0;i<e.length;i++){let r=e.charAt(i);r===r.toUpperCase()&&s?(t+="_",s=!1):s=!0,t+=r.toUpperCase()}return t}handleKeyDown(e){e.altKey||e.ctrlKey||e.metaKey||Pn.test(e.key)||e.preventDefault();let t=this.convertCode(e.code),s=e.key.toUpperCase();this.state[t]=1,this.state[s]=1,this.dirtyKeys.add(t),this.dirtyKeys.add(s),this.updateDirectional()}handleKeyUp(e){let t=this.convertCode(e.code),s=e.key.toUpperCase();this.state[t]=0,this.state[s]=0,this.dirtyKeys.add(t),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 e of this.dirtyKeys)this.state.press[e]&&(this.state.press[e]=0),this.state.release[e]&&(this.state.release[e]=0);for(let e of this.dirtyKeys){let t=this.state[e],s=this.previous[e]||0;t&&!s?this.state.press[e]=1:!t&&s&&(this.state.release[e]=1),this.previous[e]=t}this.dirtyKeys.clear()}reset(){for(let e in this.state)e==="press"||e==="release"||(this.state[e]=0);for(let e in this.previous)this.previous[e]=0;this.dirtyKeys.clear()}},Gs=class{static{l(this,"MouseInput")}static{it(this,"MouseInput")}state={x:Er,y:Er,pressed:0,left:0,middle:0,right:0,press:0,release:0,wheel:0};previousPressed=!1;wheel=0;canvas;removeListeners;constructor(e){e&&this.setCanvas(e)}setCanvas(e){this.detach(),this.canvas=e,this.attach()}syncFromTouch(e,t,s){this.state.x=e,this.state.y=t,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(!Bs)return;let e=document,t=it(a=>this.handleMouseDown(a),"onDown"),s=it(a=>this.handleMouseMove(a),"onMove"),i=it(a=>this.handleMouseUp(a),"onUp"),r=it(a=>this.handleWheel(a),"onWheel"),n=it(a=>this.handleWheel(a),"onDomWheel");e.addEventListener("mousedown",t,{passive:!1}),e.addEventListener("mousemove",s,{passive:!1}),e.addEventListener("mouseup",i,{passive:!1}),e.addEventListener("mousewheel",r,{passive:!1}),e.addEventListener("DOMMouseScroll",n,{passive:!1}),this.removeListeners=()=>{e.removeEventListener("mousedown",t),e.removeEventListener("mousemove",s),e.removeEventListener("mouseup",i),e.removeEventListener("mousewheel",r),e.removeEventListener("DOMMouseScroll",n)}}detach(){this.removeListeners?.(),this.removeListeners=void 0,this.canvas=void 0}handleMouseDown(e){if(!this.canvas)return;e.preventDefault();let{x:t,y:s}=re(this.canvas,e.clientX,e.clientY);switch(this.state.x=t,this.state.y=s,e.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(e){if(!this.canvas)return;e.preventDefault();let{x:t,y:s}=re(this.canvas,e.clientX,e.clientY);this.state.x=t,this.state.y=s}handleMouseUp(e){if(!this.canvas)return;e.preventDefault();let{x:t,y:s}=re(this.canvas,e.clientX,e.clientY);switch(this.state.x=t,this.state.y=s,e.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(e){let t=e;typeof t.deltaY=="number"&&t.deltaY!==0?this.wheel=t.deltaY>0?-1:1:typeof t.wheelDelta=="number"&&t.wheelDelta!==0?this.wheel=t.wheelDelta<0?-1:1:typeof t.detail=="number"&&t.detail!==0?this.wheel=t.detail>0?-1:1:this.wheel=0,e.preventDefault()}},Vs=class{static{l(this,"TouchInput")}static{it(this,"TouchInput")}mouse;state={touching:0,x:0,y:0,press:0,release:0,touches:[]};touches=new Map;previousTouching=!1;canvas;removeListeners;constructor(e,t){this.mouse=e,t&&this.setCanvas(t)}setCanvas(e){this.detach(),this.canvas=e,this.attach()}update(){this.syncMouseTouch();let e=[];for(let[t,{x:s,y:i}]of this.touches.entries())e.push({id:t,x:s,y:i}),this.state.x=s,this.state.y=i;this.state.touches=e,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 e=this.mouse.state;e.pressed?this.touches.set(br,{x:e.x,y:e.y}):this.touches.delete(br)}attach(){if(!Bs)return;let e=it(i=>this.handleTouchStart(i),"onStart"),t=it(i=>this.handleTouchMove(i),"onMove"),s=it(i=>this.handleTouchEnd(i),"onEnd");document.addEventListener("touchstart",e,{passive:!1}),document.addEventListener("touchmove",t,{passive:!1}),document.addEventListener("touchend",s,{passive:!1}),document.addEventListener("touchcancel",s,{passive:!1}),this.removeListeners=()=>{document.removeEventListener("touchstart",e),document.removeEventListener("touchmove",t),document.removeEventListener("touchend",s),document.removeEventListener("touchcancel",s)}}detach(){this.removeListeners?.(),this.removeListeners=void 0,this.canvas=void 0,this.touches.clear()}handleTouchStart(e){if(this.canvas){e.preventDefault(),e.stopPropagation();for(let t=0;t<e.changedTouches.length;t++){let s=e.changedTouches[t],{x:i,y:r}=re(this.canvas,s.clientX,s.clientY);this.touches.set(s.identifier,{x:i,y:r}),this.mouse.syncFromTouch(i,r,!0)}}}handleTouchMove(e){if(this.canvas){e.preventDefault(),e.stopPropagation();for(let t=0;t<e.changedTouches.length;t++){let s=e.changedTouches[t];if(!this.touches.has(s.identifier))continue;let{x:i,y:r}=re(this.canvas,s.clientX,s.clientY);this.touches.set(s.identifier,{x:i,y:r}),this.mouse.syncFromTouch(i,r,!0)}}}handleTouchEnd(e){if(this.canvas){e.preventDefault(),e.stopPropagation();for(let t=0;t<e.changedTouches.length;t++){let s=e.changedTouches[t];this.touches.delete(s.identifier)}this.mouse.syncFromTouch(this.state.x,this.state.y,!1)}}},Fo=class{static{l(this,"Input")}static{it(this,"Input")}keyboard;mouse;touch;gamepad;runtime;constructor(e,t){this.runtime=t,this.keyboard=new js,this.mouse=new Gs(e),this.touch=new Vs(this.mouse,e),this.gamepad=new Us}update(){this.keyboard.update(),this.mouse.update(),this.touch.update(),this.gamepad.update()}getKeyboard(){return!this.keyboard||!this.keyboard.state?(this.runtime?.listener?.reportError?.({code:"E7052",message:"Keyboard state not available",data:{error:"Keyboard state not available"}}),{}):this.keyboard.state}getMouse(){return!this.mouse||!this.mouse.state?(this.runtime?.listener?.reportError?.({code:"E7052",message:"Mouse state not available",data:{error:"Mouse state not available"}}),{}):this.mouse.state}getTouch(){return!this.touch||!this.touch.state?(this.runtime?.listener?.reportError?.({code:"E7052",message:"Touch state not available",data:{error:"Touch state not available"}}),{}):this.touch.state}getGamepad(){return(!this.gamepad||!navigator.getGamepads)&&this.runtime?.listener?.reportError?.({code:"E7051",message:"Gamepad API not available",data:{device:"gamepad"}}),this.gamepad}setCanvas(e){this.mouse.setCanvas(e),this.touch.setCanvas(e)}};var Wt=class{static{l(this,"InputManager")}keyboard;mouse;touch;gamepad;constructor(t){this.keyboard=new js,this.mouse=new Gs,this.touch=new Vs(this.mouse),this.gamepad=new Us,t&&this.attachCanvas(t)}attachCanvas(t){this.mouse.setCanvas(t),this.touch.setCanvas(t)}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 Ht=class{static{l(this,"GameLoop")}callbacks;state;stopped=!1;animationFrameId=null;constructor(t){this.callbacks=t,this.state={currentFrame:0,floatingFrame:0,dt:gi,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 t=performance.now();Math.abs(t-this.state.lastTime)>Ei&&(this.state.lastTime=t-de);let s=t-this.state.lastTime;this.state.dt=this.state.dt*.9+s*.1,this.state.lastTime=t;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(t){t>0&&Number.isFinite(t)&&(this.state.updateRate=t)}getFPS(){return this.state.fps}};var qt=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((t,s)=>{if(typeof window<"u"){let i=window.prompt(t);i!==null&&s&&s(i)}},"prompt"),say:l(t=>{typeof window<"u"&&window.alert(t)},"say"),file:{dropped:0},javascript:{},disable_autofullscreen:0,preemptive:1}}getAPI(){return this.systemAPI}setFPS(t){this.systemAPI.fps=t}setCPULoad(t){this.systemAPI.cpu_load=t}setLoading(t){this.systemAPI.loading=t}};var we=class{static{l(this,"DebugLogger")}lastInputDebug;lastScreenDebug;debugInputs(t,s){if(!s?.input)return;let i=this.createInputSnapshot(t,s.input);i&&(this.lastInputDebug&&xn(i,this.lastInputDebug)||(this.lastInputDebug=i,console.debug("[@al8b/runtime][input]",i)))}debugScreen(t,s){if(!s?.screen)return;let i=t.getCanvas(),r={width:t.width,height:t.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:t.width,height:t.height},canvas:{width:i.width,height:i.height,clientWidth:i.clientWidth,clientHeight:i.clientHeight,style:{width:i.style.width,height:i.style.height}}}))}createInputSnapshot(t,s){let i=Ln(s);if(i.length===0)return null;let r=t.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:t.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 Ln(e){if(typeof e=="boolean")return e?["keyboard","mouse","touch","gamepad"]:[];let t=[];return e.keyboard&&t.push("keyboard"),e.mouse&&t.push("mouse"),e.touch&&t.push("touch"),e.gamepad&&t.push("gamepad"),t}l(Ln,"getEnabledInputChannels");function xn(e,t){if(e===t)return!0;if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let s=Object.keys(e),i=Object.keys(t);if(s.length!==i.length)return!1;for(let r of s){let n=e[r],a=t[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 _ of o)if(n[_]!==a[_])return!1}else return!1}}return!0}l(xn,"shallowEqual");function vn(e){return e.code||e.context||e.suggestions?e:{...e,code:e.code||"E2005",formatted:e.message||String(e)}}l(vn,"formatRuntimeError");function Et(e,t){if(e.reportError){let s=vn(t);e.reportError(s)}}l(Et,"reportError");function Hs(e,t){if(!e)return;let s=e.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,Et(t,{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,Et(t,{error:"",type:"undefined_variable",expression:r.expression,line:r.line,column:r.column,file:r.file}))}}}l(Hs,"reportWarnings");var Ce=class{static{l(this,"RuntimeAssetsRegistry")}collections={sprites:{},maps:{},sounds:{},music:{},assets:{}};replace(t){this.collections=t}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 Sn=Object.defineProperty,kn=l((e,t)=>Sn(e,"name",{value:t,configurable:!0}),"__name"),Tr=/^#[0-9A-Fa-f]{6}$/,yr=class ne{static{l(this,"_Palette")}static{kn(this,"Palette")}colors;name;rgbCache;runtime;constructor(t={},s){this.runtime=s,"colors"in t&&Array.isArray(t.colors)?this.validatePaletteFormat(t.colors)?(this.colors=[...t.colors],this.name=t.name||"Custom"):(this.runtime?.listener?.reportError?.({code:"E7072",message:"Invalid palette format",data:{format:"invalid color array"}}),this.colors=[],this.name="Invalid"):(this.colors=[],this.name="Empty"),this.rgbCache=new Map}validatePaletteFormat(t){return Array.isArray(t)?t.every(s=>typeof s=="string"&&Tr.test(s)):!1}get(t){return!isFinite(t)||t<0?(this.runtime?.listener?.reportError?.({code:"E7073",message:"Invalid color index",data:{index:t,maxIndex:this.colors.length-1}}),"#000000"):this.colors.length===0?"#000000":this.colors[t%this.colors.length]||"#000000"}getRGB(t){if(this.rgbCache.has(t))return this.rgbCache.get(t);let s=this.get(t),i=this.hexToRGB(s);return this.rgbCache.set(t,i),i}getAll(){return[...this.colors]}get size(){return this.colors.length}get paletteName(){return this.name}set(t,s){if(!isFinite(t)||t<0){this.runtime?.listener?.reportError?.({code:"E7073",message:"Invalid color index",data:{index:t,maxIndex:this.colors.length-1}});return}if(!Tr.test(s)){this.runtime?.listener?.reportError?.({code:"E7072",message:"Invalid color format",data:{format:s}});return}for(;this.colors.length<=t;)this.colors.push("#000000");this.colors[t]=s,this.rgbCache.delete(t)}add(t){return this.colors.push(t),this.colors.length-1}remove(t){t>=0&&t<this.colors.length&&(this.colors.splice(t,1),this.rgbCache.clear())}setPalette(t){if(!this.validatePaletteFormat(t)){this.runtime?.listener?.reportError?.({code:"E7072",message:"Invalid palette format",data:{format:"invalid color array"}});return}this.colors=[...t],this.rgbCache.clear()}reset(t){t&&(this.colors=[...t.colors],this.name=t.name),this.rgbCache.clear()}hexToRGB(t){let s=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);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(t,s,i){return"#"+((1<<24)+(t<<16)+(s<<8)+i).toString(16).slice(1).toUpperCase()}findClosest(t){let s=this.hexToRGB(t),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(t,s,i){let r=this.getRGB(t),n=this.getRGB(s),a=[];for(let o=0;o<i;o++){let u=o/(i-1),_=Math.round(r.r+(n.r-r.r)*u),E=Math.round(r.g+(n.g-r.g)*u),A=Math.round(r.b+(n.b-r.b)*u);a.push(ne.rgbToHex(_,E,A))}return a}lighten(t,s=.2){let i=this.getRGB(t),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 ne.rgbToHex(r,n,a)}darken(t,s=.2){let i=this.getRGB(t),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 ne.rgbToHex(r,n,a)}mix(t,s,i=.5){let r=this.getRGB(t),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 ne.rgbToHex(a,o,u)}toData(){return{name:this.name,colors:this.getAll()}}};var ae=class{static{l(this,"ObjectPool")}pool=[];factory;reset;maxSize;constructor(t,s,i=100){this.factory=t,this.reset=s,this.maxSize=i}acquire(){return this.pool.length>0?this.pool.pop():this.factory()}release(t){this.pool.length>=this.maxSize||(this.reset(t),this.pool.push(t))}clear(){this.pool=[]}size(){return this.pool.length}getMaxSize(){return this.maxSize}setMaxSize(t){this.maxSize=t,this.pool.length>t&&(this.pool=this.pool.slice(0,t))}};function Or(e){return{print:l(t=>{let s=e.getVM();(typeof t=="object"||typeof t=="function")&&s&&(t=s.toString(t)),e.listener.log?e.listener.log(String(t)):console.log(t)},"print")}}l(Or,"createRuntimeMeta");function Ar(e){let t=e.input.getStates(),s={user:l(()=>$t(e.getSessionSnapshot()?.user??null),"user"),player:l(()=>$t(e.getSessionSnapshot()?.player??null),"player"),game:l(()=>$t(e.getSessionSnapshot()?.game??null),"game"),room:l(()=>$t(e.getSessionSnapshot()?.room??null),"room")},i={emit:l((n,a)=>{e.sendHostEvent({type:n,payload:a,source:"host"})},"emit"),request:l((n,a,o)=>e.sendHostRequest(n,a,o),"request")},r={export:l(()=>e.exportSnapshot(),"export"),import:l(n=>e.importSnapshot(n),"import"),reset:l(n=>e.resetRuntime(n),"reset"),save:l((n,a)=>e.saveSnapshot(n,a),"save"),load:l((n,a)=>e.loadSnapshot(n,a),"load")};return{screen:e.screen.getInterface(),audio:e.audio.getInterface(),keyboard:t.keyboard,mouse:t.mouse,touch:t.touch,gamepad:t.gamepad,sprites:e.assets.sprites,maps:e.assets.maps,sounds:e.assets.sounds,music:e.assets.music,assets:e.assets.assets,player:e.playerService.getInterface(),host:i,session:s,memory:r,system:e.system.getAPI(),Image:mt,Sprite:jt,TileMap:Ft,Sound:Ot,Palette:yr,Random:Vt,ObjectPool:ae}}l(Ar,"createRuntimeGlobalApi");function $t(e){if(e==null)return e;if(e instanceof Date)return new Date(e);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(t=>$t(t));if(typeof e=="object"){let t={};for(let[s,i]of Object.entries(e))t[s]=$t(i);return t}return null}l($t,"cloneValue");function Lr(e={}){return new qs(e)}l(Lr,"createRuntime");var qs=class{static{l(this,"RuntimeControllerImpl")}options;listener;assetRegistry=new Ce;assetLoader;debugLogger=new we;DEBUG_UPDATE_FREQUENCY=10;snapshotRestorer=new xs;bridgeUnsubscribe=null;sourceUpdater=null;gameLoop=null;frameCount=0;lastUpdateRate=-1;isStopped=!1;preserveStorageOnNextBoot;sessionSnapshot;screen;audio;input;system;playerService;vm=null;timeMachine=null;constructor(t={}){this.options=t,this.listener=t.listener||{},this.preserveStorageOnNextBoot=t.preserveStorage||!1,this.sessionSnapshot=t.initialSession||null,this.screen=new xi({runtime:this,canvas:t.canvas,width:t.width||400,height:t.height||400}),this.audio=new ii(this),this.input=new Wt(this.screen.getCanvas()),this.system=new qt,this.playerService=new Ti({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.assetLoader=new Gt(t.url||"",t.resources||{},this.audio,this.listener),this.logStep("RuntimeController constructed",{width:this.screen.width,height:this.screen.height,resources:{images:t.resources?.images?.length??0,sounds:t.resources?.sounds?.length??0,music:t.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?Pr(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(t={}){this.logStep("lifecycle: reset requested",t);let s=t.preserveSnapshot?this.exportSnapshot():null,i=t.preserveSession??!0,r=t.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 t=this.vm?.context?.global;return{version:1,global:t?Rn(t):{},session:this.getSession(),system:{updateRate:this.system.getAPI().update_rate}}}async importSnapshot(t){this.vm?.context?.global&&(this.snapshotRestorer.restoreState(this.vm.context.global,t.global),this.system.getAPI().update_rate=t.system.updateRate,this.updateGameLoopUpdateRate(),t.session&&(this.sessionSnapshot=Pr(t.session)))}updateSource(t,s,i=!1){return this.sourceUpdater?this.sourceUpdater.updateSource(t,s,i):!1}handleMessage(t){if(t){if(typeof t=="object"&&"type"in t&&typeof t.type=="string"){this.sendHostEvent(t);return}t.name==="time_machine"&&this.timeMachine&&this.timeMachine.messageReceived(t)}}sendHostEvent(t){this.handleHostEvent(t)}getCanvas(){return this.screen.getCanvas()}async loadAssets(){let t=await this.assetLoader.loadAll();this.assetRegistry.replace(t)}async waitForAssetsReady(){return new Promise(t=>{let s=l(()=>{if(this.assetLoader.isReady()){this.system.setLoading(100),t();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 t={listener:this.listener,options:this.options,screen:this.screen,audio:this.audio,input:this.input,system:this.system,playerService:this.playerService,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=Or(t),i=Ar(t);this.vm=new Re(s,i,this.options.namespace||"/l8b",this.preserveStorageOnNextBoot),this.sourceUpdater=new zt(this.vm,this.listener,this.audio,this.screen,()=>Hs(this.vm,this.listener),(r,n)=>this.emitBridgeEvent(r,n)),this.timeMachine=new ki(this),this.timeMachine.onStatus(r=>{this.emitBridgeEvent("time_machine_status",{status:r})}),this.loadPrograms(),this.emitBridgeEvent("runtime.started",{})}loadPrograms(){if(!this.vm)return;let t=this.options.compiledRoutines||{},s=this.options.sources||{};if(Object.keys(t).length>0){this.logStep("vm: loading compiled routines",{files:Object.keys(t)});for(let[i,r]of Object.entries(t))try{this.vm.loadRoutine(r,i)}catch(n){Et(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){Et(this.listener,{error:i.message||String(i),type:"init",stack:i.stack}),this.logStep("vm: init() error",{message:i?.message||String(i)})}}startGameLoop(){this.logStep("loop: creating game loop"),this.gameLoop=new Ht({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(t=>{if(this.vm)try{this.vm.context?.global?.system&&(this.vm.context.global.system.fps=t)}catch{}},"setFPS")}),this.gameLoop.start(),this.logStep("loop: started")}updateGameLoopUpdateRate(){if(!(!this.vm||!this.gameLoop))try{let t=this.vm.context?.global?.system?.update_rate,s=t!=null&&t>0&&Number.isFinite(t)?t: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.vm.call("update"),this.vm.runner.tick(),this.vm.error_info){let t=Object.assign({},this.vm.error_info);t.type="update",Et(this.listener,t)}}catch(t){Et(this.listener,{error:t.message||String(t),type:"update",stack:t.stack})}}}handleDraw(){if(this.vm){try{if(this.screen.initDraw(),this.screen.updateInterface(),this.vm.call("draw"),this.vm.runner.tick(),Hs(this.vm,this.listener),this.vm.error_info){let t=Object.assign({},this.vm.error_info);t.type="draw",Et(this.listener,t)}}catch(t){Et(this.listener,{error:t.message||String(t),type:"draw",stack:t.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 t=this.options.bridge.subscribe(s=>this.handleHostEvent(s));this.bridgeUnsubscribe=typeof t=="function"?t:null}handleHostEvent(t){switch(t.type){case"session.update":this.mergeSession(t.payload);break;case"runtime.reset":this.reset(Cn(t.payload));break;case"runtime.import_snapshot":In(t.payload)&&this.importSnapshot(t.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&&Kt(t.payload)){let s=t.payload.command;typeof s=="string"&&this.timeMachine.messageReceived({name:"time_machine",command:s,position:typeof t.payload.position=="number"?t.payload.position:void 0})}break}}emitPlayerMessage(t){Kt(t)&&typeof t.type=="string"?this.emitBridgeEvent(t.type,t):this.emitBridgeEvent("player.message",t)}emitBridgeEvent(t,s){this.options.bridge?.emit?.(t,s)}sendBridgeRequest(t,s,i){let r=this.options.bridge?.request;if(!r)return i?.({ok:!1,error:`No runtime bridge request handler registered for "${t}"`}),null;let n=wn(t);try{let a=r(t,s);return Ie(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(t,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,t);return Ie(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(t,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(t);return Ie(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 t=this.options.bridge?.getSession;if(!t){this.sessionSnapshot=this.options.initialSession||null;return}try{let s=t();this.sessionSnapshot=Ie(s)?await s:s}catch{this.sessionSnapshot=this.options.initialSession||null}}mergeSession(t){if(!Kt(t))return;let s=this.sessionSnapshot||{};this.sessionSnapshot={...s,...t}}teardownRuntimeState(){this.gameLoop=null,this.sourceUpdater=null,this.vm=null,this.timeMachine=null,this.frameCount=0,this.lastUpdateRate=-1,this.isStopped=!1}logStep(t,s){if(!this.options.debug?.lifecycle)return;let i="[@al8b/runtime][lifecycle]";if(s!==void 0?console.info(`${i} ${t}`,s):console.info(`${i} ${t}`),this.listener.log)try{let r=s===void 0?"":` ${JSON.stringify(s)}`;this.listener.log(`${i} ${t}${r}`)}catch{this.listener.log(`${i} ${t}`)}}};function Rn(e){let t=e,s=[t.random,t.screen,t.audio,t.keyboard,t.mouse,t.touch,t.gamepad,t.system,t.storage,t.host,t.session,t.memory].filter(i=>i!=null);return De(t,s)}l(Rn,"serializeGlobalSnapshot");function De(e,t=[]){if(e==null)return e;if(t.includes(e))return null;if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(s=>De(s,t));if(typeof e=="object"){let s={};for(let[i,r]of Object.entries(e))s[i]=De(r,t);return s}return null}l(De,"deepCloneValue");function Pr(e){return De(e)}l(Pr,"cloneSnapshot");function wn(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`}l(wn,"createRequestId");function Ie(e){return typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function"}l(Ie,"isPromiseLike");function Kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}l(Kt,"isRecord");function Cn(e){return Kt(e)?e:void 0}l(Cn,"asRecord");function In(e){return!(!Kt(e)||e.version!==1||!Kt(e.global)||!("session"in e))}l(In,"isRuntimeSnapshot");function Dn(e){if(typeof structuredClone<"u")return structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch{return e}}l(Dn,"deepClone");function Nn(e,t){if(e===t)return!0;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return!1;let s=e,i=t,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(Nn,"shallowEqual");return wr(Mn);})();