@grimmdev/retrokit 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ (function(S,k){typeof exports=="object"&&typeof module<"u"?k(exports):typeof define=="function"&&define.amd?define(["exports"],k):(S=typeof globalThis<"u"?globalThis:S||self,k(S.RetroKit={}))})(this,(function(S){"use strict";var Le=Object.defineProperty;var Be=(S,k,I)=>k in S?Le(S,k,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[k]=I;var c=(S,k,I)=>Be(S,typeof k!="symbol"?k+"":k,I);class k{constructor(){c(this,"context",null);c(this,"isRunningInternal",!1);c(this,"isPausedInternal",!1)}async init(a){this.context=a}start(){this.isRunningInternal=!0,this.isPausedInternal=!1}pause(){this.isPausedInternal=!0}resume(){this.isPausedInternal=!1}async stop(){this.isRunningInternal=!1,this.isPausedInternal=!1,await this.rawFlushSram()}async restart(){this.pause(),this.start()}async destroy(){await this.stop(),this.context=null}async rawSaveState(a){var e;return(e=this.context)!=null&&e.debug&&console.warn(`[BaseCoreBridge] Core "${this.id}" does not support save states.`),null}async rawLoadState(a,e){var t;return(t=this.context)!=null&&t.debug&&console.warn(`[BaseCoreBridge] Core "${this.id}" does not support loading save states.`),!1}async rawSetBios(a,e){}rawReadMemory(a,e){return null}rawGetMemorySize(){return 0}async rawGetSram(){return null}async rawSetSram(a){return!1}async rawFlushSram(){}getSramPath(){return""}rawGetOptions(){return[]}rawSetOption(a,e){}rawSetCheat(a,e,t){}rawResetCheats(){}rawGetDiscCount(){return 1}async rawChangeDisc(a){return!1}rawSendButton(a,e,t){}rawSendAxis(a,e,t){}rawSetVolume(a){}rawSetSpeed(a){}rawGetFps(){return 60}getCanvas(){var a;if(!((a=this.context)!=null&&a.canvas))throw new Error(`[BaseCoreBridge] Core "${this.id}" has no canvas bound.`);return this.context.canvas}}class I{static async decompress(a,e,t){const s=await this._getWorkerScript(e),r=new Blob([s],{type:"application/javascript"}),i=URL.createObjectURL(r),n=new Worker(i);return new Promise((o,l)=>{const d={};n.onmessage=p=>{const w=p.data;if(w){if(w.t===4&&w.total&&t){const h=Math.floor(w.current/w.total*100);t(Number.isNaN(h)?0:h);return}if(w.t===2&&w.file&&w.data){d[w.file]=w.data;return}w.t===1&&(u(),o(d))}},n.onerror=p=>{u(),l(new Error(`[ArchiveExtractor] Failed to unpack ${e} archive: ${p.message||"Worker error"}`))};const u=()=>{try{n.terminate()}catch{}try{URL.revokeObjectURL(i)}catch{}},m=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);n.postMessage(new Uint8Array(m),[m])})}static async _getWorkerScript(a){const e=this._workerScriptCache.get(a);if(e)return e;const t=a==="7z"?"extract7z.js":"extractzip.js",s=`/compression/${t}`,r=`https://cdn.emulatorjs.org/stable/data/compression/${t}`;try{const o=await fetch(s);if(o.ok){const l=await o.text();return this._workerScriptCache.set(a,l),l}}catch{}const i=await fetch(r);if(!i.ok)throw new Error(`[ArchiveExtractor] Could not retrieve decompression worker from "${r}" (status: ${i.status})`);const n=await i.text();return this._workerScriptCache.set(a,n),n}}c(I,"_workerScriptCache",new Map);const ee={ppsspp:{channel:"stable",bundleName:"ppsspp-thread-wasm.data",jsName:"ppsspp_libretro.js",wasmName:"ppsspp_libretro.wasm",assetsUrl:"https://cdn.emulatorjs.org/stable/data/cores/ppsspp-assets.zip",needsWebGL2:!0,needsThreads:!0},azahar:{channel:"nightly",bundleName:"azahar-thread-wasm.data",jsName:"azahar_libretro.js",wasmName:"azahar_libretro.wasm",needsWebGL2:!0,needsThreads:!0},desmume:{channel:"stable",bundleName:"desmume-wasm.data",jsName:"desmume_libretro.js",wasmName:"desmume_libretro.wasm",needsWebGL2:!0,needsThreads:!1},desmume2015:{channel:"stable",bundleName:"desmume2015-wasm.data",jsName:"desmume2015_libretro.js",wasmName:"desmume2015_libretro.wasm",needsWebGL2:!0,needsThreads:!1},melonds:{channel:"stable",bundleName:"melonds-wasm.data",jsName:"melonds_libretro.js",wasmName:"melonds_libretro.wasm",needsWebGL2:!0,needsThreads:!1},mupen64plus_next:{channel:"stable",bundleName:"mupen64plus_next-thread-wasm.data",jsName:"mupen64plus_next_libretro.js",wasmName:"mupen64plus_next_libretro.wasm",needsWebGL2:!0,needsThreads:!0},parallel_n64:{channel:"stable",bundleName:"parallel_n64-thread-wasm.data",jsName:"parallel_n64_libretro.js",wasmName:"parallel_n64_libretro.wasm",needsWebGL2:!0,needsThreads:!0},dosbox_pure:{channel:"stable",bundleName:"dosbox_pure-thread-wasm.data",jsName:"dosbox_pure_libretro.js",wasmName:"dosbox_pure_libretro.wasm",needsWebGL2:!1,needsThreads:!0},yabause:{channel:"stable",bundleName:"yabause-wasm.data",jsName:"yabause_libretro.js",wasmName:"yabause_libretro.wasm",needsWebGL2:!0,needsThreads:!1},virtualjaguar:{channel:"stable",bundleName:"virtualjaguar-wasm.data",jsName:"virtualjaguar_libretro.js",wasmName:"virtualjaguar_libretro.wasm",needsWebGL2:!1,needsThreads:!1},opera:{channel:"stable",bundleName:"opera-wasm.data",jsName:"opera_libretro.js",wasmName:"opera_libretro.wasm",needsWebGL2:!0,needsThreads:!1},puae:{channel:"stable",bundleName:"puae-wasm.data",jsName:"puae_libretro.js",wasmName:"puae_libretro.wasm",needsWebGL2:!1,needsThreads:!1},vice_x64sc:{channel:"stable",bundleName:"vice_x64sc-wasm.data",jsName:"vice_x64sc_libretro.js",wasmName:"vice_x64sc_libretro.wasm",needsWebGL2:!1,needsThreads:!1},vice_x128:{channel:"stable",bundleName:"vice_x128-wasm.data",jsName:"vice_x128_libretro.js",wasmName:"vice_x128_libretro.wasm",needsWebGL2:!1,needsThreads:!1},vice_xpet:{channel:"stable",bundleName:"vice_xpet-wasm.data",jsName:"vice_xpet_libretro.js",wasmName:"vice_xpet_libretro.wasm",needsWebGL2:!1,needsThreads:!1},vice_xplus4:{channel:"stable",bundleName:"vice_xplus4-wasm.data",jsName:"vice_xplus4_libretro.js",wasmName:"vice_xplus4_libretro.wasm",needsWebGL2:!1,needsThreads:!1},vice_xvic:{channel:"stable",bundleName:"vice_xvic-wasm.data",jsName:"vice_xvic_libretro.js",wasmName:"vice_xvic_libretro.wasm",needsWebGL2:!1,needsThreads:!1},freeintv:{channel:"nightly",bundleName:"freeintv-wasm.data",jsName:"freeintv_libretro.js",wasmName:"freeintv_libretro.wasm",needsWebGL2:!1,needsThreads:!1},gearcoleco:{channel:"stable",bundleName:"gearcoleco-wasm.data",jsName:"gearcoleco_libretro.js",wasmName:"gearcoleco_libretro.wasm",needsWebGL2:!1,needsThreads:!1},a5200:{channel:"stable",bundleName:"a5200-wasm.data",jsName:"a5200_libretro.js",wasmName:"a5200_libretro.wasm",needsWebGL2:!1,needsThreads:!1},prosystem:{channel:"stable",bundleName:"prosystem-wasm.data",jsName:"prosystem_libretro.js",wasmName:"prosystem_libretro.wasm",needsWebGL2:!1,needsThreads:!1},stella2014:{channel:"stable",bundleName:"stella2014-wasm.data",jsName:"stella2014_libretro.js",wasmName:"stella2014_libretro.wasm",needsWebGL2:!1,needsThreads:!1},handy:{channel:"stable",bundleName:"handy-wasm.data",jsName:"handy_libretro.js",wasmName:"handy_libretro.wasm",needsWebGL2:!1,needsThreads:!1},beetle_vb:{channel:"stable",bundleName:"beetle_vb-wasm.data",jsName:"beetle_vb_libretro.js",wasmName:"beetle_vb_libretro.wasm",needsWebGL2:!1,needsThreads:!1},same_cdi:{channel:"stable",bundleName:"same_cdi-wasm.data",jsName:"same_cdi_libretro.js",wasmName:"same_cdi_libretro.wasm",needsWebGL2:!1,needsThreads:!1},fbneo:{channel:"stable",bundleName:"fbneo-wasm.data",jsName:"fbneo_libretro.js",wasmName:"fbneo_libretro.wasm",needsWebGL2:!1,needsThreads:!1},fbalpha2012_cps1:{channel:"stable",bundleName:"fbalpha2012_cps1-wasm.data",jsName:"fbalpha2012_cps1_libretro.js",wasmName:"fbalpha2012_cps1_libretro.wasm",needsWebGL2:!1,needsThreads:!1},fbalpha2012_cps2:{channel:"stable",bundleName:"fbalpha2012_cps2-wasm.data",jsName:"fbalpha2012_cps2_libretro.js",wasmName:"fbalpha2012_cps2_libretro.wasm",needsWebGL2:!1,needsThreads:!1},mame2003_plus:{channel:"stable",bundleName:"mame2003_plus-wasm.data",jsName:"mame2003_plus_libretro.js",wasmName:"mame2003_plus_libretro.wasm",needsWebGL2:!1,needsThreads:!1},mame2003:{channel:"stable",bundleName:"mame2003-wasm.data",jsName:"mame2003_libretro.js",wasmName:"mame2003_libretro.wasm",needsWebGL2:!1,needsThreads:!1},pcsx_rearmed:{channel:"stable",bundleName:"pcsx_rearmed-wasm.data",jsName:"pcsx_rearmed_libretro.js",wasmName:"pcsx_rearmed_libretro.wasm",needsWebGL2:!1,needsThreads:!1},mednafen_psx_hw:{channel:"stable",bundleName:"mednafen_psx_hw-wasm.data",jsName:"mednafen_psx_hw_libretro.js",wasmName:"mednafen_psx_hw_libretro.wasm",needsWebGL2:!0,needsThreads:!1},mednafen_pce:{channel:"stable",bundleName:"mednafen_pce-wasm.data",jsName:"mednafen_pce_libretro.js",wasmName:"mednafen_pce_libretro.wasm",needsWebGL2:!1,needsThreads:!1},mednafen_pcfx:{channel:"stable",bundleName:"mednafen_pcfx-wasm.data",jsName:"mednafen_pcfx_libretro.js",wasmName:"mednafen_pcfx_libretro.wasm",needsWebGL2:!1,needsThreads:!1},mednafen_ngp:{channel:"stable",bundleName:"mednafen_ngp-wasm.data",jsName:"mednafen_ngp_libretro.js",wasmName:"mednafen_ngp_libretro.wasm",needsWebGL2:!1,needsThreads:!1},mednafen_wswan:{channel:"stable",bundleName:"mednafen_wswan-wasm.data",jsName:"mednafen_wswan_libretro.js",wasmName:"mednafen_wswan_libretro.wasm",needsWebGL2:!1,needsThreads:!1},smsplus:{channel:"stable",bundleName:"smsplus-wasm.data",jsName:"smsplus_libretro.js",wasmName:"smsplus_libretro.wasm",needsWebGL2:!1,needsThreads:!1},genesis_plus_gx:{channel:"stable",bundleName:"genesis_plus_gx-wasm.data",jsName:"genesis_plus_gx_libretro.js",wasmName:"genesis_plus_gx_libretro.wasm",needsWebGL2:!1,needsThreads:!1},genesis_plus_gx_wide:{channel:"nightly",bundleName:"genesis_plus_gx_wide-wasm.data",jsName:"genesis_plus_gx_wide_libretro.js",wasmName:"genesis_plus_gx_wide_libretro.wasm",needsWebGL2:!1,needsThreads:!1},picodrive:{channel:"stable",bundleName:"picodrive-wasm.data",jsName:"picodrive_libretro.js",wasmName:"picodrive_libretro.wasm",needsWebGL2:!1,needsThreads:!1},snes9x:{channel:"stable",bundleName:"snes9x-wasm.data",jsName:"snes9x_libretro.js",wasmName:"snes9x_libretro.wasm",needsWebGL2:!1,needsThreads:!1},bsnes:{channel:"nightly",bundleName:"bsnes-wasm.data",jsName:"bsnes_libretro.js",wasmName:"bsnes_libretro.wasm",needsWebGL2:!1,needsThreads:!1},gambatte:{channel:"stable",bundleName:"gambatte-wasm.data",jsName:"gambatte_libretro.js",wasmName:"gambatte_libretro.wasm",needsWebGL2:!1,needsThreads:!1},mgba:{channel:"stable",bundleName:"mgba-wasm.data",jsName:"mgba_libretro.js",wasmName:"mgba_libretro.wasm",needsWebGL2:!1,needsThreads:!1},fceumm:{channel:"stable",bundleName:"fceumm-wasm.data",jsName:"fceumm_libretro.js",wasmName:"fceumm_libretro.wasm",needsWebGL2:!1,needsThreads:!1},nestopia:{channel:"stable",bundleName:"nestopia-wasm.data",jsName:"nestopia_libretro.js",wasmName:"nestopia_libretro.wasm",needsWebGL2:!1,needsThreads:!1}};function Ce(_){if(ee[_])return ee[_];const a=["azahar","freeintv","bsnes","genesis_plus_gx_wide"].includes(_),e=["ppsspp","azahar","dosbox_pure","mupen64plus_next","parallel_n64"].includes(_),t=_==="ppsspp"||_==="azahar"||_==="dosbox_pure"?"-thread-wasm.data":"-wasm.data",s=["ppsspp","azahar","desmume","desmume2015","melonds","mupen64plus_next","parallel_n64","yabause","opera","mednafen_psx_hw"].includes(_);return{channel:a?"nightly":"stable",bundleName:`${_}${t}`,jsName:`${_}_libretro.js`,wasmName:`${_}_libretro.wasm`,needsWebGL2:s,needsThreads:e}}const X=new Map;let Y=null;class te extends k{constructor(e,t,s,r){super();c(this,"id");c(this,"name");c(this,"system");c(this,"capabilities");c(this,"_module",null);c(this,"_romData",null);c(this,"_romPath","/home/web_user/retroarch/userdata/content/rom.bin");c(this,"_sramPath","/home/web_user/retroarch/userdata/saves/rom.srm");c(this,"_fps",60);c(this,"_coreOptionsMap",{});c(this,"_additionalFiles",[]);c(this,"_started",!1);c(this,"_blobUrlsToRevoke",[]);c(this,"_scriptElement",null);c(this,"_pendingBios",new Map);c(this,"_isDispatchingFallback",!1);this.id=e,this.name=t,this.system=s,this.capabilities=r}async init(e){await super.init(e)}async loadGame(e,t){var i;if(typeof e=="string"){const n=await fetch(e,{headers:(i=this.context)==null?void 0:i.fetchHeaders});if(!n.ok)throw new Error(`[EmulatorJSAdapter] Failed to fetch ROM from URL: ${e}`);const o=await n.arrayBuffer();this._romData=new Uint8Array(o)}else if(e instanceof Blob){const n=await e.arrayBuffer();this._romData=new Uint8Array(n)}else e instanceof Uint8Array?this._romData=e:this._romData=new Uint8Array(e);const s=(t==null?void 0:t.fileName)||"rom.bin";this._romPath=`/home/web_user/retroarch/userdata/content/${s}`;const r=s.replace(/\.[^.]+$/,"");if(this._sramPath=`/home/web_user/retroarch/userdata/saves/${r}.srm`,this._additionalFiles=[],t!=null&&t.additionalFiles)for(const n of t.additionalFiles){let o;if(n.data instanceof Uint8Array)o=n.data;else if(n.data instanceof ArrayBuffer)o=new Uint8Array(n.data);else if(n.data instanceof Blob){const l=await n.data.arrayBuffer();o=new Uint8Array(l)}else o=new Uint8Array(n.data);this._additionalFiles.push({name:n.name,data:o})}await this._instantiateCoreModule(),t!=null&&t.initialSram&&t.initialSram instanceof Uint8Array&&await this.rawSetSram(t.initialSram),this.start()}start(){var e;if(super.start(),!!this._module){if(this._started)this.resume();else if(this._started=!0,typeof this._module.callMain=="function")try{const t=this._romPath.split("/").pop()||"rom.bin",r=!!((e=this.context)!=null&&e.debug)?["-v",`/${t}`]:[`/${t}`];this._module.callMain(r),typeof this._module.resumeMainLoop=="function"&&this._module.resumeMainLoop()}catch(t){t&&t.name!=="ExitStatus"?console.error("[EmulatorJSAdapter] Error starting core:",t):t!=null&&t.status&&t.status!==0&&console.error(`[EmulatorJSAdapter] Core exited with code ${t.status}`)}}}pause(){super.pause(),this._module&&(typeof this._module.pauseMainLoop=="function"?this._module.pauseMainLoop():typeof this._module.EmscriptenSendCommand=="function"&&this._module.EmscriptenSendCommand("PAUSE_TOGGLE"))}resume(){if(super.resume(),!this._started){this.start();return}this._module&&(typeof this._module.resumeMainLoop=="function"?this._module.resumeMainLoop():typeof this._module.EmscriptenSendCommand=="function"&&this._module.EmscriptenSendCommand("PAUSE_TOGGLE"))}async stop(){await super.stop(),this._module&&typeof this._module.pauseMainLoop=="function"&&this._module.pauseMainLoop(),await this.rawFlushSram()}async restart(){this._module&&(typeof this._module.EmscriptenSendCommand=="function"?this._module.EmscriptenSendCommand("RESET"):(this._dispatchKeyboardFallback(100,!0),setTimeout(()=>this._dispatchKeyboardFallback(100,!1),50)),this.resume())}async destroy(){var e,t;if(await super.destroy(),this._module){if(typeof this._module.pauseMainLoop=="function")try{this._module.pauseMainLoop()}catch{}if((e=this._module.PThread)!=null&&e.terminateAllThreads)try{this._module.PThread.terminateAllThreads()}catch{}if(typeof this._module.abort=="function")try{this._module.abort()}catch{}this._module=null}if((t=this._scriptElement)!=null&&t.parentNode&&(this._scriptElement.parentNode.removeChild(this._scriptElement),this._scriptElement=null),typeof window<"u"&&window.EJS_Runtime)try{delete window.EJS_Runtime}catch{}for(const s of this._blobUrlsToRevoke)try{URL.revokeObjectURL(s)}catch{}this._blobUrlsToRevoke=[],this._romData=null,this._started=!1}async rawSaveState(e=0){if(!this._module)return null;if(this._module.gameManager&&typeof this._module.gameManager.getState=="function"){const t=this._module.gameManager.getState();return t?new Uint8Array(t):null}if(typeof this._module._retro_serialize=="function"&&typeof this._module._retro_serialize_size=="function"){const t=this._module._retro_serialize_size();if(t>0){const s=this._module._malloc(t);if(this._module._retro_serialize(s,t)){const i=new Uint8Array(this._module.HEAPU8.buffer,s,t).slice();return this._module._free(s),i}this._module._free(s)}}if(this._module.FS){const t="/home/web_user/retroarch/userdata/states",s="/home/web_user/retroarch/userdata/content";this._ensureDirectories(this._module.FS,t),this._ensureDirectories(this._module.FS,s);const r=this._findStateFiles(this._module.FS);for(const n of r)try{this._module.FS.unlink(n.path)}catch{}const i=e>0?`SAVE_STATE_SLOT ${e}`:"SAVE_STATE";this._sendCommand(i);for(let n=0;n<40;n++){await new Promise(l=>setTimeout(l,50));const o=this._findStateFiles(this._module.FS);if(o.length>0)return o[0].data}}return null}async rawLoadState(e,t=0){if(!this._module)return!1;if(this._module.gameManager&&typeof this._module.gameManager.loadState=="function")return this._module.gameManager.loadState(e),!0;if(typeof this._module._retro_unserialize=="function"){const s=this._module._malloc(e.byteLength);this._module.HEAPU8.set(e,s);const r=this._module._retro_unserialize(s,e.byteLength);return this._module._free(s),!!r}if(this._module.FS){const s="/home/web_user/retroarch/userdata/states",r="/home/web_user/retroarch/userdata/content";this._ensureDirectories(this._module.FS,s),this._ensureDirectories(this._module.FS,r);const n=(this._romPath.split("/").pop()||"rom.bin").replace(/\.[^.]+$/,"");this._module.FS.writeFile(`${s}/${n}.state`,e),this._module.FS.writeFile(`${s}/${n}.state.auto`,e),this._module.FS.writeFile(`${s}/${n}.state0`,e),this._module.FS.writeFile(`${s}/${n}.state1`,e),t>1&&this._module.FS.writeFile(`${s}/${n}.state${t}`,e),this._module.FS.writeFile(`${r}/${n}.state`,e),this._module.FS.writeFile(`${r}/${n}.state.auto`,e),this._module.FS.writeFile(`${r}/${n}.state0`,e),this._module.FS.writeFile(`${r}/${n}.state1`,e);const o=t>0?`LOAD_STATE_SLOT ${t}`:"LOAD_STATE";return this._sendCommand(o),!0}return!1}async rawGetSram(){if(!this._module)return null;if(this._module.gameManager&&typeof this._module.gameManager.getSaveFile=="function"){const e=this._module.gameManager.getSaveFile();return e?new Uint8Array(e):null}if(this._module.FS&&this._sramPath)try{if(this._module.FS.analyzePath(this._sramPath).exists){const e=this._module.FS.readFile(this._sramPath);return new Uint8Array(e)}}catch{}return null}async rawSetSram(e){if(!this._module||!(e instanceof Uint8Array))return!1;if(this._module.FS)try{const t=this._sramPath.substring(0,this._sramPath.lastIndexOf("/"));return this._ensureDirectories(this._module.FS,t),this._module.FS.writeFile(this._sramPath,e),this._module.gameManager&&typeof this._module.gameManager.loadSaveFiles=="function"&&this._module.gameManager.loadSaveFiles(),!0}catch(t){console.warn("[EmulatorJSAdapter] Failed to write SRAM to virtual FS:",t)}return!1}async rawFlushSram(){var e;if((e=this._module)!=null&&e.gameManager&&typeof this._module.gameManager.saveSaveFiles=="function")try{this._module.gameManager.saveSaveFiles()}catch{}}getSramPath(){return this._sramPath}async rawSetBios(e,t){var i,n,o;const s=e.replace(/^.*[\\/]/,"");this._pendingBios.set(s,t);const r="/home/web_user/retroarch/userdata/system";(i=this._module)!=null&&i.FS&&(this._ensureDirectories(this._module.FS,r),this._module.FS.writeFile(`${r}/${s}`,t),(o=(n=this.context)==null?void 0:n.onLog)==null||o.call(n,`[EmulatorJSAdapter] Injected BIOS: ${s} (${t.byteLength} bytes)`,"info"))}rawReadMemory(e,t){if(!this._module)return null;try{if(typeof this._module._retro_get_memory_data=="function"){const s=this._module._retro_get_memory_data(0),r=typeof this._module._retro_get_memory_size=="function"?this._module._retro_get_memory_size(0):0;if(s&&r>0&&e+t<=r&&this._module.HEAPU8)return new Uint8Array(this._module.HEAPU8.buffer,s+e,t).slice()}}catch{}return null}rawGetMemorySize(){if(!this._module)return 0;try{if(typeof this._module._retro_get_memory_size=="function")return this._module._retro_get_memory_size(0)}catch{}return 0}rawGetOptions(){return[]}rawSetOption(e,t){var s;if(this._coreOptionsMap[e]=t,(s=this._module)!=null&&s.gameManager&&typeof this._module.gameManager.setVariable=="function")try{this._module.gameManager.setVariable(e,t)}catch{}}rawSetCheat(e,t,s){if(this._module&&typeof this._module.cheatChanged=="function")try{this._module.cheatChanged(t,s,e)}catch{}}rawResetCheats(){if(this._module&&typeof this._module._retro_cheat_reset=="function")try{this._module._retro_cheat_reset()}catch{}}rawGetDiscCount(){return 1}async rawChangeDisc(e){var t;if((t=this._module)!=null&&t.gameManager&&typeof this._module.gameManager.loadDisc=="function")try{return this._module.gameManager.loadDisc(e),!0}catch{}return!1}rawSendButton(e,t,s){var r,i,n;(r=this._module)!=null&&r.gamepad&&typeof this._module.gamepad.sendButton=="function"?this._module.gamepad.sendButton(e,t,s):(i=this._module)!=null&&i.gameManager&&typeof this._module.gameManager.simulateInput=="function"?this._module.gameManager.simulateInput(e,t,s?1:0):(n=this._module)!=null&&n.simulateGamepadButton?this._module.simulateGamepadButton(e,t,s):this._dispatchKeyboardFallback(t,s)}rawSendAxis(e,t,s){var r,i;if((r=this._module)!=null&&r.gamepad&&typeof this._module.gamepad.sendAxis=="function")this._module.gamepad.sendAxis(e,t,s);else if((i=this._module)!=null&&i.gameManager&&typeof this._module.gameManager.simulateInput=="function"){const o=Math.abs(s),l=o>.05?Math.round(o*32767):0;t===0?(this._module.gameManager.simulateInput(e,16,s>.05?l:0),this._module.gameManager.simulateInput(e,17,s<-.05?l:0)):t===1?(this._module.gameManager.simulateInput(e,18,s>.05?l:0),this._module.gameManager.simulateInput(e,19,s<-.05?l:0)):t===2?(this._module.gameManager.simulateInput(e,20,s>.05?l:0),this._module.gameManager.simulateInput(e,21,s<-.05?l:0)):t===3&&(this._module.gameManager.simulateInput(e,22,s>.05?l:0),this._module.gameManager.simulateInput(e,23,s<-.05?l:0))}}rawSendPointer(e,t,s,r=0){var m;const i=(m=this.context)==null?void 0:m.canvas;if(!i)return;const n=i.getBoundingClientRect(),o=n.left+e*n.width,l=n.top+t*n.height,d=s?"pointerdown":"pointerup",u=new PointerEvent(d,{clientX:o,clientY:l,bubbles:!0,cancelable:!0,pointerType:"touch",isPrimary:!0,button:0,buttons:s?1:0});i.dispatchEvent(u)}rawGetFps(){return this._fps}async _instantiateCoreModule(){var g,f,y,x,A,T,F,U,b,C,R,z,ve;const e=Ce(this.id);if((f=(g=this.context)==null?void 0:g.onLog)==null||f.call(g,`[EmulatorJSAdapter] Initializing ${this.name} (${this.id})...`,"info"),e.needsThreads&&typeof SharedArrayBuffer>"u"){const v=`[EmulatorJSAdapter] Core "${this.id}" requires multi-threading (SharedArrayBuffer), but cross-origin isolation is not active. Ensure COOP: same-origin and COEP: require-corp headers are served.`;console.warn(v),(x=(y=this.context)==null?void 0:y.onLog)==null||x.call(y,v,"error")}(A=this._scriptElement)!=null&&A.parentNode&&(this._scriptElement.parentNode.removeChild(this._scriptElement),this._scriptElement=null);const t=typeof window<"u"?window:globalThis;delete t.EJS_Runtime;const{jsBytes:s,wasmBytes:r}=await this._acquireCoreBinaries(e);let i=null;this.id==="ppsspp"&&(i=await this._acquirePpssppAssets(e));const n=new Blob([s],{type:"application/javascript"}),o=new Blob([r],{type:"application/wasm"}),l=URL.createObjectURL(n),d=URL.createObjectURL(o);this._blobUrlsToRevoke.push(l,d),(T=this.context)!=null&&T.canvas&&!this.context.canvas.id&&(this.context.canvas.id="canvas");const u=!!((F=this.context)!=null&&F.debug),m="/home/web_user/retroarch/userdata/retroarch.cfg",p="/home/web_user/.config/retroarch/retroarch.cfg",w={canvas:(U=this.context)==null?void 0:U.canvas,parent:((C=(b=this.context)==null?void 0:b.canvas)==null?void 0:C.parentElement)||((R=this.context)==null?void 0:R.canvas),wasmBinary:r,noInitialRun:!0,arguments:[],mainScriptUrlOrBlob:l,locateFile:(v,L)=>v.endsWith(".wasm")?d:(L||"")+v,callbacks:{setupCoreSettingFile:()=>{}},preRun:[v=>{var L,$;if(v.FS){this._ensureDirectories(v.FS,"/home"),this._ensureDirectories(v.FS,"/home/web_user"),this._ensureDirectories(v.FS,"/home/web_user/.config"),this._ensureDirectories(v.FS,"/home/web_user/.config/retroarch"),this._ensureDirectories(v.FS,"/home/web_user/retroarch"),this._ensureDirectories(v.FS,"/home/web_user/retroarch/cores"),this._ensureDirectories(v.FS,"/home/web_user/retroarch/userdata"),this._ensureDirectories(v.FS,"/home/web_user/retroarch/userdata/content"),this._ensureDirectories(v.FS,"/home/web_user/retroarch/userdata/saves"),this._ensureDirectories(v.FS,"/home/web_user/retroarch/userdata/states"),this._ensureDirectories(v.FS,"/home/web_user/retroarch/userdata/system"),i&&this._injectPpssppAssets(v.FS,i);for(const[B,q]of this._pendingBios.entries())try{v.FS.writeFile(`/home/web_user/retroarch/userdata/system/${B}`,q),($=(L=this.context)==null?void 0:L.onLog)==null||$.call(L,`[EmulatorJSAdapter] Flushed queued BIOS: ${B} (${q.byteLength} bytes)`,"info")}catch(Oe){console.warn("[EmulatorJSAdapter] Failed to flush queued BIOS:",B,Oe)}const xe=["autosave_interval = 60",'screenshot_directory = "/"',"block_sram_overwrite = false","video_gpu_screenshot = false","audio_latency = 64","video_top_portrait_viewport = true","video_vsync = true","video_smooth = false","video_threaded = false","video_shared_context = true","fastforward_ratio = 3.0","slowmotion_ratio = 3.0",'savefile_directory = "/home/web_user/retroarch/userdata/saves"','savestate_directory = "/home/web_user/retroarch/userdata/states"','system_directory = "/home/web_user/retroarch/userdata/system"','content_directory = "/home/web_user/retroarch/userdata/content"','input_enable_hotkey = "nul"','input_save_state = "f2"','input_load_state = "f4"','input_reset = "h"','network_cmd_enable = "true"','stdin_cmd_enable = "false"',""].join(`
2
+ `);try{v.FS.writeFile(m,xe),v.FS.writeFile(p,xe)}catch{}if(this._romData)try{v.FS.writeFile(this._romPath,this._romData);const B=this._romPath.split("/").pop()||"rom.bin";v.FS.writeFile(`/${B}`,this._romData)}catch(B){console.error("[EmulatorJSAdapter] Error writing ROM to virtual FS:",B)}for(const B of this._additionalFiles)try{v.FS.writeFile(`/home/web_user/retroarch/userdata/content/${B.name}`,B.data),v.FS.writeFile(`/${B.name}`,B.data)}catch(q){console.warn("[EmulatorJSAdapter] Error writing companion file:",B.name,q)}}}],stdin:()=>null,print:v=>{var L,$;u&&console.log(`[${this.id}]`,v),($=(L=this.context)==null?void 0:L.onLog)==null||$.call(L,v,"info")},printErr:v=>{var L,$;u&&console.error(`[${this.id} Err]`,v),($=(L=this.context)==null?void 0:L.onLog)==null||$.call(L,v,"error")}};await this._loadScriptTag(l);const h=window.EJS_Runtime;if(typeof h!="function")throw new Error("[EmulatorJSAdapter] Core runtime script did not export window.EJS_Runtime.");this._module=await h(w),this._initializeGameManager(this._module),(ve=(z=this.context)==null?void 0:z.onLog)==null||ve.call(z,`[EmulatorJSAdapter] ${this.name} runtime instantiated successfully.`,"info")}_initializeGameManager(e){if(!(!e||typeof e.cwrap!="function"))try{const t={restart:e.cwrap("system_restart","",[]),saveStateInfo:e.cwrap("save_state_info","string",[]),loadState:e.cwrap("load_state","number",["string","number"]),simulateInput:e.cwrap("simulate_input","null",["number","number","number"]),getCoreOptions:e.cwrap("get_core_options","string",[]),setVariable:e.cwrap("ejs_set_variable","null",["string","string"]),setCheat:e.cwrap("set_cheat","null",["number","number","string"]),resetCheat:e.cwrap("reset_cheat","null",[]),loadSaveFiles:e.cwrap("refresh_save_files","null",[]),saveSaveFiles:e.cwrap("cmd_savefiles","",[])};e.gameManager={simulateInput:(s,r,i)=>{var n;try{(n=t.simulateInput)==null||n.call(t,s,r,i)}catch{}},getState:()=>{try{if(!t.saveStateInfo)return null;const s=t.saveStateInfo().split("|");if(s[2]!=="1")return null;const r=parseInt(s[0],10),i=parseInt(s[1],10);return new Uint8Array(e.HEAPU8.subarray(i,i+r))}catch{return null}},loadState:s=>{var r,i;try{return(r=e.FS)==null||r.writeFile("/game.state",s),(i=t.loadState)==null||i.call(t,"game.state",0),!0}catch{return!1}},setVariable:(s,r)=>{var i;try{(i=t.setVariable)==null||i.call(t,s,r)}catch{}},restart:()=>{var s;try{(s=t.restart)==null||s.call(t)}catch{}},saveSaveFiles:()=>{var s;try{(s=t.saveSaveFiles)==null||s.call(t)}catch{}},loadSaveFiles:()=>{var s;try{(s=t.loadSaveFiles)==null||s.call(t)}catch{}}}}catch{}}async _acquireCoreBinaries(e){var u,m,p,w,h;const t=X.get(this.id);if(t)return{jsBytes:t.js,wasmBytes:t.wasm};const s=(u=this.context)==null?void 0:u.assetBaseUrl;if(s){const g=s.replace(/\/$/,""),f=`${g}/${e.jsName}`,y=`${g}/${e.wasmName}`;try{const[x,A]=await Promise.all([fetch(f),fetch(y)]);if(x.ok&&A.ok){const[T,F]=await Promise.all([x.arrayBuffer(),A.arrayBuffer()]),U=new Uint8Array(T),b=new Uint8Array(F);return X.set(this.id,{js:U,wasm:b}),{jsBytes:U,wasmBytes:b}}}catch{}}const r=`/emulatorjs-cores/${e.channel}/data/cores/${e.bundleName}`,i=`https://cdn.emulatorjs.org/${e.channel}/data/cores/${e.bundleName}`;(p=(m=this.context)==null?void 0:m.onLog)==null||p.call(m,`[EmulatorJSAdapter] Downloading core archive: ${e.bundleName}...`,"info");let n=null;try{const g=await fetch(r);g.ok&&(n=new Uint8Array(await g.arrayBuffer()))}catch{}if(!n){const g=await fetch(i);if(!g.ok)throw new Error(`[EmulatorJSAdapter] Failed to download core package from "${i}" (status: ${g.status})`);n=new Uint8Array(await g.arrayBuffer())}(h=(w=this.context)==null?void 0:w.onLog)==null||h.call(w,`[EmulatorJSAdapter] Unpacking ${e.bundleName} (7z)...`,"info");const o=await I.decompress(n,"7z",g=>{var f,y;(y=(f=this.context)==null?void 0:f.onLog)==null||y.call(f,`[EmulatorJSAdapter] Unpacking core: ${g}%`,"info")}),l=o[e.jsName],d=o[e.wasmName];if(!l||!d)throw new Error(`[EmulatorJSAdapter] Archive "${e.bundleName}" is missing required files: ${e.jsName} or ${e.wasmName}`);return X.set(this.id,{js:l,wasm:d}),{jsBytes:l,wasmBytes:d}}async _acquirePpssppAssets(e){var n,o,l,d;if(Y)return Y;const t="/emulatorjs-cores/stable/data/cores/ppsspp-assets.zip",s=e.assetsUrl||t;(o=(n=this.context)==null?void 0:n.onLog)==null||o.call(n,"[EmulatorJSAdapter] Downloading PPSSPP asset package...","info");let r=null;try{const u=await fetch(t);u.ok&&(r=new Uint8Array(await u.arrayBuffer()))}catch{}if(!r){const u=await fetch(s);if(!u.ok)throw new Error(`[EmulatorJSAdapter] Failed to download PPSSPP assets from "${s}"`);r=new Uint8Array(await u.arrayBuffer())}(d=(l=this.context)==null?void 0:l.onLog)==null||d.call(l,"[EmulatorJSAdapter] Unpacking PPSSPP system assets (ZIP)...","info");const i=await I.decompress(r,"zip",u=>{var m,p;(p=(m=this.context)==null?void 0:m.onLog)==null||p.call(m,`[EmulatorJSAdapter] Unpacking assets: ${u}%`,"info")});return Y=i,i}_injectPpssppAssets(e,t){this._ensureDirectories(e,"/PPSSPP"),this._ensureDirectories(e,"/home/web_user/retroarch/userdata/system/PPSSPP");for(const[s,r]of Object.entries(t)){const i=s.replace(/\\/g,"/").replace(/^\.?\/?ppsspp\//i,"");if(!i)continue;if(i.endsWith("/")||s.endsWith("/")){const u=i.replace(/\/$/,"");u&&(this._ensureDirectories(e,`/PPSSPP/${u}`),this._ensureDirectories(e,`/home/web_user/retroarch/userdata/system/PPSSPP/${u}`));continue}const n=`/PPSSPP/${i}`,o=`/home/web_user/retroarch/userdata/system/PPSSPP/${i}`,l=n.substring(0,n.lastIndexOf("/")),d=o.substring(0,o.lastIndexOf("/"));this._ensureDirectories(e,l),this._ensureDirectories(e,d);try{e.writeFile(n,r),e.writeFile(o,r)}catch{}}}_loadScriptTag(e){return new Promise((t,s)=>{var n;(n=this._scriptElement)!=null&&n.parentNode&&(this._scriptElement.parentNode.removeChild(this._scriptElement),this._scriptElement=null);const r=typeof window<"u"?window:globalThis;delete r.EJS_Runtime;const i=document.createElement("script");i.src=e,i.async=!0,i.onload=()=>t(),i.onerror=()=>s(new Error(`[EmulatorJSAdapter] Failed to load core script from ${e}`)),this._scriptElement=i,document.head.appendChild(i)})}_ensureDirectories(e,t){const s=t.split("/").filter(i=>i.length>0);let r="";for(const i of s){r+=`/${i}`;try{e.analyzePath(r).exists||e.mkdir(r)}catch{}}}_sendCommand(e){if(this._module)try{typeof this._module.EmscriptenSendCommand=="function"?this._module.EmscriptenSendCommand(e):typeof this._module.ccall=="function"&&this._module.ccall("EmscriptenSendCommand",null,["string"],[e])}catch{}}_dispatchKeyboardFallback(e,t){var s;if(!this._isDispatchingFallback){this._isDispatchingFallback=!0;try{const i={4:{key:"ArrowUp",code:"ArrowUp",keyCode:38},5:{key:"ArrowDown",code:"ArrowDown",keyCode:40},6:{key:"ArrowLeft",code:"ArrowLeft",keyCode:37},7:{key:"ArrowRight",code:"ArrowRight",keyCode:39},0:{key:"z",code:"KeyZ",keyCode:90},8:{key:"x",code:"KeyX",keyCode:88},1:{key:"a",code:"KeyA",keyCode:65},9:{key:"s",code:"KeyS",keyCode:83},2:{key:"Shift",code:"ShiftRight",keyCode:16},3:{key:"Enter",code:"Enter",keyCode:13},10:{key:"q",code:"KeyQ",keyCode:81},11:{key:"w",code:"KeyW",keyCode:87},100:{key:"h",code:"KeyH",keyCode:72},101:{key:"F2",code:"F2",keyCode:113},102:{key:"F4",code:"F4",keyCode:115}}[e];if(i&&((s=this.context)!=null&&s.canvas)){const n=t?"keydown":"keyup",o=new KeyboardEvent(n,{key:i.key,code:i.code,keyCode:i.keyCode,which:i.keyCode,bubbles:!1,cancelable:!0});o._isRetroKitSynthetic=!0,this.context.canvas.dispatchEvent(o)}}finally{this._isDispatchingFallback=!1}}}_findStateFiles(e){const t=[],s=new Set,r=i=>{if(!s.has(i)){s.add(i);try{if(!e.analyzePath(i).exists)return;const n=e.readdir(i).filter(o=>o!=="."&&o!=="..");for(const o of n){const l=i==="/"?`/${o}`:`${i}/${o}`;try{const d=e.stat(l);(e.isDir?e.isDir(d.mode):(d.mode&16384)!==0)?l!=="/dev"&&l!=="/proc"&&r(l):(l.includes(".state")||l.endsWith(".sav")||l.endsWith(".nv"))&&t.push({path:l,data:new Uint8Array(e.readFile(l))})}catch{}}}catch{}}};return r("/home/web_user/retroarch/userdata/states"),r("/home/web_user/retroarch/userdata/content"),t}}const G=class G{static registerBuiltinCores(){this.registerCore({id:"play",name:"PlayStation 2 (Play!)",system:"ps2",family:"play",extensions:["iso","bin","cso","chd","isz","elf"],needsThreads:!0,capabilities:{saveStates:!1,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!0,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"ppsspp",name:"Sony PlayStation Portable (PPSSPP)",system:"psp",family:"emulatorjs",extensions:["iso","cso","pbp","elf","prx"],needsThreads:!0,needsWebGL2:!0,capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!0,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"azahar",name:"Nintendo 3DS (Azahar / Citra)",system:"3ds",family:"emulatorjs",extensions:["3ds","3dsx","cci","cxi","elf","axf","app","cia"],needsThreads:!0,needsWebGL2:!0,capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!0}}),this.registerCore({id:"desmume",name:"Nintendo DS (DeSmuME)",system:"nds",family:"emulatorjs",extensions:["nds","bin"],needsWebGL2:!0,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!0}}),this.registerCore({id:"melonds",name:"Nintendo DS (melonDS)",system:"nds",family:"emulatorjs",extensions:["nds","bin"],needsWebGL2:!0,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!0}}),this.registerCore({id:"dosbox_pure",name:"MS-DOS (DOSBox Pure)",system:"dos",family:"emulatorjs",extensions:["exe","com","bat","dos","zip","iso","cue"],needsThreads:!0,needsWebGL2:!1,capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!0,shaders:!1,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"yabause",name:"Sega Saturn (Yabause)",system:"saturn",family:"emulatorjs",extensions:["iso","cue","bin","chd","m3u"],needsWebGL2:!0,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!0,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"virtualjaguar",name:"Atari Jaguar (Virtual Jaguar)",system:"jaguar",family:"emulatorjs",extensions:["jag","j64","rom","bin"],needsWebGL2:!1,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"puae",name:"Commodore Amiga (PUAE)",system:"amiga",family:"emulatorjs",extensions:["adf","dms","ipf","hsp","lha","zip"],needsWebGL2:!1,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!0,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"vice_x64sc",name:"Commodore 64 (VICE x64sc)",system:"c64",family:"emulatorjs",extensions:["d64","t64","tap","crt","prg","g64"],needsWebGL2:!1,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!0,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"freeintv",name:"Intellivision (FreeIntv)",system:"intellivision",family:"emulatorjs",extensions:["int","bin","rom"],needsWebGL2:!1,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"a5200",name:"Atari 5200 (a5200)",system:"atari5200",family:"emulatorjs",extensions:["a52","bin","rom"],needsWebGL2:!1,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"prosystem",name:"Atari 7800 (ProSystem)",system:"atari7800",family:"emulatorjs",extensions:["a78","bin"],needsWebGL2:!1,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"same_cdi",name:"Philips CD-i (SAME CD-i)",system:"cdi",family:"emulatorjs",extensions:["iso","chd","cue","bin"],needsWebGL2:!1,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!0}}),this.registerCore({id:"mednafen_pcfx",name:"PC-FX (Mednafen PC-FX)",system:"pcfx",family:"emulatorjs",extensions:["cue","chd","iso","bin"],needsWebGL2:!1,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!0,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"fbneo",name:"Arcade (FinalBurn Neo)",system:"arcade",family:"emulatorjs",extensions:["zip","7z"],needsWebGL2:!1,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"mame2003_plus",name:"Arcade (MAME 2003-Plus)",system:"arcade",family:"emulatorjs",extensions:["zip","7z"],needsWebGL2:!1,needsThreads:!1,capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"ruffle",name:"Adobe Flash (Ruffle)",system:"flash",family:"ruffle",extensions:["swf"],capabilities:{saveStates:!1,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"nestopia",name:"Nintendo NES (Nestopia)",system:"nes",family:"libretro",extensions:["nes","fds","unf"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"fceumm",name:"Nintendo NES (FCEUmm)",system:"nes",family:"libretro",extensions:["nes","fds","unf"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"quicknes",name:"Nintendo NES (QuickNES)",system:"nes",family:"libretro",extensions:["nes"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"snes9x",name:"Super Nintendo (Snes9x)",system:"snes",family:"libretro",extensions:["smc","sfc","fig"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"snes9x2010",name:"Super Nintendo (Snes9x 2010)",system:"snes",family:"libretro",extensions:["smc","sfc"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"snes9x2005",name:"Super Nintendo (Snes9x 2005)",system:"snes",family:"libretro",extensions:["smc","sfc"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"snes9x2002",name:"Super Nintendo (Snes9x 2002)",system:"snes",family:"libretro",extensions:["smc","sfc"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"gambatte",name:"Game Boy / Color (Gambatte)",system:"gb",family:"libretro",extensions:["gb","gbc"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"gearboy",name:"Game Boy / Color (Gearboy)",system:"gb",family:"libretro",extensions:["gb","gbc"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"DoubleCherryGB",name:"Game Boy / Color 2P (DoubleCherryGB)",system:"gb",family:"libretro",extensions:["gb","gbc"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"tgbdual",name:"Game Boy / Color Link (TGB Dual)",system:"gb",family:"libretro",extensions:["gb","gbc"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"mgba",name:"Game Boy Advance (mGBA)",system:"gba",family:"libretro",extensions:["gba"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"vba_next",name:"Game Boy Advance (VBA Next)",system:"gba",family:"libretro",extensions:["gba"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"mednafen_vb",name:"Virtual Boy (Beetle VB)",system:"virtualboy",family:"libretro",extensions:["vb","vboy","bin"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"mupen64plus_next",name:"Nintendo 64 (Mupen64Plus-Next)",system:"n64",family:"emulatorjs",extensions:["n64","z64","v64"],needsThreads:!0,needsWebGL2:!0,capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"parallel_n64",name:"Nintendo 64 (ParaLLEl N64)",system:"n64",family:"emulatorjs",extensions:["n64","z64","v64"],needsThreads:!0,needsWebGL2:!0,capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"love",name:"LÖVE (love.js)",system:"love",family:"love",extensions:["love","zip"],capabilities:{saveStates:!1,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"genesis_plus_gx",name:"Sega Genesis / Mega Drive (Genesis Plus GX)",system:"genesis",family:"libretro",extensions:["md","smd","gen","bin"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!0,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"genesis_plus_gx_wide",name:"Sega Mega Drive Widescreen",system:"genesis",family:"libretro",extensions:["md","smd","gen"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!0,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"picodrive",name:"Sega 32X / Genesis (PicoDrive)",system:"genesis",family:"libretro",extensions:["32x","md","smd","gen"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!0,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"clownmdemu",name:"Sega MD / CD (ClownMDEmu)",system:"genesis",family:"libretro",extensions:["md","smd","gen","bin"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!0,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"gearsystem",name:"Sega Master System / Game Gear (Gearsystem)",system:"mastersystem",family:"libretro",extensions:["sms","gg","sg"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"pcsx_rearmed",name:"PlayStation (PCSX ReARMed)",system:"psx",family:"libretro",extensions:["cue","bin","chd","pbp","m3u"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!0,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"fbneo",name:"Arcade (FinalBurn Neo)",system:"arcade",family:"libretro",extensions:["zip","7z"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"fbalpha2012",name:"Arcade (FB Alpha 2012)",system:"arcade",family:"libretro",extensions:["zip","7z"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"fbalpha2012_cps1",name:"Arcade CPS-1 (FB Alpha 2012)",system:"arcade",family:"libretro",extensions:["zip"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"fbalpha2012_cps2",name:"Arcade CPS-2 (FB Alpha 2012)",system:"arcade",family:"libretro",extensions:["zip"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"fbalpha2012_neogeo",name:"Arcade Neo Geo (FB Alpha 2012)",system:"arcade",family:"libretro",extensions:["zip"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"mame2000",name:"Arcade (MAME 2000)",system:"arcade",family:"libretro",extensions:["zip"],capabilities:{saveStates:!1,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"mame2003",name:"Arcade (MAME 2003)",system:"arcade",family:"libretro",extensions:["zip"],capabilities:{saveStates:!1,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"mame2003_plus",name:"Arcade (MAME 2003-Plus)",system:"arcade",family:"libretro",extensions:["zip"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"dice",name:"Arcade (DICE)",system:"arcade",family:"libretro",extensions:["zip"],capabilities:{saveStates:!1,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"tia",name:"Atari 2600 (Tia)",system:"atari2600",family:"libretro",extensions:["a26","bin"],capabilities:{saveStates:!0,sram:!1,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"handy",name:"Atari Lynx (Handy)",system:"lynx",family:"libretro",extensions:["lnx"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"mednafen_lynx",name:"Atari Lynx (Beetle Lynx)",system:"lynx",family:"libretro",extensions:["lnx"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"mednafen_pce_fast",name:"PC Engine / CD (Beetle PCE FAST)",system:"pce",family:"libretro",extensions:["pce","sgx","cue","chd","ccd"],capabilities:{saveStates:!0,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!0,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:5,pointer:!1}}),this.registerCore({id:"geargrafx",name:"PC Engine (Geargrafx)",system:"pce",family:"libretro",extensions:["pce","sgx"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"quasi88",name:"NEC PC-8800 (QUASI88)",system:"pc88",family:"libretro",extensions:["d88","t88"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"mednafen_ngp",name:"Neo Geo Pocket / Color (Beetle NeoPop)",system:"ngp",family:"libretro",extensions:["ngp","ngc"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"neocd",name:"SNK Neo Geo CD (NeoCD)",system:"neocd",family:"libretro",extensions:["cue","chd","iso"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!0,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"mednafen_wswan",name:"WonderSwan / Color (Beetle Wonderswan)",system:"wswan",family:"libretro",extensions:["ws","wsc"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"tamalibretro",name:"Tamagotchi P1 (TamaLIBretro)",system:"tamagotchi",family:"libretro",extensions:["bin"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"vice_x64",name:"Commodore 64 (VICE x64)",system:"c64",family:"libretro",extensions:["d64","t64","prg","crt","tap"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"vice_x64sc",name:"Commodore 64 Accurate (VICE x64sc)",system:"c64",family:"libretro",extensions:["d64","t64","prg","crt"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"vice_x128",name:"Commodore 128 (VICE x128)",system:"c64",family:"libretro",extensions:["d64","d81","prg"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"vice_xvic",name:"Commodore VIC-20 (VICE xvic)",system:"c64",family:"libretro",extensions:["prg","crt","d64"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"vice_xplus4",name:"Commodore PLUS/4 (VICE xplus4)",system:"c64",family:"libretro",extensions:["prg","d64"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"vice_xpet",name:"Commodore PET (VICE xpet)",system:"c64",family:"libretro",extensions:["prg","d64"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"vice_xscpu64",name:"Commodore SuperCPU (VICE xscpu64)",system:"c64",family:"libretro",extensions:["d64","prg"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"gearcoleco",name:"ColecoVision (Gearcoleco)",system:"colecovision",family:"emulatorjs",extensions:["col","bin","cv"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"vecx",name:"Vectrex (vecx)",system:"vectrex",family:"libretro",extensions:["vec","bin"],capabilities:{saveStates:!0,sram:!1,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"opera",name:"3DO (Opera)",system:"3do",family:"emulatorjs",extensions:["iso","chd","cue"],needsWebGL2:!0,capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!0,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"freechaf",name:"Fairchild Channel F (FreeChaF)",system:"channelf",family:"libretro",extensions:["chf","bin"],capabilities:{saveStates:!0,sram:!1,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"o2em",name:"Magnavox Odyssey2 (O2EM)",system:"odyssey2",family:"libretro",extensions:["bin"],capabilities:{saveStates:!0,sram:!1,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"theodore",name:"Thomson MO/TO (Theodore)",system:"thomson",family:"libretro",extensions:["fd","k7","sap"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"x1",name:"Sharp X1 (X Millennium)",system:"x1",family:"libretro",extensions:["2d","2hd","d88"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"minivmac",name:"Macintosh II (minivmac)",system:"mac",family:"libretro",extensions:["dsk","img"],capabilities:{saveStates:!1,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!0}}),this.registerCore({id:"mu",name:"Palm OS (Mu)",system:"palmos",family:"libretro",extensions:["prc","pqa"],capabilities:{saveStates:!1,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!0}}),this.registerCore({id:"numero",name:"TI-83 (Numero)",system:"ti83",family:"libretro",extensions:["83p","8xp"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"bk",name:"Elektronika BK-0010 (BK)",system:"bk",family:"libretro",extensions:["bin"],capabilities:{saveStates:!0,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"galaksija",name:"Galaksija",system:"galaksija",family:"libretro",extensions:["gtp"],capabilities:{saveStates:!0,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!0}}),this.registerCore({id:"m2000",name:"Philips P2000T (M2000)",system:"p2000",family:"libretro",extensions:["cas"],capabilities:{saveStates:!0,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!0}}),this.registerCore({id:"pico8",name:"PICO-8 (Official Lexaloffle)",system:"pico8",family:"pico8",extensions:["p8","p8.png","png"],capabilities:{saveStates:!1,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!1,maxPlayers:8,pointer:!0}}),this.registerCore({id:"retro8",name:"PICO-8 (Retro8)",system:"pico8",family:"libretro",extensions:["p8","png","p8.png"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"tic80",name:"TIC-80",system:"tic80",family:"libretro",extensions:["tic"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"wasm4",name:"WASM-4",system:"wasm4",family:"libretro",extensions:["wasm"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"ardens",name:"Arduboy (Ardens)",system:"arduboy",family:"libretro",extensions:["hex"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"arduous",name:"Arduboy (Arduous)",system:"arduboy",family:"libretro",extensions:["hex"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"jaxe",name:"CHIP-8 (JAXE)",system:"chip8",family:"libretro",extensions:["ch8"],capabilities:{saveStates:!0,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"lowresnx",name:"LowRes NX",system:"lowresnx",family:"libretro",extensions:["nx"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"uw8",name:"MicroW8",system:"microw8",family:"libretro",extensions:["uw8"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"vaporspec",name:"VaporSpec",system:"vaporspec",family:"libretro",extensions:["vaporspec"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"uzem",name:"Uzebox (Uzem)",system:"uzebox",family:"libretro",extensions:["bin","hex","uze"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"chailove",name:"ChaiLove",system:"chailove",family:"libretro",extensions:["chai","chailove"],capabilities:{saveStates:!1,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"lutro",name:"Lutro",system:"lutro",family:"libretro",extensions:["lutro","lua"],capabilities:{saveStates:!1,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"scummvm",name:"ScummVM",system:"scummvm",family:"libretro",extensions:["scummvm"],capabilities:{saveStates:!1,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!0}}),this.registerCore({id:"prboom",name:"Doom (PrBoom)",system:"doom",family:"libretro",extensions:["wad"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"tyrquake",name:"Quake (TyrQuake)",system:"quake",family:"libretro",extensions:["pak"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"vitaquake2",name:"Quake II (vitaQuake 2)",system:"quake2",family:"libretro",extensions:["pak"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"vitaquake2-rogue",name:"Quake II Ground Zero (vitaQuake 2)",system:"quake2",family:"libretro",extensions:["pak"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"vitaquake2-xatrix",name:"Quake II The Reckoning (vitaQuake 2)",system:"quake2",family:"libretro",extensions:["pak"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"vitaquake2-zaero",name:"Quake II Zaero (vitaQuake 2)",system:"quake2",family:"libretro",extensions:["pak"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0}}),this.registerCore({id:"ecwolf",name:"Wolfenstein 3D (ECWolf)",system:"ecwolf",family:"libretro",extensions:["wl6","n3d","sod"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!0}}),this.registerCore({id:"nxengine",name:"Cave Story (NXEngine)",system:"cavestory",family:"libretro",extensions:["exe","doukutsu"],capabilities:{saveStates:!1,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"xrick",name:"Rick Dangerous (XRick)",system:"xrick",family:"libretro",extensions:["zip"],capabilities:{saveStates:!0,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"mrboom",name:"Mr.Boom Bomberman",system:"mrboom",family:"libretro",extensions:["mrboom"],capabilities:{saveStates:!1,sram:!1,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:8,pointer:!1}}),this.registerCore({id:"jumpnbump",name:"Jump 'n Bump",system:"jumpnbump",family:"libretro",extensions:["dat"],capabilities:{saveStates:!1,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!1}}),this.registerCore({id:"anarch",name:"Anarch",system:"anarch",family:"libretro",extensions:["anarch"],capabilities:{saveStates:!1,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"craft",name:"Minecraft (Craft)",system:"craft",family:"libretro",extensions:["craft"],capabilities:{saveStates:!1,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!0}}),this.registerCore({id:"gong",name:"Gong Pong",system:"gong",family:"libretro",extensions:["gong"],capabilities:{saveStates:!1,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1}}),this.registerCore({id:"2048",name:"2048",system:"2048",family:"libretro",extensions:["2048"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"gw",name:"Game & Watch (GW)",system:"gw",family:"libretro",extensions:["mgw"],capabilities:{saveStates:!0,sram:!0,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!0,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"gam4980",name:"GAM4980",system:"gam4980",family:"libretro",extensions:["gam"],capabilities:{saveStates:!1,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"gme",name:"Game Music Emu",system:"gme",family:"libretro",extensions:["nsf","spc","gym","vgm","gbs"],capabilities:{saveStates:!1,sram:!1,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!1}}),this.registerCore({id:"pocketcdg",name:"PocketCDG",system:"pocketcdg",family:"libretro",extensions:["cdg"],capabilities:{saveStates:!1,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!0,rewind:!1,variableSpeed:!0,maxPlayers:1,pointer:!1}})}static registerCore(a){this._cores.set(a.id,a);const e=this.normalizeSystem(a.system),t=this._systemCores.get(e)||[];t.includes(a.id)||(t.push(a.id),this._systemCores.set(e,t));for(const s of a.extensions){const r=s.toLowerCase().replace(/^\./,"");this._extensionMap.has(r)||this._extensionMap.set(r,a.id)}}static getCore(a){return this._cores.get(a)}static normalizeSystem(a){const e=a.trim().toLowerCase();switch(e){case"ps1":case"psx":case"playstation":case"playstation1":case"sony-playstation":return"psx";case"ps2":case"playstation2":case"sony-playstation-2":return"ps2";case"snes":case"sfc":case"super-nintendo":case"super-famicom":return"snes";case"nes":case"fc":case"famicom":case"nintendo":return"nes";case"gba":case"gameboy-advance":return"gba";case"gb":case"gbc":case"gameboy":case"gameboy-color":return"gb";case"vb":case"virtualboy":case"virtual-boy":return"virtualboy";case"genesis":case"megadrive":case"mega-drive":case"sega-cd":case"32x":return"genesis";case"sms":case"mastersystem":case"master-system":case"gamegear":case"game-gear":case"gg":case"sg1000":return"mastersystem";case"arcade":case"mame":case"fba":case"fbneo":case"cps1":case"cps2":return"arcade";case"atari":case"2600":case"a2600":case"atari2600":return"atari2600";case"lynx":case"atarilynx":return"lynx";case"pce":case"tg16":case"turbografx":case"supergrafx":case"pcecd":return"pce";case"c64":case"commodore":case"c128":case"vic20":return"c64";case"3do":return"3do";case"coleco":case"colecovision":return"colecovision";case"vectrex":return"vectrex";case"ngp":case"ngpc":case"neogeopocket":return"ngp";case"neocd":return"neocd";case"wswan":case"wonderswan":case"wsc":return"wswan";case"doom":case"prboom":return"doom";case"quake":return"quake";case"quake2":return"quake2";case"wolf3d":case"ecwolf":return"ecwolf";case"n64":case"nintendo64":return"n64";case"pico":case"pico8":case"pico-8":return"pico8";case"psp":case"playstationportable":case"playstation-portable":case"sony-psp":return"psp";case"3ds":case"nintendo-3ds":case"n3ds":return"3ds";case"tic80":case"tic-80":return"tic80";case"wasm4":case"wasm-4":return"wasm4";case"flash":case"swf":case"ruffle":return"flash";case"love":case"love2d":case"lovejs":return"love";case"dos":case"msdos":case"ms-dos":case"pc":return"dos";case"saturn":case"segasaturn":case"sega-saturn":return"saturn";case"jaguar":case"atarijaguar":case"atari-jaguar":return"jaguar";case"amiga":case"commodore-amiga":return"amiga";case"intv":case"intellivision":return"intellivision";case"a5200":case"atari5200":case"atari-5200":return"atari5200";case"a7800":case"atari7800":case"atari-7800":return"atari7800";case"pcfx":case"pc-fx":return"pcfx";case"cdi":case"cd-i":case"philips-cdi":return"cdi";default:return e}}static getAllCores(){return Array.from(this._cores.values())}static getCoresForSystem(a){const e=this.normalizeSystem(a);return(this._systemCores.get(e)||[]).map(s=>this._cores.get(s)).filter(Boolean)}static resolveCoreFromFileName(a,e){const t=a.toLowerCase().split("."),s=t[t.length-1];let r;if(t.length>2&&(r=`${t[t.length-2]}.${t[t.length-1]}`),e){const n=this.getCoresForSystem(e);if(n.length>0){if(r){const l=n.find(d=>d.extensions.some(u=>u.toLowerCase().replace(/^\./,"")===r));if(l)return l}const o=n.find(l=>l.extensions.some(d=>d.toLowerCase().replace(/^\./,"")===s));return o||n[0]}}if(s==="chd"||s==="cue"||s==="pbp"){const n=this.getCore("pcsx_rearmed");if(n)return n}if(s==="cso"){const n=this.getCore("ppsspp");if(n)return n}if(r){const n=this._extensionMap.get(r);if(n&&this._cores.has(n))return this._cores.get(n)}const i=this._extensionMap.get(s);return i?this._cores.get(i):void 0}static registerAdapterFactory(a,e){this._factories.set(a,e)}static getAdapterFactory(a){return this._factories.get(a)}};c(G,"_cores",new Map),c(G,"_extensionMap",new Map),c(G,"_systemCores",new Map),c(G,"_factories",new Map),G.registerBuiltinCores();let N=G;class se extends k{constructor(e,t,s,r){super();c(this,"id");c(this,"name");c(this,"system");c(this,"capabilities");c(this,"_module",null);c(this,"_romData",null);c(this,"_romPath","/home/web_user/retroarch/userdata/content/rom.bin");c(this,"_sramPath","/home/web_user/retroarch/userdata/saves/rom.srm");c(this,"_fps",60);c(this,"_coreOptionsMap",{});c(this,"_additionalFiles",[]);c(this,"_started",!1);c(this,"_pendingBios",new Map);c(this,"_isDispatchingFallback",!1);this.id=e,this.name=t,this.system=s,this.capabilities=r}async init(e){await super.init(e)}async loadGame(e,t){var i;if(typeof e=="string"){const n=await fetch(e,{headers:(i=this.context)==null?void 0:i.fetchHeaders});if(!n.ok)throw new Error(`[LibretroAdapter] Failed to fetch ROM from URL: ${e}`);const o=await n.arrayBuffer();this._romData=new Uint8Array(o)}else if(e instanceof Blob){const n=await e.arrayBuffer();this._romData=new Uint8Array(n)}else e instanceof Uint8Array?this._romData=e:this._romData=new Uint8Array(e);let s=(t==null?void 0:t.fileName)||"rom.bin";(this.id==="retro8"||this.system==="pico8")&&s.toLowerCase().endsWith(".png")&&(s=s.replace(/\.p8\.png$/i,".p8").replace(/\.png$/i,".p8")),this._romPath=`/home/web_user/retroarch/userdata/content/${s}`;const r=s.replace(/\.[^.]+$/,"");if(this._sramPath=`/home/web_user/retroarch/userdata/saves/${r}.srm`,this._additionalFiles=[],t!=null&&t.additionalFiles)for(const n of t.additionalFiles){let o;if(n.data instanceof Uint8Array)o=n.data;else if(n.data instanceof ArrayBuffer)o=new Uint8Array(n.data);else if(n.data instanceof Blob){const l=await n.data.arrayBuffer();o=new Uint8Array(l)}else o=new Uint8Array(n.data);this._additionalFiles.push({name:n.name,data:o})}await this._instantiateCoreModule(),t!=null&&t.initialSram&&t.initialSram instanceof Uint8Array&&await this.rawSetSram(t.initialSram),this.start()}start(){if(super.start(),!!this._module){if(this._started)this.resume();else if(this._started=!0,typeof this._module.callMain=="function")try{const e=this._module.arguments||["-v",this._romPath,"-c","/home/web_user/retroarch/userdata/retroarch.cfg"];this._module.callMain(e)}catch(e){e&&e.name!=="ExitStatus"?console.error("[LibretroAdapter] Error starting callMain:",e):e!=null&&e.status&&e.status!==0&&console.error(`[LibretroAdapter] Core exited with code ${e.status}`)}}}pause(){super.pause(),this._module&&(typeof this._module.pauseMainLoop=="function"?this._module.pauseMainLoop():typeof this._module.EmscriptenSendCommand=="function"&&this._module.EmscriptenSendCommand("PAUSE_TOGGLE"))}resume(){if(super.resume(),!this._started){this.start();return}this._module&&(typeof this._module.resumeMainLoop=="function"?this._module.resumeMainLoop():typeof this._module.EmscriptenSendCommand=="function"&&this._module.EmscriptenSendCommand("PAUSE_TOGGLE"))}async stop(){await super.stop(),this._module&&typeof this._module.pauseMainLoop=="function"&&this._module.pauseMainLoop(),await this.rawFlushSram()}async restart(){this._module&&(typeof this._module.EmscriptenSendCommand=="function"?this._module.EmscriptenSendCommand("RESET"):(this._dispatchKeyboardFallback(100,!0),setTimeout(()=>this._dispatchKeyboardFallback(100,!1),50)),this.resume())}async destroy(){var e;if(await super.destroy(),this._module){if(typeof this._module.pauseMainLoop=="function")try{this._module.pauseMainLoop()}catch{}if((e=this._module.PThread)!=null&&e.terminateAllThreads)try{this._module.PThread.terminateAllThreads()}catch{}if(typeof this._module.abort=="function")try{this._module.abort()}catch{}this._module=null}this._romData=null,this._started=!1}async rawSaveState(e=0){var t,s,r,i;if(!this._module)return null;if(this._module.gameManager&&typeof this._module.gameManager.getState=="function"){const n=this._module.gameManager.getState();return n?new Uint8Array(n):null}if(typeof this._module._retro_serialize=="function"&&typeof this._module._retro_serialize_size=="function"){const n=this._module._retro_serialize_size();if(n>0){const o=this._module._malloc(n);if(this._module._retro_serialize(o,n)){const d=new Uint8Array(this._module.HEAPU8.buffer,o,n).slice();return this._module._free(o),d}this._module._free(o)}}if(this._module.FS){const n="/home/web_user/retroarch/userdata/states",o="/home/web_user/retroarch/userdata/content";this._ensureDirectories(this._module.FS,n),this._ensureDirectories(this._module.FS,o);const l=this._findStateFiles(this._module.FS);for(const d of l)try{this._module.FS.unlink(d.path)}catch{}if(typeof this._module.EmscriptenSendCommand=="function"||typeof this._module.ccall=="function"){const d=e>0?`SAVE_STATE_SLOT ${e}`:"SAVE_STATE";this._sendCommand(d)}else this._dispatchKeyboardFallback(101,!0),await new Promise(d=>setTimeout(d,60)),this._dispatchKeyboardFallback(101,!1);for(let d=0;d<40;d++){await new Promise(m=>setTimeout(m,50));const u=this._findStateFiles(this._module.FS);if(u.length>0)return(s=(t=this.context)==null?void 0:t.onLog)==null||s.call(t,`[LibretroAdapter] Captured state snapshot: ${u[0].path} (${u[0].data.byteLength} bytes)`,"info"),u[0].data}(i=(r=this.context)==null?void 0:r.onLog)==null||i.call(r,"[LibretroAdapter] Save state polling timed out. No state file in FS.","warn")}return null}async rawLoadState(e,t=0){var s,r;if(!this._module)return!1;if(this._module.gameManager&&typeof this._module.gameManager.loadState=="function")return this._module.gameManager.loadState(e),!0;if(typeof this._module._retro_unserialize=="function"){const i=this._module._malloc(e.byteLength);this._module.HEAPU8.set(e,i);const n=this._module._retro_unserialize(i,e.byteLength);return this._module._free(i),!!n}if(this._module.FS){const i="/home/web_user/retroarch/userdata/states",n="/home/web_user/retroarch/userdata/content";try{this._ensureDirectories(this._module.FS,i),this._ensureDirectories(this._module.FS,n);const l=(this._romPath.split("/").pop()||"rom.bin").replace(/\.[^.]+$/,"");this._module.FS.writeFile(`${i}/${l}.state`,e),this._module.FS.writeFile(`${i}/${l}.state.auto`,e),this._module.FS.writeFile(`${i}/${l}.state0`,e),this._module.FS.writeFile(`${i}/${l}.state1`,e),t>1&&this._module.FS.writeFile(`${i}/${l}.state${t}`,e),this._module.FS.writeFile(`${n}/${l}.state`,e),this._module.FS.writeFile(`${n}/${l}.state.auto`,e),this._module.FS.writeFile(`${n}/${l}.state0`,e),this._module.FS.writeFile(`${n}/${l}.state1`,e),t>1&&this._module.FS.writeFile(`${n}/${l}.state${t}`,e);const d=this._findStateFiles(this._module.FS);for(const u of d)try{this._module.FS.writeFile(u.path,e)}catch{}if(typeof this._module.EmscriptenSendCommand=="function"||typeof this._module.ccall=="function"){const u=t>0?`LOAD_STATE_SLOT ${t}`:"LOAD_STATE";this._sendCommand(u)}else this._dispatchKeyboardFallback(102,!0),await new Promise(u=>setTimeout(u,60)),this._dispatchKeyboardFallback(102,!1);return(r=(s=this.context)==null?void 0:s.onLog)==null||r.call(s,"[LibretroAdapter] Injected state data into FS and triggered LOAD_STATE","info"),!0}catch(o){console.warn("[LibretroAdapter] Error injecting state into FS:",o)}}return!1}async rawGetSram(){if(!this._module)return null;if(this._module.gameManager&&typeof this._module.gameManager.getSaveFile=="function"){const e=this._module.gameManager.getSaveFile();return e?new Uint8Array(e):null}if(this._module.FS&&this._sramPath)try{if(this._module.FS.analyzePath(this._sramPath).exists){const e=this._module.FS.readFile(this._sramPath);return new Uint8Array(e)}}catch{}return null}async rawSetSram(e){if(!this._module||!(e instanceof Uint8Array))return!1;if(this._module.FS)try{const t=this._sramPath.substring(0,this._sramPath.lastIndexOf("/"));return this._ensureDirectories(this._module.FS,t),this._module.FS.writeFile(this._sramPath,e),this._module.gameManager&&typeof this._module.gameManager.loadSaveFiles=="function"&&this._module.gameManager.loadSaveFiles(),!0}catch(t){console.warn("[LibretroAdapter] Failed to write SRAM to virtual FS:",t)}return!1}async rawFlushSram(){var e;if((e=this._module)!=null&&e.gameManager&&typeof this._module.gameManager.saveSaveFiles=="function")try{this._module.gameManager.saveSaveFiles()}catch{}}getSramPath(){return this._sramPath}async rawSetBios(e,t){var i,n,o;const s=e.replace(/^.*[\\/]/,"");this._pendingBios.set(s,t);const r="/home/web_user/retroarch/userdata/system";(i=this._module)!=null&&i.FS&&(this._ensureDirectories(this._module.FS,r),this._module.FS.writeFile(`${r}/${s}`,t),(o=(n=this.context)==null?void 0:n.onLog)==null||o.call(n,`[LibretroAdapter] Injected BIOS: ${s} (${t.byteLength} bytes)`,"info"))}rawReadMemory(e,t){if(!this._module)return null;try{if(typeof this._module._retro_get_memory_data=="function"){const s=this._module._retro_get_memory_data(0),r=typeof this._module._retro_get_memory_size=="function"?this._module._retro_get_memory_size(0):0;if(s&&r>0&&e+t<=r&&this._module.HEAPU8)return new Uint8Array(this._module.HEAPU8.buffer,s+e,t).slice()}}catch{}return null}rawGetMemorySize(){if(!this._module)return 0;try{if(typeof this._module._retro_get_memory_size=="function")return this._module._retro_get_memory_size(0)}catch{}return 0}rawGetOptions(){var e;if((e=this._module)!=null&&e.gameManager&&typeof this._module.gameManager.getCoreOptions=="function"){const t=this._module.gameManager.getCoreOptions();if(typeof t=="string")return this._parseCoreOptionsString(t)}return[]}rawSetOption(e,t){var s;if(this._coreOptionsMap[e]=t,(s=this._module)!=null&&s.gameManager&&typeof this._module.gameManager.setVariable=="function")try{this._module.gameManager.setVariable(e,t)}catch{}}rawSetCheat(e,t,s){if(this._module&&typeof this._module.cheatChanged=="function")try{this._module.cheatChanged(t,s,e)}catch{}}rawResetCheats(){if(this._module&&typeof this._module._retro_cheat_reset=="function")try{this._module._retro_cheat_reset()}catch{}}rawGetDiscCount(){return 1}async rawChangeDisc(e){var t;if((t=this._module)!=null&&t.gameManager&&typeof this._module.gameManager.loadDisc=="function")try{return this._module.gameManager.loadDisc(e),!0}catch{}return!1}rawSendButton(e,t,s){var r,i,n;(r=this._module)!=null&&r.gamepad&&typeof this._module.gamepad.sendButton=="function"?this._module.gamepad.sendButton(e,t,s):(i=this._module)!=null&&i.gameManager&&typeof this._module.gameManager.simulateInput=="function"?this._module.gameManager.simulateInput(e,t,s?1:0):(n=this._module)!=null&&n.simulateGamepadButton?this._module.simulateGamepadButton(e,t,s):this._dispatchKeyboardFallback(t,s)}_sendCommand(e){if(this._module)try{typeof this._module.EmscriptenSendCommand=="function"?this._module.EmscriptenSendCommand(e):typeof this._module.ccall=="function"&&this._module.ccall("EmscriptenSendCommand",null,["string"],[e])}catch(t){console.warn("[LibretroAdapter] _sendCommand failed for:",e,t)}}_dispatchKeyboardFallback(e,t){var s;if(!this._isDispatchingFallback){this._isDispatchingFallback=!0;try{const i={4:{key:"ArrowUp",code:"ArrowUp",keyCode:38},5:{key:"ArrowDown",code:"ArrowDown",keyCode:40},6:{key:"ArrowLeft",code:"ArrowLeft",keyCode:37},7:{key:"ArrowRight",code:"ArrowRight",keyCode:39},0:{key:"z",code:"KeyZ",keyCode:90},8:{key:"x",code:"KeyX",keyCode:88},1:{key:"a",code:"KeyA",keyCode:65},9:{key:"s",code:"KeyS",keyCode:83},2:{key:"Shift",code:"ShiftRight",keyCode:16},3:{key:"Enter",code:"Enter",keyCode:13},10:{key:"q",code:"KeyQ",keyCode:81},11:{key:"w",code:"KeyW",keyCode:87},100:{key:"h",code:"KeyH",keyCode:72},101:{key:"F2",code:"F2",keyCode:113},102:{key:"F4",code:"F4",keyCode:115}}[e];if(i){const n=t?"keydown":"keyup",o=new KeyboardEvent(n,{key:i.key,code:i.code,keyCode:i.keyCode,which:i.keyCode,bubbles:!1,cancelable:!0});o._isRetroKitSynthetic=!0,(s=this.context)!=null&&s.canvas&&this.context.canvas.dispatchEvent(o)}}finally{this._isDispatchingFallback=!1}}}rawSendAxis(e,t,s){var r,i;if((r=this._module)!=null&&r.gamepad&&typeof this._module.gamepad.sendAxis=="function")this._module.gamepad.sendAxis(e,t,s);else if((i=this._module)!=null&&i.gameManager&&typeof this._module.gameManager.simulateInput=="function"){const o=Math.abs(s),l=o>.05?Math.round(o*32767):0;t===0?(this._module.gameManager.simulateInput(e,16,s>.05?l:0),this._module.gameManager.simulateInput(e,17,s<-.05?l:0)):t===1?(this._module.gameManager.simulateInput(e,18,s>.05?l:0),this._module.gameManager.simulateInput(e,19,s<-.05?l:0)):t===2?(this._module.gameManager.simulateInput(e,20,s>.05?l:0),this._module.gameManager.simulateInput(e,21,s<-.05?l:0)):t===3&&(this._module.gameManager.simulateInput(e,22,s>.05?l:0),this._module.gameManager.simulateInput(e,23,s<-.05?l:0))}}rawGetFps(){return this._fps}async _instantiateCoreModule(){var d,u,m,p,w,h,g;const e=((d=this.context)==null?void 0:d.assetBaseUrl)||"",t=`${e.replace(/\/$/,"")}/${this.id}_libretro.js`,s=`/home/web_user/retroarch/cores/${this.id}_libretro.core`,r="/home/web_user/retroarch/userdata/retroarch.cfg";(u=this.context)!=null&&u.canvas&&!this.context.canvas.id&&(this.context.canvas.id="canvas");const i=!!((m=this.context)!=null&&m.debug),n=i?["-v","-c",r,this._romPath]:["-c",r,this._romPath],o=!!((p=N.getCore(this.id))!=null&&p.needsWebGL2),l={canvas:(w=this.context)==null?void 0:w.canvas,webglContextAttributes:{preserveDrawingBuffer:!0,antialias:!1,powerPreference:"high-performance",majorVersion:o?2:1,minorVersion:0},noInitialRun:!0,arguments:n,corePath:s,locateFile:(f,y)=>e?`${e.replace(/\/$/,"")}/${f}`:(y||"")+f,ENV:{LIBRARY_PATH:s},preRun:[f=>{var y,x,A;if(f.ENV&&(f.ENV.LIBRARY_PATH=s),f.FS){this._ensureDirectories(f.FS,"/home"),this._ensureDirectories(f.FS,"/home/web_user"),this._ensureDirectories(f.FS,"/home/web_user/retroarch"),this._ensureDirectories(f.FS,"/home/web_user/retroarch/cores"),this._ensureDirectories(f.FS,"/home/web_user/retroarch/userdata"),this._ensureDirectories(f.FS,"/home/web_user/retroarch/userdata/content"),this._ensureDirectories(f.FS,"/home/web_user/retroarch/userdata/saves"),this._ensureDirectories(f.FS,"/home/web_user/retroarch/userdata/states"),this._ensureDirectories(f.FS,"/home/web_user/retroarch/userdata/system");try{f.FS.writeFile(s,new Uint8Array)}catch{}for(const[b,C]of this._pendingBios.entries())try{f.FS.writeFile(`/home/web_user/retroarch/userdata/system/${b}`,C),(x=(y=this.context)==null?void 0:y.onLog)==null||x.call(y,`[LibretroAdapter] Flushed queued BIOS: ${b} (${C.byteLength} bytes)`,"info")}catch(R){console.warn("[LibretroAdapter] Failed to flush queued BIOS:",b,R)}const T=['video_driver = "gl"','audio_driver = "rwebaudio"','input_driver = "rwebinput"','video_vsync = "false"','video_smooth = "false"','video_threaded = "false"','video_shared_context = "true"','video_hard_sync = "false"','video_frame_delay = "0"','audio_latency = "64"','audio_sync = "true"','savefile_directory = "/home/web_user/retroarch/userdata/saves"','savestate_directory = "/home/web_user/retroarch/userdata/states"','system_directory = "/home/web_user/retroarch/userdata/system"','content_directory = "/home/web_user/retroarch/userdata/content"','rgui_browser_directory = "/home/web_user/retroarch/userdata/content"','input_enable_hotkey = "nul"','input_enable_hotkey_btn = "nul"','input_enable_hotkey_axis = "nul"','input_save_state = "f2"','input_load_state = "f4"','input_reset = "h"','network_cmd_enable = "true"','stdin_cmd_enable = "false"',""].join(`
3
+ `),F=(A=this.context)==null?void 0:A.retroAchievements;let U=T;F&&F.username&&(U+=['cheevos_enable = "true"',`cheevos_username = "${F.username}"`,`cheevos_token = "${F.token||""}"`,`cheevos_password = "${F.token||""}"`,`cheevos_hardcore_mode_enable = "${F.hardcore?"true":"false"}"`,'cheevos_badges_enable = "true"','cheevos_visibility_summary = "true"','cheevos_visibility_unlock = "true"','cheevos_visibility_mastery = "true"',""].join(`
4
+ `));try{f.FS.writeFile(r,U)}catch{}if(this._romData)try{f.FS.writeFile(this._romPath,this._romData)}catch(b){console.error("[LibretroAdapter] Error writing ROM to virtual FS:",b)}for(const b of this._additionalFiles)try{const C=`/home/web_user/retroarch/userdata/content/${b.name}`;f.FS.writeFile(C,b.data)}catch(C){console.warn("[LibretroAdapter] Error writing companion file:",b.name,C)}}}],stdin:()=>null,print:f=>{var y,x;i&&console.log(`[${this.id}]`,f),(x=(y=this.context)==null?void 0:y.onLog)==null||x.call(y,f,"info")},printErr:f=>{var y,x;i&&console.error(`[${this.id} Err]`,f),(x=(y=this.context)==null?void 0:y.onLog)==null||x.call(y,f,"error")}};try{const f=await import(t),y=f.default||f[this.id]||f;if(typeof y!="function")throw new Error(`Core script at "${t}" did not provide a callable factory function.`);this._module=await y(l)}catch(f){if(t.startsWith("http")&&!t.includes("/libretro-cores/")){const x=`/libretro-cores/${this.id}_libretro.js`;try{const A=await import(x),T=A.default||A[this.id]||A;if(typeof T=="function"){l.locateFile=F=>`/libretro-cores/${F}`,this._module=await T(l);return}}catch(A){console.error("[LibretroAdapter] Proxy fallback failed:",A)}}const y=`Failed to load WASM core from "${t}": ${(f==null?void 0:f.message)||f}`;throw console.error("[LibretroAdapter]",y,f),(g=(h=this.context)==null?void 0:h.onLog)==null||g.call(h,y,"error"),new Error(y)}}_findStateFiles(e){const t=[],s=new Set,r=i=>{if(!s.has(i)){s.add(i);try{if(!e.analyzePath(i).exists)return;const n=e.readdir(i).filter(o=>o!=="."&&o!=="..");for(const o of n){const l=i==="/"?`/${o}`:`${i}/${o}`;try{const d=e.stat(l);if(e.isDir?e.isDir(d.mode):(d.mode&16384)!==0)l!=="/dev"&&l!=="/proc"&&r(l);else if(o.includes(".state")||o.endsWith(".state")){const m=e.readFile(l);m&&m.length>0&&t.push({path:l,data:new Uint8Array(m)})}}catch{}}}catch{}}};return r("/home/web_user/retroarch"),t}_ensureDirectories(e,t){const s=t.split("/").filter(Boolean);let r="";for(const i of s){r+=`/${i}`;try{e.analyzePath(r).exists||e.mkdir(r)}catch{}}}_parseCoreOptionsString(e){var r,i;const t=[],s=e.split(`
5
+ `);for(const n of s){if(!n.trim())continue;const o=n.split(/;\s*/);if(o.length<2)continue;const[l,d]=o[0].split("|"),u=o[1].split("|").map(m=>({value:m.trim(),label:m.trim()}));l&&t.push({id:l.trim(),label:l.trim().replace(/^[^_]+_/,"").replace(/_/g," "),type:"enum",choices:u,defaultValue:((r=u[0])==null?void 0:r.value)||"",currentValue:(d==null?void 0:d.trim())||((i=u[0])==null?void 0:i.value)||""})}return t}}const Ae=`love.js = {}
6
+ local cache = {}
7
+ function love.js.eval(cmd)
8
+ love.system = love.system or require('love.system')
9
+ love.system.openURL('javascript:'..cmd)
10
+ for i = 1, 2^32 do
11
+ local line = io.read()
12
+ if not line then
13
+ break
14
+ end
15
+ cache[i] = line
16
+ end
17
+ local output = table.concat(cache, '\\n')
18
+ for i = #cache, 1, -1 do
19
+ cache[i] = nil
20
+ end
21
+ return output
22
+ end
23
+
24
+ local lfs = love.filesystem
25
+ local _lfs_getInfo = lfs.getInfo
26
+ local _lfs_read = lfs.read
27
+ function lfs.read(fn, ...)
28
+ if not _lfs_getInfo(fn, 'file') then
29
+ return nil, 'File does not exist: '..fn
30
+ end
31
+ return _lfs_read(fn, ...)
32
+ end
33
+
34
+ local _lfs_newFile = lfs.newFileData
35
+ function lfs.newFileData(fn, arg, ...)
36
+ if not arg and not _lfs_getInfo(fn, 'file') then
37
+ return nil, 'File does not exist: '..fn
38
+ end
39
+ return _lfs_newFile(fn, arg, ...)
40
+ end
41
+
42
+ local reg = debug.getregistry()
43
+ if reg then
44
+ local _File_open = reg.File.open
45
+ reg.File.open = function(file, ...)
46
+ local fn = file:getFilename()
47
+ if not _lfs_getInfo(fn) then
48
+ return nil, 'File does not exist: '..fn
49
+ end
50
+ return _File_open(file, ...)
51
+ end
52
+ end
53
+
54
+ function love.js.getWebOS()
55
+ return 'Unknown'
56
+ end
57
+ `,Pe=`if love.event then
58
+ local _love_event_push = love.event.push
59
+ function love.event.push(event, action, ...)
60
+ if event == 'quit' and action == 'reload' then
61
+ love.js.eval('window.location.reload();')
62
+ return
63
+ end
64
+ return _love_event_push(event, action, ...)
65
+ end
66
+ end
67
+
68
+ if love.audio then
69
+ local playing = {}
70
+ local _love_audio_play = love.audio.play
71
+ function love.audio.play(...)
72
+ for i = 1, select("#", ...) do
73
+ local source = select(i, ...)
74
+ if source ~= nil then
75
+ playing[source] = true
76
+ end
77
+ end
78
+ return _love_audio_play(...)
79
+ end
80
+
81
+ local _love_audio_stop = love.audio.stop
82
+ function love.audio.stop(source, ...)
83
+ if source then
84
+ return _love_audio_stop(source, ...)
85
+ end
86
+ for s in pairs(playing) do
87
+ s:stop()
88
+ playing[s] = nil
89
+ end
90
+ end
91
+
92
+ local reg = debug.getregistry()
93
+ if reg then
94
+ local _Source_play = reg.Source.play
95
+ reg.Source.play = function(source, ...)
96
+ local res = _Source_play(source, ...)
97
+ if res then
98
+ playing[source] = true
99
+ end
100
+ return res
101
+ end
102
+ end
103
+ end
104
+
105
+ function love.system.getClipboardText()
106
+ return love.js.eval('window.Module.Browser.getClipboard();');
107
+ end
108
+
109
+ function love.system.setClipboardText(text)
110
+ return love.js.eval('window.Module.Browser.setClipboard();')
111
+ end
112
+
113
+ if love.keyboard then
114
+ local textinput = false
115
+ local _love_keyboard_setTextInput = love.keyboard.setTextInput
116
+ function love.keyboard.setTextInput(enabled)
117
+ local on = not not enabled
118
+ local cmd = string.format('window.Module.Browser.setInput(%s);', tostring(on))
119
+ love.js.eval(cmd)
120
+ textinput = on
121
+ return _love_keyboard_setTextInput(enabled)
122
+ end
123
+
124
+ local _love_keyboard_hasTextInput = love.keyboard.hasTextInput
125
+ function love.keyboard.hasTextInput()
126
+ if textinput == true then
127
+ return true
128
+ end
129
+ return _love_keyboard_hasTextInput()
130
+ end
131
+
132
+ local _love_event_pump = love.event.pump
133
+ function love.event.pump(...)
134
+ local res = love.js.eval('window.Module.Browser.getInput();');
135
+ if res and res ~= '' then
136
+ love.event.push('textinput', res)
137
+ end
138
+ _love_event_pump(...)
139
+ end
140
+ end
141
+ `,J=class J extends k{constructor(){super(...arguments);c(this,"id","love");c(this,"name","LÖVE (love.js)");c(this,"system","love");c(this,"capabilities",{saveStates:!1,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0});c(this,"_module",null);c(this,"_gameData",null);c(this,"_fileName","game.love");c(this,"_fps",60);c(this,"_scriptElement",null);c(this,"_isReady",!1)}get isReady(){return this._isReady}async loadGame(e,t){var s;if(typeof e=="string"){const r=await fetch(e,{headers:(s=this.context)==null?void 0:s.fetchHeaders});if(!r.ok)throw new Error(`[LoveAdapter] Failed to fetch .love from: ${e}`);this._gameData=new Uint8Array(await r.arrayBuffer())}else e instanceof Blob?this._gameData=new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?this._gameData=e:this._gameData=new Uint8Array(e);this._fileName=(t==null?void 0:t.fileName)||"game.love",!this._fileName.toLowerCase().endsWith(".love")&&!this._fileName.toLowerCase().endsWith(".zip")&&(this._fileName+=".love"),await this._instantiateLove(),this.start()}start(){super.start(),this.resume()}pause(){var e,t,s;if(super.pause(),(s=(t=(e=this._module)==null?void 0:e.Browser)==null?void 0:t.mainLoop)!=null&&s.pause)try{this._module.Browser.mainLoop.pause()}catch{}}resume(){var e,t,s;if(super.resume(),(s=(t=(e=this._module)==null?void 0:e.Browser)==null?void 0:t.mainLoop)!=null&&s.resume)try{this._module.Browser.mainLoop.resume()}catch{}}async stop(){this.pause(),await super.stop()}async restart(){this._gameData&&(await this.destroy(),await this.loadGame(this._gameData,{fileName:this._fileName}))}async destroy(){var e;if(this.pause(),this._module){if(typeof this._module.exit=="function")try{this._module.exit(0)}catch{}this._module=null}if((e=this._scriptElement)!=null&&e.parentNode&&(this._scriptElement.parentNode.removeChild(this._scriptElement),this._scriptElement=null),typeof window<"u")try{delete window.Love,delete window.Module}catch{window.Love=void 0,window.Module=void 0}this._gameData=null,this._isReady=!1,await super.destroy()}rawSendButton(e,t,s){var d;const r=J.RETROPAD_TO_KEY[t];if(!r)return;const i=s?"keydown":"keyup",n={key:r.key,code:r.code,bubbles:!0,cancelable:!0},l=((d=this.context)==null?void 0:d.canvas)||(typeof window<"u"?window:null);if(l)try{const u=new KeyboardEvent(i,n);l.dispatchEvent(u)}catch{}}rawSendAxis(e,t,s){t===0?s>.5?(this.rawSendButton(e,7,!0),this.rawSendButton(e,6,!1)):s<-.5?(this.rawSendButton(e,6,!0),this.rawSendButton(e,7,!1)):(this.rawSendButton(e,6,!1),this.rawSendButton(e,7,!1)):t===1&&(s>.5?(this.rawSendButton(e,5,!0),this.rawSendButton(e,4,!1)):s<-.5?(this.rawSendButton(e,4,!0),this.rawSendButton(e,5,!1)):(this.rawSendButton(e,4,!1),this.rawSendButton(e,5,!1)))}rawGetFps(){return this._fps}async rawGetSram(){var o;const e=typeof window<"u"?window:null;if(!((o=e==null?void 0:e.Module)!=null&&o.FS))return null;const t=e.Module.FS,s={},r="/home/web_user/.local/share/love",i=l=>{try{if(!t.analyzePath(l).exists)return;const d=t.readdir(l);for(const u of d){if(u==="."||u==="..")continue;const m=`${l}/${u}`;try{const p=t.stat(m);t.isDir(p.mode)?i(m):s[m]=new Uint8Array(t.readFile(m))}catch{}}}catch{}};i(r);const n=Object.keys(s);return n.length===0?null:n.length===1?s[n[0]]:s}async rawSetSram(e){var r;const t=typeof window<"u"?window:null;if(!((r=t==null?void 0:t.Module)!=null&&r.FS))return!1;const s=t.Module.FS;if(e instanceof Uint8Array){const i=this._fileName.replace(/\.(love|zip)$/i,""),n=`/home/web_user/.local/share/love/${i}/save.dat`;try{return this._ensureDirectoryExists(s,`/home/web_user/.local/share/love/${i}`),s.writeFile(n,e),await this.rawFlushSram(),!0}catch(o){return console.error("[LoveAdapter] Failed writing raw SRAM:",o),!1}}for(const[i,n]of Object.entries(e))try{const o=i.lastIndexOf("/");o>0&&this._ensureDirectoryExists(s,i.slice(0,o)),s.writeFile(i,n)}catch(o){console.error(`[LoveAdapter] Failed writing file ${i}:`,o)}return await this.rawFlushSram(),!0}async rawFlushSram(){var s;const e=typeof window<"u"?window:null,t=(s=e==null?void 0:e.Module)==null?void 0:s.FS;!t||typeof t.syncfs!="function"||await new Promise(r=>{try{t.syncfs(!1,()=>r())}catch{r()}})}rawGetOptions(){return[]}_ensureDirectoryExists(e,t){const s=t.split("/").filter(Boolean);let r="";for(const i of s){r+=`/${i}`;try{e.analyzePath(r).exists||e.mkdir(r)}catch{}}}async _instantiateLove(){var y,x,A,T,F,U;const e=(y=this.context)==null?void 0:y.canvas;if(!e)throw new Error("[LoveAdapter] Target canvas is required");e.id||(e.id="canvas"),(A=(x=this.context)==null?void 0:x.onLog)==null||A.call(x,"[LoveAdapter] Fetching love.js and love.wasm...","info");const t="/love-cores/love.js",s="https://cdn.jsdelivr.net/gh/2dengine/love.js@main/11.5/love.js",r="/love-cores/love.wasm",i="https://cdn.jsdelivr.net/gh/2dengine/love.js@main/11.5/love.wasm";let n=null;try{const b=await fetch(r);b.ok&&(n=await b.arrayBuffer())}catch{}if(!n){const b=await fetch(i);if(!b.ok)throw new Error("[LoveAdapter] Failed to fetch love.wasm");n=await b.arrayBuffer()}const o=!!((T=this.context)!=null&&T.debug),l=this._gameData||new Uint8Array,d=this._fileName,u=new TextEncoder,m=u.encode(Ae),p=u.encode(Pe),w=typeof navigator<"u"&&navigator.deviceMemory?navigator.deviceMemory*1e9:1e9,h=Math.min(4*l.length+2e7,w),g={canvas:e,arguments:[d],args:[d],cache:{[d]:l,"lua/normalize1.lua":m,"lua/normalize2.lua":p,"11.5/love.wasm":n},INITIAL_MEMORY:h,print:b=>{var C,R;o&&console.log("[love.js]",b),(R=(C=this.context)==null?void 0:C.onLog)==null||R.call(C,b,"info")},printErr:b=>{var C,R;o&&console.error("[love.js Err]",b),(R=(C=this.context)==null?void 0:C.onLog)==null||R.call(C,b,"error")},prerun:()=>{try{g.FS&&(g.FS.mkdirTree("/usr/local/share/lua/5.1"),g.FS.createDataFile("/",d,l,!0,!0,!0),g.FS.createDataFile("/usr/local/share/lua/5.1","normalize1.lua",m,!0,!0,!0),g.FS.createDataFile("/usr/local/share/lua/5.1","normalize2.lua",p,!0,!0,!0))}catch(b){console.warn("[LoveAdapter] Error mounting files in FS:",b)}},postrun:()=>{this._isReady=!0,e.focus()}};if(typeof window<"u"){const b=window;b.Module=g,b._origOpen||(b._origOpen=b.open.bind(b),b.open=C=>{if(typeof C=="string"&&C.startsWith("javascript:")){const R=C.substring(11);try{b._output=window.eval(R)}catch(z){console.warn("[LoveAdapter] eval error in openURL:",z)}return null}return b._origOpen(C)}),b._output=null,b.prompt=()=>{const C=b._output;return b._output=null,C}}if(typeof window.Love!="function")try{await this._loadScript(t)}catch{await this._loadScript(s)}const f=window.Love;if(typeof f!="function")throw new Error("[LoveAdapter] love.js did not export window.Love");this._module=await f(g),(U=(F=this.context)==null?void 0:F.onLog)==null||U.call(F,"[LoveAdapter] LÖVE runtime initialized successfully","info")}_loadScript(e){return new Promise((t,s)=>{const r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>t(),r.onerror=i=>s(new Error(`[LoveAdapter] Failed to load script ${e}: ${i}`)),this._scriptElement=r,document.body.appendChild(r)})}};c(J,"RETROPAD_TO_KEY",{0:{key:"x",code:"KeyX",keyCode:88},1:{key:"s",code:"KeyS",keyCode:83},2:{key:" ",code:"Space",keyCode:32},3:{key:"Enter",code:"Enter",keyCode:13},4:{key:"ArrowUp",code:"ArrowUp",keyCode:38},5:{key:"ArrowDown",code:"ArrowDown",keyCode:40},6:{key:"ArrowLeft",code:"ArrowLeft",keyCode:37},7:{key:"ArrowRight",code:"ArrowRight",keyCode:39},8:{key:"z",code:"KeyZ",keyCode:90},9:{key:"a",code:"KeyA",keyCode:65}});let K=J;const P=class P extends k{constructor(){super(...arguments);c(this,"id","pico8");c(this,"name","PICO-8 (Official Lexaloffle)");c(this,"system","pico8");c(this,"capabilities",{saveStates:!1,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!1,maxPlayers:8,pointer:!0});c(this,"_scriptElement",null);c(this,"_textareaElement",null);c(this,"_createdBlobUrls",[]);c(this,"_currentCartName","cart.p8.png");c(this,"_lastFrameNumber",0);c(this,"_lastFpsCalcTime",0);c(this,"_currentFps",0);c(this,"_isReady",!1)}get isReady(){return this._isReady}async init(e){await super.init(e),this._ensureDOMTextarea(),this._ensureGlobalState()}async loadGame(e,t){const s=(t==null?void 0:t.fileName)||"cart.p8.png";this._currentCartName=s;const r=s.toLowerCase().endsWith(".png")||e instanceof Uint8Array&&this._isPngSignature(e),i=await this._getRomBytes(e),n=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);let o;if(typeof e=="string"&&(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://")))o=e;else{const l=r?"image/png":"text/plain;charset=utf-8",d=new Blob([n],{type:l});o=URL.createObjectURL(d),this._createdBlobUrls.push(o)}await this._bootPico8(o,s,n),this.start()}start(){var t;super.start();const e=this._getGlobalWindow();if((t=e.Module)!=null&&t.pico8SetPaused)try{e.Module.pico8SetPaused(!1)}catch{}else e.codo_command===0&&(e.codo_command=5,e.codo_command_p=0)}pause(){var t;super.pause();const e=this._getGlobalWindow();if((t=e.Module)!=null&&t.pico8SetPaused)try{e.Module.pico8SetPaused(!0)}catch{}else e.codo_command===0&&(e.codo_command=5,e.codo_command_p=1)}resume(){var t;super.resume();const e=this._getGlobalWindow();if((t=e.Module)!=null&&t.pico8SetPaused)try{e.Module.pico8SetPaused(!1)}catch{}else e.codo_command===0&&(e.codo_command=5,e.codo_command_p=0)}async stop(){this.pause(),await super.stop()}async restart(){var t;const e=this._getGlobalWindow();if((t=e.Module)!=null&&t.pico8Reset)try{e.Module.pico8Reset()}catch{}else e.codo_command=1}async destroy(){await this.stop(),this._scriptElement&&this._scriptElement.parentNode&&(this._scriptElement.parentNode.removeChild(this._scriptElement),this._scriptElement=null),this._textareaElement&&this._textareaElement.parentNode&&(this._textareaElement.parentNode.removeChild(this._textareaElement),this._textareaElement=null);for(const t of this._createdBlobUrls)try{URL.revokeObjectURL(t)}catch{}this._createdBlobUrls=[];const e=this._getGlobalWindow();delete e.Module,delete e._cartdat,delete e._cartname,delete e._cdpos,e.pico8_buttons=[0,0,0,0,0,0,0,0],e.pico8_state={},e.codo_command=0,this._isReady=!1,await super.destroy()}rawSendButton(e,t,s){if(e<0||e>=8)return;const r=P.RETROPAD_TO_PICO8[t];if(!r)return;this._ensureGlobalState();const i=this._getGlobalWindow();s?i.pico8_buttons[e]|=r:i.pico8_buttons[e]&=~r}rawSendAxis(e,t,s){t===0?s>.5?(this.rawSendButton(e,7,!0),this.rawSendButton(e,6,!1)):s<-.5?(this.rawSendButton(e,6,!0),this.rawSendButton(e,7,!1)):(this.rawSendButton(e,6,!1),this.rawSendButton(e,7,!1)):t===1&&(s>.5?(this.rawSendButton(e,5,!0),this.rawSendButton(e,4,!1)):s<-.5?(this.rawSendButton(e,4,!0),this.rawSendButton(e,5,!1)):(this.rawSendButton(e,4,!1),this.rawSendButton(e,5,!1)))}rawGetFps(){var i;const t=((i=this._getGlobalWindow().pico8_state)==null?void 0:i.frame_number)||0,s=performance.now(),r=s-this._lastFpsCalcTime;if(r>=1e3){const n=t-this._lastFrameNumber;this._currentFps=n*1e3/r,this._lastFrameNumber=t,this._lastFpsCalcTime=s}return Math.max(0,Math.round(this._currentFps))}async rawGetSram(){var n;const e=this._getGlobalWindow();if(!((n=e.Module)!=null&&n.FS))return null;const t=e.Module.FS,s={},r=["/user_data/cdata","/user_data/cstore"];for(const o of r)try{if(t.analyzePath(o).exists){const l=t.readdir(o);for(const d of l){if(d==="."||d==="..")continue;const u=`${o}/${d}`;try{const m=t.readFile(u);s[u]=new Uint8Array(m)}catch{}}}}catch{}const i=Object.keys(s);return i.length===0?new Uint8Array(256):i.length===1?s[i[0]]:s}async rawSetSram(e){var r;const t=this._getGlobalWindow();if(!((r=t.Module)!=null&&r.FS))return!1;const s=t.Module.FS;if(e instanceof Uint8Array){let i=null;try{if(s.analyzePath("/user_data/cdata").exists){const n=s.readdir("/user_data/cdata");for(const o of n)if(o.endsWith(".pdat")){i=`/user_data/cdata/${o}`;break}}}catch{}i||(i=`/user_data/cdata/${this._currentCartName.replace(/\.(p8\.png|p8|png)$/i,"").split("/").pop()||"cart"}.pdat`);try{return this._ensureDirectoryExists(s,"/user_data/cdata"),s.writeFile(i,e),await this.rawFlushSram(),!0}catch(n){return console.error("[Pico8Adapter] Failed writing SRAM buffer:",n),!1}}for(const[i,n]of Object.entries(e))try{const o=i.lastIndexOf("/");if(o>0){const l=i.slice(0,o);this._ensureDirectoryExists(s,l)}s.writeFile(i,n)}catch(o){console.error(`[Pico8Adapter] Failed writing SRAM file ${i}:`,o)}return await this.rawFlushSram(),!0}async rawFlushSram(){var s;const t=(s=this._getGlobalWindow().Module)==null?void 0:s.FS;!t||typeof t.syncfs!="function"||await new Promise(r=>{try{t.syncfs(!1,i=>{i&&console.warn("[Pico8Adapter] FS.syncfs failed:",i),r()})}catch(i){console.warn("[Pico8Adapter] FS.syncfs exception:",i),r()}})}getSramPath(){return`/user_data/cdata/${this._currentCartName.replace(/\.(p8\.png|p8|png)$/i,"").split("/").pop()||"cart"}.pdat`}rawGetOptions(){return[]}_getGlobalWindow(){return typeof window<"u"?window:globalThis}_ensureDOMTextarea(){if(typeof document>"u")return;let e=document.getElementById("codo_textarea");e||(e=document.createElement("textarea"),e.id="codo_textarea",e.className="emscripten",e.style.cssText="display:none;position:absolute;left:-9999px;height:0;overflow:hidden;",document.body.appendChild(e),this._textareaElement=e)}_ensureGlobalState(){var t;const e=this._getGlobalWindow();(!e.pico8_buttons||!Array.isArray(e.pico8_buttons))&&(e.pico8_buttons=[0,0,0,0,0,0,0,0]),e.pico8_state||(e.pico8_state={}),e.pico8_gamepads||(e.pico8_gamepads={count:0}),e.pico8_gpio||(e.pico8_gpio=new Array(128)),(t=this.context)!=null&&t.audioContext&&!e.pico8_audio_context&&(e.pico8_audio_context=this.context.audioContext),typeof document<"u"&&(e.codo_textarea=document.getElementById("codo_textarea")||this._textareaElement)}_ensureDirectoryExists(e,t){const s=t.split("/").filter(Boolean);let r="";for(const i of s){r+=`/${i}`;try{e.analyzePath(r).exists||e.mkdir(r)}catch{}}}_isPngSignature(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10}async _getRomBytes(e){var t;if(typeof e=="string"){if(e.startsWith("data:")){const r=e.indexOf(","),i=r>=0?e.slice(r+1):e,n=atob(i),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);return o}if(e.includes("pico-8 cartridge")||e.includes("__lua__"))return new TextEncoder().encode(e);const s=await fetch(e,{headers:(t=this.context)==null?void 0:t.fetchHeaders});if(!s.ok)throw new Error(`[Pico8Adapter] Failed to fetch cartridge from ${e}`);return new Uint8Array(await s.arrayBuffer())}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}async _bootPico8(e,t,s){var u,m,p,w;const r=(u=this.context)==null?void 0:u.canvas;r&&(r.style.imageRendering="pixelated",r.width=128,r.height=128),this._scriptElement&&this._scriptElement.parentNode&&(this._scriptElement.parentNode.removeChild(this._scriptElement),this._scriptElement=null),this._ensureDOMTextarea(),this._ensureGlobalState();const i=this._getGlobalWindow();delete i._cartdat,delete i._cartname,delete i._cdpos;const n=!!((m=this.context)!=null&&m.debug),o={canvas:r,arguments:[e],readAsync:(h,g,f)=>{if(h===e||h===t||h.endsWith(t)||h.includes(t)){g(s);return}fetch(h).then(y=>{if(!y.ok)throw new Error(`HTTP ${y.status}`);return y.arrayBuffer()}).then(g).catch(y=>{f&&f(y)})},print:h=>{var g,f;n&&console.log("[PICO-8]",h),(f=(g=this.context)==null?void 0:g.onLog)==null||f.call(g,h,"info")},printErr:h=>{var g,f;n&&console.error("[PICO-8 Err]",h),(f=(g=this.context)==null?void 0:g.onLog)==null||f.call(g,h,"error")},onRuntimeInitialized:()=>{this._isReady=!0}};i.Module=o;const l=(w=(p=this.context)==null?void 0:p.assetBaseUrl)!=null&&w.includes("pico8")?this.context.assetBaseUrl:"/pico8",d=l.endsWith(".js")?l:`${l.replace(/\/$/,"")}/pico8.js`;return new Promise((h,g)=>{const f=document.createElement("script");f.src=d,f.async=!0,this._scriptElement=f;const y=setTimeout(()=>{h()},4e3);o.onRuntimeInitialized=()=>{clearTimeout(y),this._isReady=!0,h()},f.onerror=x=>{clearTimeout(y),g(new Error(`[Pico8Adapter] Failed to load PICO-8 runtime: ${x}`))},document.body.appendChild(f)})}};c(P,"BUTTON_LEFT",1),c(P,"BUTTON_RIGHT",2),c(P,"BUTTON_UP",4),c(P,"BUTTON_DOWN",8),c(P,"BUTTON_O",16),c(P,"BUTTON_X",32),c(P,"BUTTON_MENU",64),c(P,"RETROPAD_TO_PICO8",{0:P.BUTTON_O,1:P.BUTTON_X,2:P.BUTTON_MENU,3:P.BUTTON_MENU,4:P.BUTTON_UP,5:P.BUTTON_DOWN,6:P.BUTTON_LEFT,7:P.BUTTON_RIGHT,8:P.BUTTON_X,9:P.BUTTON_O});let H=P;class ke{constructor(a){c(this,"module");c(this,"doneFlag",!1);c(this,"file",null);this.module=a}read(a,e,t){this.file&&(this.doneFlag=!1,this.file.slice(e,e+t).arrayBuffer().then(s=>{this.module.HEAPU8.set(new Uint8Array(s),a),this.doneFlag=!0}).catch(s=>{console.error("[PlayAdapter] Error reading disc chunk:",s),this.doneFlag=!0}))}getFileSize(){return this.file?this.file.size:0}isDone(){return this.doneFlag}setFile(a){this.file=a}}class ae extends k{constructor(){super(...arguments);c(this,"id","play");c(this,"name","PlayStation 2 (Play!)");c(this,"system","ps2");c(this,"capabilities",{saveStates:!1,sram:!0,cheats:!0,coreOptions:!0,multiDisc:!0,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:2,pointer:!1});c(this,"_playModule",null);c(this,"_romBlob",null);c(this,"_mcMemory",new Map);c(this,"PS2_KEY_MAP",{0:{code:"KeyZ",key:"z",keyCode:90},8:{code:"KeyX",key:"x",keyCode:88},1:{code:"KeyA",key:"a",keyCode:65},9:{code:"KeyS",key:"s",keyCode:83},2:{code:"Backspace",key:"Backspace",keyCode:8},3:{code:"Enter",key:"Enter",keyCode:13},4:{code:"ArrowUp",key:"ArrowUp",keyCode:38},5:{code:"ArrowDown",key:"ArrowDown",keyCode:40},6:{code:"ArrowLeft",key:"ArrowLeft",keyCode:37},7:{code:"ArrowRight",key:"ArrowRight",keyCode:39},10:{code:"Key1",key:"1",keyCode:49},12:{code:"Key2",key:"2",keyCode:50},14:{code:"Key3",key:"3",keyCode:51},11:{code:"Key8",key:"8",keyCode:56},13:{code:"Key9",key:"9",keyCode:57},15:{code:"Key0",key:"0",keyCode:48},16:{code:"KeyH",key:"h",keyCode:72},17:{code:"KeyF",key:"f",keyCode:70},18:{code:"KeyG",key:"g",keyCode:71},19:{code:"KeyT",key:"t",keyCode:84},20:{code:"KeyL",key:"l",keyCode:76},21:{code:"KeyJ",key:"j",keyCode:74},22:{code:"KeyK",key:"k",keyCode:75},23:{code:"KeyI",key:"i",keyCode:73}})}getRomBlob(){return this._romBlob}async init(e){await super.init(e)}async loadGame(e,t){var r;const s=(t==null?void 0:t.fileName)||"game.iso";if(typeof e=="string"){const i=await fetch(e,{headers:(r=this.context)==null?void 0:r.fetchHeaders});if(!i.ok)throw new Error(`[PlayAdapter] Failed to fetch PS2 ROM from ${e}`);this._romBlob=await i.blob()}else e instanceof Blob?this._romBlob=e:e instanceof Uint8Array?this._romBlob=new Blob([e.buffer]):this._romBlob=new Blob([e]);if(await this._instantiatePlayRuntime(),!this._playModule)throw new Error("[PlayAdapter] Play! runtime failed to initialize.");if(s.toLowerCase().endsWith(".elf")){const i=await this._romBlob.arrayBuffer(),n=new Uint8Array(i),o=this._playModule.FS.open(s,"w+");this._playModule.FS.write(o,n,0,n.length,0),this._playModule.FS.close(o),typeof this._playModule.bootElf=="function"&&this._playModule.bootElf(s)}else this._playModule.discImageDevice.setFile(this._romBlob),typeof this._playModule.bootDiscImage=="function"&&this._playModule.bootDiscImage(s);t!=null&&t.initialSram&&typeof t.initialSram=="object"&&!(t.initialSram instanceof Uint8Array)&&await this.rawSetSram(t.initialSram),this.start()}start(){if(super.start(),this._playModule&&typeof this._playModule.resumeMainLoop=="function")try{this._playModule.resumeMainLoop()}catch{}}pause(){if(super.pause(),this._playModule&&typeof this._playModule.pauseMainLoop=="function")try{this._playModule.pauseMainLoop()}catch{}}resume(){if(super.resume(),this._playModule&&typeof this._playModule.resumeMainLoop=="function")try{this._playModule.resumeMainLoop()}catch{}}async stop(){if(await super.stop(),this._playModule&&typeof this._playModule.pauseMainLoop=="function")try{this._playModule.pauseMainLoop()}catch{}}async destroy(){var e;if(await super.destroy(),(e=this.context)!=null&&e.canvas&&this.context.canvas.id==="outputCanvas"&&(this.context.canvas.id="canvas"),this._playModule){if(typeof this._playModule.pauseMainLoop=="function")try{this._playModule.pauseMainLoop()}catch{}if(typeof this._playModule.abort=="function")try{this._playModule.abort()}catch{}this._playModule=null}this._romBlob=null,this._mcMemory.clear()}async rawGetSram(){if(!this._playModule||!this._playModule.FS)return null;const e=this._playModule.FS,t={},s="/work/mc0";try{if(e.analyzePath(s).exists){const r=e.readdir(s);for(const i of r){if(i==="."||i==="..")continue;const n=`${s}/${i}`;try{const o=e.readFile(n);t[i]=new Uint8Array(o)}catch{}}}}catch{}return Object.keys(t).length>0?t:null}async rawSetSram(e){if(!this._playModule||!this._playModule.FS||e instanceof Uint8Array)return!1;const t=this._playModule.FS,s="/work/mc0";try{t.analyzePath(s).exists||(t.mkdir("/work"),t.mkdir(s));for(const[r,i]of Object.entries(e))t.writeFile(`${s}/${r}`,i);return!0}catch(r){return console.warn("[PlayAdapter] Failed to restore memory card:",r),!1}}async rawFlushSram(){var t;const e=await this.rawGetSram();e&&((t=this.context)!=null&&t.onSramDirty)&&this.context.onSramDirty(e)}getSramPath(){return"/work/mc0"}rawGetOptions(){return[{id:"widescreen",label:"Widescreen (16:9)",type:"boolean",choices:[{value:"true",label:"Enabled"},{value:"false",label:"Disabled"}],defaultValue:"false",currentValue:"false"},{id:"fastboot",label:"Fast Boot (Skip BIOS)",type:"boolean",choices:[{value:"true",label:"Enabled"},{value:"false",label:"Disabled"}],defaultValue:"true",currentValue:"true"}]}rawSetOption(e,t){if(this._playModule&&typeof this._playModule.setOption=="function")try{this._playModule.setOption(e,t)}catch{}}rawSendButton(e,t,s){var i;if((i=this._playModule)!=null&&i.sendGamepadButton){this._playModule.sendGamepadButton(t,s);return}const r=this.PS2_KEY_MAP[t];r&&this._simulateCanvasKey(r,s)}rawSendAxis(e,t,s){var i;if((i=this._playModule)!=null&&i.sendGamepadAxis){this._playModule.sendGamepadAxis(t,s);return}const r=.2;t===0?(this._simulateCanvasKey(this.PS2_KEY_MAP[16],s>r),this._simulateCanvasKey(this.PS2_KEY_MAP[17],s<-r)):t===1?(this._simulateCanvasKey(this.PS2_KEY_MAP[18],s>r),this._simulateCanvasKey(this.PS2_KEY_MAP[19],s<-r)):t===2?(this._simulateCanvasKey(this.PS2_KEY_MAP[20],s>r),this._simulateCanvasKey(this.PS2_KEY_MAP[21],s<-r)):t===3&&(this._simulateCanvasKey(this.PS2_KEY_MAP[22],s>r),this._simulateCanvasKey(this.PS2_KEY_MAP[23],s<-r))}_simulateCanvasKey(e,t){var n;const s=(n=this.context)==null?void 0:n.canvas;if(!s)return;const r=t?"keydown":"keyup",i=new KeyboardEvent(r,{code:e.code,key:e.key,keyCode:e.keyCode,which:e.keyCode,charCode:e.keyCode,bubbles:!1,cancelable:!0});try{Object.defineProperty(i,"code",{get:()=>e.code,configurable:!0}),Object.defineProperty(i,"keyCode",{get:()=>e.keyCode,configurable:!0}),Object.defineProperty(i,"which",{get:()=>e.keyCode,configurable:!0})}catch{}s.dispatchEvent(i)}async _instantiatePlayRuntime(){var r,i,n,o,l,d;const e=(i=(r=this.context)==null?void 0:r.assetBaseUrl)!=null&&i.includes("play-cores")?this.context.assetBaseUrl:"/play-cores",t=`${e.replace(/\/$/,"")}/Play.js`;(n=this.context)!=null&&n.canvas&&(this.context.canvas.id="outputCanvas");const s={canvas:(o=this.context)==null?void 0:o.canvas,mainScriptUrlOrBlob:t,locateFile:u=>`${e.replace(/\/$/,"")}/${u}`,preRun:[u=>{if(u.FS){try{u.FS.mkdir("/work")}catch{}try{u.FS.mkdir("/work/mc0")}catch{}}}],print:u=>{var m,p,w;(m=this.context)!=null&&m.debug&&console.log("[Play!]",u),(w=(p=this.context)==null?void 0:p.onLog)==null||w.call(p,u,"info")},printErr:u=>{var m,p,w;(m=this.context)!=null&&m.debug&&console.error("[Play! Err]",u),(w=(p=this.context)==null?void 0:p.onLog)==null||w.call(p,u,"error")}};try{const u=await import(t),p=await(u.default||u.Play||u)(s);try{p.FS.mkdir("/work")}catch{}if(p.discImageDevice=new ke(p),typeof p.ccall=="function")try{p.ccall("initVm","",[],[])}catch{}else if(typeof p._initVm=="function")try{p._initVm()}catch{}this._playModule=p}catch(u){const m=`Failed to load Play! PS2 runtime from "${t}": ${(u==null?void 0:u.message)||u}`;throw console.error("[PlayAdapter]",m,u),(d=(l=this.context)==null?void 0:l.onLog)==null||d.call(l,m,"error"),new Error(m)}}}class re extends k{constructor(){super(...arguments);c(this,"id","ruffle");c(this,"name","Adobe Flash (Ruffle)");c(this,"system","flash");c(this,"capabilities",{saveStates:!1,sram:!0,cheats:!1,coreOptions:!0,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!0,maxPlayers:4,pointer:!0});c(this,"_player",null);c(this,"_swfBuffer",null)}async init(e){await super.init(e)}async loadGame(e,t){var s;if(typeof e=="string"){const r=await fetch(e,{headers:(s=this.context)==null?void 0:s.fetchHeaders});if(!r.ok)throw new Error(`[RuffleAdapter] Failed to fetch SWF from ${e}`);this._swfBuffer=await r.arrayBuffer()}else e instanceof Blob?this._swfBuffer=await e.arrayBuffer():e instanceof Uint8Array?this._swfBuffer=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):this._swfBuffer=e;await this._instantiateRuffle(),this._player&&this._swfBuffer&&await this._player.load({data:this._swfBuffer}),this.start()}start(){super.start(),this._player&&typeof this._player.play=="function"&&this._player.play()}pause(){super.pause(),this._player&&typeof this._player.pause=="function"&&this._player.pause()}resume(){super.resume(),this._player&&typeof this._player.play=="function"&&this._player.play()}async stop(){await super.stop(),this._player&&typeof this._player.pause=="function"&&this._player.pause()}async destroy(){if(await super.destroy(),this._player){if(typeof this._player.destroy=="function")try{this._player.destroy()}catch{}this._player=null}this._swfBuffer=null}async rawGetSram(){if(typeof localStorage>"u")return null;const e={};for(let t=0;t<localStorage.length;t++){const s=localStorage.key(t);if(s&&(s.startsWith("ruffle_sol")||s.endsWith(".sol"))){const r=localStorage.getItem(s);r&&(e[s]=new TextEncoder().encode(r))}}return Object.keys(e).length>0?e:null}async rawSetSram(e){if(typeof localStorage>"u"||e instanceof Uint8Array)return!1;for(const[t,s]of Object.entries(e))localStorage.setItem(t,new TextDecoder().decode(s));return!0}rawGetOptions(){return[{id:"letterbox",label:"Letterbox",type:"enum",choices:[{value:"on",label:"On"},{value:"off",label:"Off"}],defaultValue:"on",currentValue:"on"},{id:"quality",label:"Rendering Quality",type:"enum",choices:[{value:"high",label:"High"},{value:"medium",label:"Medium"},{value:"low",label:"Low"}],defaultValue:"high",currentValue:"high"}]}rawSetOption(e,t){this._player&&typeof this._player.setConfig=="function"&&this._player.setConfig({[e]:t})}rawSendButton(e,t,s){const i={4:"ArrowUp",5:"ArrowDown",6:"ArrowLeft",7:"ArrowRight",0:"Space",8:"KeyZ",1:"KeyX",3:"Enter"}[t];i&&typeof window<"u"&&window.dispatchEvent(new KeyboardEvent(s?"keydown":"keyup",{code:i,key:i}))}async _instantiateRuffle(){var r,i,n;const t=`${(((r=this.context)==null?void 0:r.assetBaseUrl)||"").replace(/\/$/,"")}/ruffle.js`;if(!window.RufflePlayer)try{await import(t)}catch(o){(i=this.context)!=null&&i.debug&&console.warn("[RuffleAdapter] Dynamic import of ruffle.js failed:",o)}const s=window.RufflePlayer;if(s&&typeof s.newest=="function"){const o=s.newest();this._player=o.createPlayer();const l=(n=this.context)==null?void 0:n.canvas;l&&l.parentElement&&(l.style.display="none",l.parentElement.appendChild(this._player))}}}function j(_,a){const e=(_&65535)+(a&65535);return(_>>16)+(a>>16)+(e>>16)<<16|e&65535}function Fe(_,a){return _<<a|_>>>32-a}function V(_,a,e,t,s,r){return j(Fe(j(j(a,_),j(t,r)),s),e)}function D(_,a,e,t,s,r,i){return V(a&e|~a&t,_,a,s,r,i)}function M(_,a,e,t,s,r,i){return V(a&t|e&~t,_,a,s,r,i)}function E(_,a,e,t,s,r,i){return V(a^e^t,_,a,s,r,i)}function O(_,a,e,t,s,r,i){return V(e^(a|~t),_,a,s,r,i)}function W(_){const a=_.length,e=[];for(let d=0;d<a;d++)e[d>>2]|=_[d]<<d%4*8;e[a>>2]|=128<<a%4*8,e[(a+8>>6<<4)+14]=a*8;let t=1732584193,s=-271733879,r=-1732584194,i=271733878;for(let d=0;d<e.length;d+=16){const u=t,m=s,p=r,w=i,h=e.slice(d,d+16);for(;h.length<16;)h.push(0);t=D(t,s,r,i,h[0],7,-680876936),i=D(i,t,s,r,h[1],12,-389564586),r=D(r,i,t,s,h[2],17,606105819),s=D(s,r,i,t,h[3],22,-1044525330),t=D(t,s,r,i,h[4],7,-176418897),i=D(i,t,s,r,h[5],12,1200080426),r=D(r,i,t,s,h[6],17,-1473231341),s=D(s,r,i,t,h[7],22,-45705983),t=D(t,s,r,i,h[8],7,1770035416),i=D(i,t,s,r,h[9],12,-1958414417),r=D(r,i,t,s,h[10],17,-42063),s=D(s,r,i,t,h[11],22,-1990404162),t=D(t,s,r,i,h[12],7,1804603682),i=D(i,t,s,r,h[13],12,-40341101),r=D(r,i,t,s,h[14],17,-1502002290),s=D(s,r,i,t,h[15],22,1236535329),t=M(t,s,r,i,h[1],5,-165796510),i=M(i,t,s,r,h[6],9,-1069501632),r=M(r,i,t,s,h[11],14,643717713),s=M(s,r,i,t,h[0],20,-373897302),t=M(t,s,r,i,h[5],5,-701558691),i=M(i,t,s,r,h[10],9,38016083),r=M(r,i,t,s,h[15],14,-660478335),s=M(s,r,i,t,h[4],20,-405537848),t=M(t,s,r,i,h[9],5,568446438),i=M(i,t,s,r,h[14],9,-1019803690),r=M(r,i,t,s,h[3],14,-187363961),s=M(s,r,i,t,h[8],20,1163531501),t=M(t,s,r,i,h[13],5,-1444681467),i=M(i,t,s,r,h[2],9,-51403784),r=M(r,i,t,s,h[7],14,1735328473),s=M(s,r,i,t,h[12],20,-1926607734),t=E(t,s,r,i,h[5],4,-378558),i=E(i,t,s,r,h[8],11,-2022574463),r=E(r,i,t,s,h[11],16,1839030562),s=E(s,r,i,t,h[14],23,-35309556),t=E(t,s,r,i,h[1],4,-1530992060),i=E(i,t,s,r,h[4],11,1272893353),r=E(r,i,t,s,h[7],16,-155497632),s=E(s,r,i,t,h[10],23,-1094730640),t=E(t,s,r,i,h[13],4,681279174),i=E(i,t,s,r,h[0],11,-358537222),r=E(r,i,t,s,h[3],16,-722521979),s=E(s,r,i,t,h[6],23,76029189),t=E(t,s,r,i,h[9],4,-640364487),i=E(i,t,s,r,h[12],11,-421815835),r=E(r,i,t,s,h[15],16,530742520),s=E(s,r,i,t,h[2],23,-995338651),t=O(t,s,r,i,h[0],6,-198630844),i=O(i,t,s,r,h[7],10,1126891415),r=O(r,i,t,s,h[14],15,-1416354905),s=O(s,r,i,t,h[5],21,-57434055),t=O(t,s,r,i,h[12],6,1700485571),i=O(i,t,s,r,h[3],10,-1894986606),r=O(r,i,t,s,h[10],15,-1051523),s=O(s,r,i,t,h[1],21,-2054922799),t=O(t,s,r,i,h[8],6,1873313359),i=O(i,t,s,r,h[15],10,-30611744),r=O(r,i,t,s,h[6],15,-1560198380),s=O(s,r,i,t,h[13],21,1309151649),t=O(t,s,r,i,h[4],6,-145523070),i=O(i,t,s,r,h[11],10,-1120210379),r=O(r,i,t,s,h[2],15,718787259),s=O(s,r,i,t,h[9],21,-343485551),t=j(t,u),s=j(s,m),r=j(r,p),i=j(i,w)}const n="0123456789abcdef";let o="";const l=[t,s,r,i];for(let d=0;d<4;d++)for(let u=0;u<4;u++){const m=l[d]>>>u*8&255;o+=n.charAt(m>>>4&15)+n.charAt(m&15)}return o}class ie{constructor(a,e){c(this,"_user",null);c(this,"_achievements",[]);c(this,"_gameHash",null);c(this,"_gameId",null);c(this,"_gameTitle",null);c(this,"_hardcore",!0);c(this,"_unlockedIds",new Set);c(this,"_defaultApi","/ra-api/dorequest.php");this._getAdapter=a,this._emit=e}get user(){return this._user}get isLoggedIn(){return!!this._user&&!!this._user.token}get achievements(){return[...this._achievements]}get gameHash(){return this._gameHash}get gameId(){return this._gameId}get gameTitle(){return this._gameTitle}get hardcore(){return this._hardcore}setHardcore(a){this._hardcore=a}computeGameHash(a){return a.length>16&&a[0]===78&&a[1]===69&&a[2]===83&&a[3]===26?W(a.subarray(16)):a.length>512&&a.length%1024===512||a.length>512&&a.length%16384===512?W(a.subarray(512)):W(a)}async login(a,e,t=this._defaultApi){try{const s=`${t}?r=login&u=${encodeURIComponent(a)}&p=${encodeURIComponent(e)}`,i=await(await fetch(s)).json();if(i&&i.Success)return this._user={username:i.User||a,token:i.Token||e,score:Number(i.Score||0),softcoreScore:Number(i.SoftcoreScore||0)},this._emit("achievementLogin",{user:this._user}),this._gameHash&&this.loadAchievements(this._gameHash,this._gameTitle||void 0,t).catch(()=>{}),{success:!0,user:this._user};try{const n=`${t}?r=patch&g=228&u=${encodeURIComponent(a)}&t=${encodeURIComponent(e)}`,l=await(await fetch(n)).json();if(l&&l.Success)return this._user={username:a,token:e,score:0,softcoreScore:0},this._emit("achievementLogin",{user:this._user}),this._gameHash&&this.loadAchievements(this._gameHash,this._gameTitle||void 0,t).catch(()=>{}),{success:!0,user:this._user}}catch{}return{success:!1,error:(i==null?void 0:i.Error)||(i==null?void 0:i.Code)||"Invalid credentials. Please verify your username and password or Web API Key."}}catch{return this._user={username:a,token:e,score:0,softcoreScore:0},this._emit("achievementLogin",{user:this._user}),{success:!0,user:this._user}}}logout(){this._user=null,this._achievements=[],this._gameHash=null,this._gameId=null,this._gameTitle=null,this._unlockedIds.clear(),this._emit("achievementsLoaded",{gameId:null,gameTitle:null,achievements:[]})}async loadAchievements(a,e="Unknown",t=this._defaultApi){if(this._gameHash=a,this._gameTitle=e,this._achievements=[],this._unlockedIds.clear(),!this.isLoggedIn||!this._user)return this._achievements;try{const s=`${t}?r=gameid&m=${encodeURIComponent(a)}`,i=await(await fetch(s)).json();if(i&&i.Success&&i.GameID){this._gameId=Number(i.GameID);const n=`${t}?r=patch&g=${this._gameId}&u=${encodeURIComponent(this._user.username)}&t=${encodeURIComponent(this._user.token||"")}`,l=await(await fetch(n)).json();if(l&&l.Success&&l.PatchData){const d=l.PatchData;this._gameTitle=d.Title||e;const u=d.Achievements||[];this._achievements=u.map(m=>({id:Number(m.ID),title:m.Title||"Achievement",description:m.Description||"",points:Number(m.Points||0),badgeName:m.BadgeName,badgeUrl:m.BadgeName?`https://media.retroachievements.org/Badge/${m.BadgeName}.png`:void 0,unlocked:!!m.DateEarned,unlockedHardcore:!!m.DateEarnedHardcore}));for(const m of this._achievements)m.unlocked&&this._unlockedIds.add(m.id)}}}catch(s){console.warn("[AchievementManager] Error fetching achievements from RetroAchievements API:",s)}return this._emit("achievementsLoaded",{gameId:this._gameId,gameTitle:this._gameTitle,achievements:this._achievements}),this._achievements}setAchievements(a,e,t){e&&(this._gameHash=e),t&&(this._gameTitle=t),this._achievements=[...a],this._unlockedIds.clear();for(const s of a)s.unlocked&&this._unlockedIds.add(s.id)}async unlock(a,e=this._defaultApi){if(this._unlockedIds.has(a))return!1;this._unlockedIds.add(a);const t=this._achievements.find(s=>s.id===a);if(t){if(t.unlocked=!0,this._hardcore&&(t.unlockedHardcore=!0),this.isLoggedIn&&this._user&&this._gameHash)try{const s=`${e}?r=awardachievement&u=${encodeURIComponent(this._user.username)}&t=${encodeURIComponent(this._user.token||"")}&a=${a}&h=${this._hardcore?1:0}&m=${encodeURIComponent(this._gameHash)}`;fetch(s).catch(()=>{})}catch{}return this._emit("achievementUnlocked",{achievement:t,hardcore:this._hardcore}),!0}return!1}updateProgress(a,e,t){const s=this._achievements.find(r=>r.id===a);s&&(s.progress={current:e,max:t},this._emit("achievementProgress",{achievement:s,current:e,max:t}))}evaluate(){const a=this._getAdapter();!a||a.rawGetMemorySize()<=0}}class ne{constructor(a,e){c(this,"_masterGain");c(this,"_volume",1);c(this,"_isMuted",!1);this._ctx=a,this._getAdapter=e,this._masterGain=this._ctx.createGain(),this._masterGain.gain.value=this._volume,this._masterGain.connect(this._ctx.destination)}getVolume(){return this._volume}setVolume(a){this._volume=Math.max(0,Math.min(1,a)),this._isMuted||this._masterGain.gain.setValueAtTime(this._volume,this._ctx.currentTime);const e=this._getAdapter();e&&e.rawSetVolume(this._isMuted?0:this._volume)}setMute(a){this._isMuted=a,this._masterGain.gain.setValueAtTime(a?0:this._volume,this._ctx.currentTime);const e=this._getAdapter();e&&e.rawSetVolume(a?0:this._volume)}isMuted(){return this._isMuted}async unlockAudio(){this._ctx.state==="suspended"&&await this._ctx.resume()}getAudioContext(){return this._ctx}destroy(){try{this._masterGain.disconnect()}catch{}}}class oe{constructor(){c(this,"_biosMap",new Map)}register(a,e){const t=a.replace(/^.*[\\/]/,""),s=e instanceof Uint8Array?e:new Uint8Array(e);this._biosMap.set(t,s)}unregister(a){const e=a.replace(/^.*[\\/]/,"");return this._biosMap.delete(e)}has(a){const e=a.replace(/^.*[\\/]/,"");return this._biosMap.has(e)}get(a){const e=a.replace(/^.*[\\/]/,"");return this._biosMap.get(e)}list(){return Array.from(this._biosMap.keys())}clear(){this._biosMap.clear()}async injectIntoAdapter(a){if(a)for(const[e,t]of this._biosMap.entries())try{await a.rawSetBios(e,t)}catch(s){console.warn(`[BiosManager] Failed to inject BIOS "${e}" into adapter:`,s)}}}class le{constructor(a){c(this,"_cheats",new Map);c(this,"_counter",0);this._getAdapter=a}getCheats(){return Array.from(this._cheats.values())}addCheat(a){const e=`cheat_${++this._counter}`,t={...a,id:e};return this._cheats.set(e,t),this._syncToCore(),e}removeCheat(a){const e=this._cheats.delete(a);return e&&this._syncToCore(),e}toggleCheat(a,e){const t=this._cheats.get(a);t&&(t.enabled=e,this._syncToCore())}clearAllCheats(){this._cheats.clear();const a=this._getAdapter();a&&a.capabilities.cheats&&a.rawResetCheats()}loadCheatFile(a,e="cht"){var n,o,l;if(e==="json"){try{const d=JSON.parse(a);for(const u of d)this.addCheat({name:u.name,code:u.code,enabled:!!u.enabled,type:u.type})}catch(d){console.error("[CheatManager] Failed to parse JSON cheats:",d)}return}const t=a.split(`
142
+ `);let s="",r="",i=!1;for(const d of t){const u=d.trim();u&&(u.includes("_desc =")?s=((n=u.split("=")[1])==null?void 0:n.replace(/"/g,"").trim())||"":u.includes("_code =")?r=((o=u.split("=")[1])==null?void 0:o.replace(/"/g,"").trim())||"":u.includes("_enable =")&&(i=((l=u.split("=")[1])==null?void 0:l.trim())==="true",r&&(this.addCheat({name:s||r,code:r,enabled:i}),s="",r="",i=!1)))}}exportCheatFile(){let a=`cheats = ${this._cheats.size}
143
+
144
+ `,e=0;for(const t of this._cheats.values())a+=`cheat${e}_desc = "${t.name}"
145
+ `,a+=`cheat${e}_code = "${t.code}"
146
+ `,a+=`cheat${e}_enable = ${t.enabled}
147
+
148
+ `,e++;return a}_syncToCore(){const a=this._getAdapter();if(!a||!a.capabilities.cheats)return;a.rawResetCheats();let e=0;for(const t of this._cheats.values())a.rawSetCheat(e,t.enabled,t.code),e++}}class ce{constructor(a){c(this,"_optionOverrides",new Map);c(this,"_listeners",new Set);this._getAdapter=a}getOptions(){const a=this._getAdapter();return!a||!a.capabilities.coreOptions?[]:a.rawGetOptions().map(t=>{const s=this._optionOverrides.get(t.id);return{...t,currentValue:s!==void 0?s:t.currentValue}})}getOption(a){if(this._optionOverrides.has(a))return this._optionOverrides.get(a);const t=this.getOptions().find(s=>s.id===a);return t?t.currentValue:void 0}setOption(a,e){this._optionOverrides.set(a,e);const t=this._getAdapter();t&&t.capabilities.coreOptions&&t.rawSetOption(a,e);for(const s of this._listeners)s(a,e)}resetOption(a){const t=this.getOptions().find(s=>s.id===a);t&&this.setOption(a,t.defaultValue)}resetAll(){const a=this.getOptions();for(const e of a)this.setOption(e.id,e.defaultValue);this._optionOverrides.clear()}onOptionChanged(a){return this._listeners.add(a),()=>this._listeners.delete(a)}}class ue{constructor(a){c(this,"_currentDisc",0);c(this,"_discs",[]);c(this,"_listeners",new Set);this._getAdapter=a}setDiscs(a){this._discs=a.map((e,t)=>({index:t,name:`Disc ${t+1}`,path:e,isCurrent:t===0})),this._currentDisc=0}getDiscCount(){const a=this._getAdapter();return a&&a.capabilities.multiDisc?Math.max(a.rawGetDiscCount(),this._discs.length):1}getCurrentDiscIndex(){return this._currentDisc}getDiscList(){return[...this._discs]}async changeDisc(a){const e=this._getAdapter();if(!e||!e.capabilities.multiDisc||a<0||a>=this.getDiscCount())return!1;const t=await e.rawChangeDisc(a);if(t){this._currentDisc=a;for(const r of this._discs)r.isCurrent=r.index===a;const s=this._discs[a]||{index:a,name:`Disc ${a+1}`,path:"",isCurrent:!0};for(const r of this._listeners)r(s)}return t}async nextDisc(){const a=(this._currentDisc+1)%this.getDiscCount();return this.changeDisc(a)}async previousDisc(){const a=(this._currentDisc-1+this.getDiscCount())%this.getDiscCount();return this.changeDisc(a)}async ejectDisc(){const a=this._getAdapter();a&&a.capabilities.multiDisc&&await a.rawChangeDisc(-1)}async insertDisc(a){await this.changeDisc(a)}onDiscChanged(a){return this._listeners.add(a),()=>this._listeners.delete(a)}}const De={ACTION_DOWN:0,ACTION_RIGHT:8,ACTION_LEFT:1,ACTION_UP:9,SELECT:2,START:3,DPAD_UP:4,DPAD_DOWN:5,DPAD_LEFT:6,DPAD_RIGHT:7,L1:10,R1:11,L2:12,R2:13,L3:14,R3:15,HOME:16,HOTKEY_FAST_FORWARD:20,HOTKEY_REWIND:21,HOTKEY_SAVE:22,HOTKEY_LOAD:23},Me={L_STICK_X:0,L_STICK_Y:1,R_STICK_X:2,R_STICK_Y:3};class de{constructor(a,e){c(this,"_assignedGamepadIndex",null);c(this,"_keyBindings",new Map);c(this,"_gamepadBindings",new Map);c(this,"_buttonStates",new Map);c(this,"_axisStates",new Map);c(this,"_turboIntervals",new Map);this.playerIndex=a,this._getAdapter=e,this.resetBindings()}get assignedGamepadIndex(){return this._assignedGamepadIndex}assignGamepad(a){this._assignedGamepadIndex=a}sendButton(a,e){this._buttonStates.set(a,e);const t=this._getAdapter();if(!t)return;const s=De[a];s!==void 0&&t.rawSendButton(this.playerIndex,s,e)}sendAxis(a,e){const t=Math.max(-1,Math.min(1,e));this._axisStates.set(a,t);const s=this._getAdapter();if(!s)return;const r=Me[a];r!==void 0&&s.rawSendAxis(this.playerIndex,r,t)}sendAnalogStick(a,e,t){a==="LEFT"?(this.sendAxis("L_STICK_X",e),this.sendAxis("L_STICK_Y",t)):(this.sendAxis("R_STICK_X",e),this.sendAxis("R_STICK_Y",t))}isButtonPressed(a){return!!this._buttonStates.get(a)}getAxisValue(a){return this._axisStates.get(a)||0}setKeyBinding(a,e){this._keyBindings.set(e,a)}setGamepadBinding(a,e){this._gamepadBindings.set(e,a)}resetBindings(){this._keyBindings.clear(),this._gamepadBindings.clear(),this.playerIndex===0&&(this._keyBindings.set("ArrowUp","DPAD_UP"),this._keyBindings.set("ArrowDown","DPAD_DOWN"),this._keyBindings.set("ArrowLeft","DPAD_LEFT"),this._keyBindings.set("ArrowRight","DPAD_RIGHT"),this._keyBindings.set("KeyZ","ACTION_DOWN"),this._keyBindings.set("KeyX","ACTION_RIGHT"),this._keyBindings.set("KeyA","ACTION_LEFT"),this._keyBindings.set("KeyS","ACTION_UP"),this._keyBindings.set("Enter","START"),this._keyBindings.set("ShiftRight","SELECT"),this._keyBindings.set("KeyQ","L1"),this._keyBindings.set("KeyW","R1"),this._keyBindings.set("KeyE","L2"),this._keyBindings.set("KeyR","R2")),this._gamepadBindings.set(0,"ACTION_DOWN"),this._gamepadBindings.set(1,"ACTION_RIGHT"),this._gamepadBindings.set(2,"ACTION_LEFT"),this._gamepadBindings.set(3,"ACTION_UP"),this._gamepadBindings.set(4,"L1"),this._gamepadBindings.set(5,"R1"),this._gamepadBindings.set(6,"L2"),this._gamepadBindings.set(7,"R2"),this._gamepadBindings.set(8,"SELECT"),this._gamepadBindings.set(9,"START"),this._gamepadBindings.set(10,"L3"),this._gamepadBindings.set(11,"R3"),this._gamepadBindings.set(12,"DPAD_UP"),this._gamepadBindings.set(13,"DPAD_DOWN"),this._gamepadBindings.set(14,"DPAD_LEFT"),this._gamepadBindings.set(15,"DPAD_RIGHT"),this._gamepadBindings.set(16,"HOME")}setTurbo(a,e,t=15){const s=this._turboIntervals.get(a);if(s&&(window.clearInterval(s),this._turboIntervals.delete(a)),e){let r=!1;const i=window.setInterval(()=>{r=!r,this.sendButton(a,r)},1e3/t);this._turboIntervals.set(a,i)}else this.sendButton(a,!1)}handleKeyEvent(a,e){const t=this._keyBindings.get(a);return t?(this.sendButton(t,e),!0):!1}handleGamepadState(a){for(let e=0;e<a.buttons.length;e++){const t=this._gamepadBindings.get(e);if(t){const s=a.buttons[e],r=s.pressed||s.value>.5;this._buttonStates.get(t)!==r&&this.sendButton(t,r)}}if(a.axes.length>=2){const e=Math.abs(a.axes[0])>.15?a.axes[0]:0,t=Math.abs(a.axes[1])>.15?a.axes[1]:0;this.sendAxis("L_STICK_X",e),this.sendAxis("L_STICK_Y",t)}if(a.axes.length>=4){const e=Math.abs(a.axes[2])>.15?a.axes[2]:0,t=Math.abs(a.axes[3])>.15?a.axes[3]:0;this.sendAxis("R_STICK_X",e),this.sendAxis("R_STICK_Y",t)}}}class he{constructor(a,e=4){c(this,"_players",[]);c(this,"_hotkeys",new Map);c(this,"_hotkeyHandlers",new Map);c(this,"_pollRaf",null);c(this,"_onKeyDownRef");c(this,"_onKeyUpRef");this._getAdapter=a,this._maxPlayers=e;for(let t=0;t<this._maxPlayers;t++)this._players.push(new de(t,this._getAdapter));this._onKeyDownRef=this._handleKeyDown.bind(this),this._onKeyUpRef=this._handleKeyUp.bind(this),typeof window<"u"&&(window.addEventListener("keydown",this._onKeyDownRef),window.addEventListener("keyup",this._onKeyUpRef),this._startGamepadLoop())}player(a){if(a<0||a>=this._players.length)throw new Error(`[InputManager] Invalid player index: ${a} (max: ${this._players.length})`);return this._players[a]}sendButton(a,e,t){this.player(a).sendButton(e,t)}sendAxis(a,e,t){this.player(a).sendAxis(e,t)}sendAnalogStick(a,e,t,s){this.player(a).sendAnalogStick(e,t,s)}getMaxPlayers(){const a=this._getAdapter();return(a==null?void 0:a.capabilities.maxPlayers)||this._maxPlayers}autoAssignGamepads(){if(typeof navigator>"u"||!navigator.getGamepads)return;Array.from(navigator.getGamepads()).filter(e=>e!==null).forEach((e,t)=>{t<this._players.length&&this._players[t].assignGamepad(e.index)})}setHotkeyBinding(a,e){this._hotkeys.set(String(e),a)}registerHotkeyHandler(a,e){this._hotkeyHandlers.set(a,e)}getConnectedControllers(){return typeof navigator>"u"||!navigator.getGamepads?[]:Array.from(navigator.getGamepads()).filter(a=>a!==null).map(a=>{const e=this._players.find(t=>t.assignedGamepadIndex===a.index);return{index:a.index,id:a.id,connected:a.connected,mapping:a.mapping,assignedPlayer:e?e.playerIndex:null}})}destroy(){this._pollRaf&&(cancelAnimationFrame(this._pollRaf),this._pollRaf=null),typeof window<"u"&&(window.removeEventListener("keydown",this._onKeyDownRef),window.removeEventListener("keyup",this._onKeyUpRef))}_handleKeyDown(a){if(a._isRetroKitSynthetic)return;const e=this._hotkeys.get(a.code)||this._hotkeys.get(a.key);if(e){const s=this._hotkeyHandlers.get(e);if(s){a.preventDefault(),s();return}}this._players[0].handleKeyEvent(a.code,!0)&&a.preventDefault()}_handleKeyUp(a){if(a._isRetroKitSynthetic)return;this._players[0].handleKeyEvent(a.code,!1)&&a.preventDefault()}_startGamepadLoop(){const a=()=>{if(typeof navigator<"u"&&navigator.getGamepads){const e=navigator.getGamepads();for(const t of this._players)if(t.assignedGamepadIndex!==null){const s=e[t.assignedGamepadIndex];s&&s.connected&&t.handleGamepadState(s)}}this._pollRaf=requestAnimationFrame(a)};this._pollRaf=requestAnimationFrame(a)}}class me{constructor(){c(this,"_connected",!1);c(this,"_isHost",!1);c(this,"_playerIndex",0);c(this,"_peers",[]);c(this,"_socket",null)}isConnected(){return this._connected}isHost(){return this._isHost}getPlayerIndex(){return this._playerIndex}getConnectedPeers(){return[...this._peers]}async connect(a,e,t="Player"){return this.disconnect(),new Promise((s,r)=>{try{const i=`${a.replace(/^http/,"ws")}?room=${encodeURIComponent(e)}&nick=${encodeURIComponent(t)}`;this._socket=new WebSocket(i),this._socket.onopen=()=>{this._connected=!0,s()},this._socket.onclose=()=>{this._connected=!1},this._socket.onerror=n=>{r(n)}}catch(i){r(i)}})}disconnect(){this._socket&&(this._socket.close(),this._socket=null),this._connected=!1,this._peers=[]}}class fe{constructor(a){c(this,"_isDirty",!1);c(this,"_lastData",null);c(this,"_modifiedListeners",new Set);c(this,"_pollTimer",null);this._getAdapter=a,this._startDirtyWatchdog()}async getSram(){const a=this._getAdapter();return!a||!a.capabilities.sram?null:a.rawGetSram()}async setSram(a,e){const t=this._getAdapter();if(!t||!t.capabilities.sram)return!1;const s=await t.rawSetSram(a);return s&&(e!=null&&e.restart)&&await t.restart(),this._isDirty=!1,this._lastData=a,s}async flushSram(){const a=this._getAdapter();!a||!a.capabilities.sram||(await a.rawFlushSram(),this._isDirty=!1)}isDirty(){return this._isDirty}onSramModified(a){return this._modifiedListeners.add(a),()=>this._modifiedListeners.delete(a)}getSaveFilePath(){const a=this._getAdapter();return(a==null?void 0:a.getSramPath())||""}destroy(){this._pollTimer&&(clearInterval(this._pollTimer),this._pollTimer=null),this._modifiedListeners.clear()}_startDirtyWatchdog(){this._pollTimer=setInterval(async()=>{const a=this._getAdapter();if(!a||!a.capabilities.sram)return;const e=await a.rawGetSram();if(e&&this._hasChanged(this._lastData,e)){this._isDirty=!0,this._lastData=e;for(const t of this._modifiedListeners)try{t(e)}catch(s){console.error("[SramManager] Error in onSramModified listener:",s)}}},2500)}_hasChanged(a,e){if(!a&&!e)return!1;if(!a||!e)return!0;if(a instanceof Uint8Array&&e instanceof Uint8Array){if(a.byteLength!==e.byteLength)return!0;for(let t=0;t<a.byteLength;t++)if(a[t]!==e[t])return!0;return!1}return!0}}class pe{constructor(a,e){c(this,"_stateCache",new Map);c(this,"_activeGameId","default");this._getAdapter=a,this._getScreenshot=e}setGameId(a){this._activeGameId=a,this._stateCache.clear()}async saveState(a=0){const e=this._getAdapter();if(!e||!e.capabilities.saveStates)return null;const t=await e.rawSaveState(a);if(!t)return null;let s;try{const i=await this._getScreenshot();i&&(s=i)}catch{}const r={data:t,metadata:{slot:a,timestamp:Date.now(),gameId:this._activeGameId,coreId:e.id,screenshot:s,sizeBytes:t.byteLength}};return this._stateCache.set(a,r),r}async loadState(a){const e=this._getAdapter();if(!e||!e.capabilities.saveStates)return!1;let t=null;const s=typeof a=="number"?a:void 0;if(typeof a=="number"){const r=this._stateCache.get(a);t=r?r.data:null}else t=a;return t?e.rawLoadState(t,s):!1}async getStateBuffer(){const a=this._getAdapter();return!a||!a.capabilities.saveStates?null:a.rawSaveState()}async listStates(){return Array.from(this._stateCache.values()).map(a=>a.metadata)}async hasState(a){return this._stateCache.has(a)}async deleteState(a){this._stateCache.delete(a)}async autoSave(){return this.saveState(-1)}async autoLoad(){return this.loadState(-1)}}class _e{constructor(a){c(this,"_speedRatio",1);c(this,"_isFastForward",!1);c(this,"_isSlowMotion",!1);this._getAdapter=a}get isFastForward(){return this._isFastForward}get isSlowMotion(){return this._isSlowMotion}get speedRatio(){return this._speedRatio}setFastForward(a,e=2.5){this._isFastForward=a,a?(this._isSlowMotion=!1,this.setSpeed(e)):this.setSpeed(1)}setSlowMotion(a,e=.5){this._isSlowMotion=a,a?(this._isFastForward=!1,this.setSpeed(e)):this.setSpeed(1)}setSpeed(a){this._speedRatio=Math.max(.1,Math.min(10,a));const e=this._getAdapter();e&&e.capabilities.variableSpeed&&e.rawSetSpeed(this._speedRatio)}stepFrame(){const a=this._getAdapter();a&&(a.resume(),requestAnimationFrame(()=>{a.pause()}))}isRewindSupported(){const a=this._getAdapter();return!!(a!=null&&a.capabilities.rewind)}startRewind(){if(!this.isRewindSupported())return;const a=this._getAdapter();a&&a.rawSetSpeed(-1)}stopRewind(){this.isRewindSupported()&&this.setSpeed(1)}}class ye{constructor(a,e){c(this,"_aspectRatio","auto");c(this,"_rotation",0);c(this,"_currentShader","disabled");c(this,"_resizeObserver",null);this._getAdapter=a,this._getCanvas=e,typeof window<"u"&&window.addEventListener("resize",()=>this.updateLayout())}get aspectRatio(){return this._aspectRatio}get rotation(){return this._rotation}get currentShader(){return this._currentShader}async setShader(a){this._currentShader=a;const e=this._getCanvas();e&&(a==="scanlines"?e.style.filter="contrast(1.05) brightness(0.98)":e.style.filter="none")}setAspectRatio(a){this._aspectRatio=a,this.updateLayout()}updateLayout(){const a=this._getCanvas();if(!a)return;if(typeof ResizeObserver<"u"&&a.parentElement&&!this._resizeObserver)try{this._resizeObserver=new ResizeObserver(()=>this.updateLayout()),this._resizeObserver.observe(a.parentElement)}catch{}if(this._aspectRatio==="stretch"){a.style.aspectRatio="unset",a.style.width="100%",a.style.height="100%",a.style.maxWidth="100%",a.style.maxHeight="100%",a.style.objectFit="fill";return}const e=a.parentElement,t=e?e.clientWidth:typeof window<"u"?window.innerWidth:800,s=e?e.clientHeight:typeof window<"u"?window.innerHeight:600,r=a.width||240,i=a.height||160;if(this._aspectRatio==="pixel-perfect"){const l=Math.max(1,Math.floor(Math.min(t/r,s/i)));a.style.aspectRatio="unset",a.style.width=`${r*l}px`,a.style.height=`${i*l}px`,a.style.maxWidth="100%",a.style.maxHeight="100%",a.style.objectFit="contain";return}let n=r/i;this._aspectRatio==="4:3"?n=4/3:this._aspectRatio==="16:9"&&(n=16/9),a.style.aspectRatio=`${n}`,a.style.maxWidth="100%",a.style.maxHeight="100%",a.style.objectFit="contain",(t&&s?t/s:n)>n?(a.style.height="100%",a.style.width="auto"):(a.style.width="100%",a.style.height="auto")}setRotation(a){this._rotation=a;const e=this._getCanvas();e&&(e.style.transform=a===0?"none":`rotate(${a}deg)`)}setVsync(a){}async takeScreenshot(a="image/png",e=.92){const t=this._getCanvas();if(!t)throw new Error("[VideoManager] Canvas is not available.");return new Promise((s,r)=>{t.toBlob(i=>{i?s(i):r(new Error("[VideoManager] Failed to create screenshot blob."))},a,e)})}getMetrics(){const a=this._getAdapter(),e=this._getCanvas();return{internalWidth:(e==null?void 0:e.width)||0,internalHeight:(e==null?void 0:e.height)||0,fps:(a==null?void 0:a.rawGetFps())||60}}clear(){const a=this._getCanvas();if(a){try{const e=a.getContext("webgl2")||a.getContext("webgl")||a.getContext("experimental-webgl");if(e){const t=e;t.clearColor(0,0,0,1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT);return}}catch{}try{const e=a.width,t=a.height;a.width=e,a.height=t}catch{}}}destroy(){if(this._resizeObserver){try{this._resizeObserver.disconnect()}catch{}this._resizeObserver=null}this.clear()}}class ge{constructor(){c(this,"_listeners",{})}on(a,e){return this._listeners[a]||(this._listeners[a]=new Set),this._listeners[a].add(e),()=>this.off(a,e)}once(a,e){const t=s=>{this.off(a,t),e(s)};return this.on(a,t)}off(a,e){const t=this._listeners[a];t&&(t.delete(e),t.size===0&&delete this._listeners[a])}emit(a,...e){const t=this._listeners[a];if(t){const s=e[0];for(const r of Array.from(t))try{r(s)}catch(i){console.error(`[EventEmitter] Error in listener for event "${String(a)}":`,i)}}}removeAllListeners(){this._listeners={}}}const be=new Uint32Array(256);for(let _=0;_<256;_++){let a=_;for(let e=0;e<8;e++)a=a&1?3988292384^a>>>1:a>>>1;be[_]=a}function Q(_){let a=4294967295;for(let e=0;e<_.length;e++)a=a>>>8^be[(a^_[e])&255];return(a^4294967295)>>>0}class we{static identifyFormat(a){if(a.length>=5&&a[0]===80&&a[1]===65&&a[2]===84&&a[3]===67&&a[4]===72)return"IPS";if(a.length>=4&&a[0]===66&&a[1]===80&&a[2]===83&&a[3]===49)return"BPS";if(a.length>=4&&a[0]===85&&a[1]===80&&a[2]===83&&a[3]===49)return"UPS";throw new Error("[RomPatcher] Unknown or unsupported patch format. Expected IPS, BPS, or UPS header.")}static applyPatch(a,e,t=!0){const s=this.identifyFormat(e),r=Q(a);let i;switch(s){case"IPS":i=this.applyIps(a,e);break;case"BPS":i=this.applyBps(a,e,t);break;case"UPS":i=this.applyUps(a,e,t);break}return{patchedRom:i,format:s,originalCrc32:r,patchedCrc32:Q(i)}}static applyIps(a,e){let t=5,s=new Uint8Array(a);const r=i=>{if(i>s.length){const n=new Uint8Array(Math.max(i,s.length*2));n.set(s),s=n}};for(;t<e.length;){if(t+3<=e.length&&e[t]===69&&e[t+1]===79&&e[t+2]===70){if(t+=3,t+3<=e.length){const o=e[t]<<16|e[t+1]<<8|e[t+2];o<s.length&&(s=s.subarray(0,o))}break}if(t+5>e.length)break;const i=e[t]<<16|e[t+1]<<8|e[t+2],n=e[t+3]<<8|e[t+4];if(t+=5,n===0){if(t+3>e.length)break;const o=e[t]<<8|e[t+1],l=e[t+2];t+=3,r(i+o),s.fill(l,i,i+o)}else{if(t+n>e.length)break;r(i+n),s.set(e.subarray(t,t+n),i),t+=n}}return s}static applyBps(a,e,t=!0){let s=4;const r=()=>{let h=0,g=1;for(;;){if(s>=e.length)throw new Error("[RomPatcher] Unexpected EOF in BPS patch");const f=e[s++];if(h+=(f&127)*g,f&128)break;g<<=7,h+=g}return h},i=r(),n=r(),o=r();s+=o,t&&i!==a.length&&console.warn(`[RomPatcher] BPS Source size mismatch. Expected ${i}, got ${a.length}.`);const l=new Uint8Array(n);let d=0,u=0,m=0;const w=e.length-12;for(;s<w;){const h=r(),g=h&3,f=(h>>2)+1;switch(g){case 0:{for(;f>0;){l[d]=a[d],d++;break}const y=(h>>2)+1;l.set(a.subarray(d,d+y),d),d+=y;break}case 1:{const y=(h>>2)+1;l.set(e.subarray(s,s+y),d),s+=y,d+=y;break}case 2:{const y=r();u+=(y&1?-1:1)*(y>>1);const x=(h>>2)+1;for(let A=0;A<x;A++)l[d++]=a[u++];break}case 3:{const y=r();m+=(y&1?-1:1)*(y>>1);const x=(h>>2)+1;for(let A=0;A<x;A++)l[d++]=l[m++];break}}}return l}static applyUps(a,e,t=!0){let s=4;const r=()=>{let d=0,u=1;for(;;){if(s>=e.length)throw new Error("[RomPatcher] Unexpected EOF in UPS patch");const m=e[s++];if(d+=(m&127)*u,m&128)break;u<<=7,d+=u}return d};r();const i=r(),n=new Uint8Array(i);n.set(a.subarray(0,Math.min(a.length,i)));let o=0;const l=e.length-12;for(;s<l;){const d=r();for(o+=d;s<l;){const u=e[s++];if(u===0)break;o<n.length&&(n[o]^=u),o++}o++}return n}}const Z={saveStates:!1,sram:!1,cheats:!1,coreOptions:!1,multiDisc:!1,shaders:!1,rewind:!1,variableSpeed:!1,maxPlayers:1,pointer:!1};class Se extends ge{constructor(e){var t,s;super();c(this,"state");c(this,"sram");c(this,"cheats");c(this,"options");c(this,"discs");c(this,"input");c(this,"audio");c(this,"video");c(this,"timing");c(this,"netplay");c(this,"bios");c(this,"achievements");c(this,"_adapter",null);c(this,"_config");c(this,"_audioCtx");c(this,"_activeRom",null);c(this,"_lastLoadOptions");c(this,"_isRunning",!1);c(this,"_isPaused",!1);c(this,"_fpsTimer",null);this._config=e,e.audioContext?this._audioCtx=e.audioContext:typeof AudioContext<"u"?this._audioCtx=new AudioContext({latencyHint:"interactive"}):this._audioCtx={},this.video=new ye(()=>this._adapter,()=>this._config.canvas),this.state=new pe(()=>this._adapter,async()=>{try{return await this.video.takeScreenshot("image/jpeg",.8)}catch{return null}}),this.sram=new fe(()=>this._adapter),this.cheats=new le(()=>this._adapter),this.options=new ce(()=>this._adapter),this.discs=new ue(()=>this._adapter),this.input=new he(()=>this._adapter),this.audio=new ne(this._audioCtx,()=>this._adapter),this.timing=new _e(()=>this._adapter),this.netplay=new me,this.bios=new oe,this.achievements=new ie(()=>this._adapter,(r,i)=>this.emit(r,i)),(t=e.retroAchievements)!=null&&t.username&&((s=e.retroAchievements)!=null&&s.token)&&(this.achievements.login(e.retroAchievements.username,e.retroAchievements.token,e.retroAchievements.apiEndpoint).catch(()=>{}),typeof e.retroAchievements.hardcore=="boolean"&&this.achievements.setHardcore(e.retroAchievements.hardcore)),this.sram.onSramModified(r=>{this.emit("sramModified",{data:r})}),this.options.onOptionChanged((r,i)=>{this.emit("optionChanged",{id:r,value:i})}),this.discs.onDiscChanged(r=>{this.emit("discChanged",{disc:r})})}get capabilities(){return this._adapter?this._adapter.capabilities:Z}async load(e,t){var d,u;this._activeRom=e,this._lastLoadOptions=t;const s=(t==null?void 0:t.gameId)||(typeof e=="string"?e:(t==null?void 0:t.fileName)||"game");this.state.setGameId(s);const r=this._resolveCore(t);if(!r)throw new Error(`[RetroKit] Could not determine emulator core for: ${(t==null?void 0:t.fileName)||"ROM"}`);if(t!=null&&t.bios)if(Array.isArray(t.bios))for(const m of t.bios)this.bios.register(m.name,m.data);else for(const[m,p]of Object.entries(t.bios))this.bios.register(m,p);const n=e instanceof Blob&&e.size>150*1024*1024;let o=e,l=null;if(n)try{const m=await e.slice(0,65536).arrayBuffer(),p=this.achievements.computeGameHash(new Uint8Array(m));this.achievements.loadAchievements(p,t==null?void 0:t.fileName).catch(()=>{})}catch{}else{if(typeof e=="string"){const w=await(await fetch(e,{headers:this._config.fetchHeaders})).arrayBuffer();l=new Uint8Array(w)}else if(e instanceof Blob){const p=await e.arrayBuffer();l=new Uint8Array(p)}else e instanceof Uint8Array?l=e:l=new Uint8Array(e);if(o=l,t!=null&&t.patch){let p;if(t.patch instanceof Blob){const h=await t.patch.arrayBuffer();p=new Uint8Array(h)}else t.patch instanceof ArrayBuffer?p=new Uint8Array(t.patch):p=t.patch;const w=we.applyPatch(l,p,t.verifyPatchChecksum);l=w.patchedRom,o=l,this.emit("romPatched",{format:w.format,originalSize:l.length,patchedSize:w.patchedRom.length})}const m=this.achievements.computeGameHash(l);this.achievements.loadAchievements(m,t==null?void 0:t.fileName).catch(p=>{console.warn("[RetroKit] RetroAchievements lookup failed:",p)})}this._adapter&&(await this._adapter.destroy(),this._adapter=null),this._resetCanvas(),this._adapter=this._createAdapter(r),await this._adapter.init({canvas:this._config.canvas,assetBaseUrl:this._config.assetBaseUrl||"/cores",audioContext:this._audioCtx,fetchHeaders:this._config.fetchHeaders,debug:this._config.debug,onFpsUpdate:m=>this.emit("fps",{fps:m}),onSramDirty:m=>this.emit("sramModified",{data:m}),onLog:(m,p="info")=>this.emit("log",{message:m,level:p}),retroAchievements:this.achievements.isLoggedIn&&this.achievements.user?{username:this.achievements.user.username,token:this.achievements.user.token,hardcore:this.achievements.hardcore}:void 0}),await this.bios.injectIntoAdapter(this._adapter),await this._adapter.loadGame(o,t),this._isRunning=!0,this._isPaused=!1,this._startFpsMonitoring(),(u=(d=this.video).updateLayout)==null||u.call(d),this.emit("ready",{core:r.id,gameId:s})}async play(){if(!this._isRunning&&this._activeRom){await this.load(this._activeRom,this._lastLoadOptions);return}this._adapter&&(this.audio.unlockAudio().catch(()=>{}),this._adapter.resume(),this._isRunning=!0,this._isPaused=!1,this._startFpsMonitoring(),this.emit("resume"))}pause(){this._adapter&&(this._adapter.pause(),this._isPaused=!0,this._fpsTimer&&(clearInterval(this._fpsTimer),this._fpsTimer=null),this.emit("pause"))}async stop(){this._adapter&&(this._fpsTimer&&(clearInterval(this._fpsTimer),this._fpsTimer=null),await this._adapter.stop(),this._isRunning=!1,this._isPaused=!1,this.video.clear(),this.emit("stop"))}setSystem(e){this._lastLoadOptions||(this._lastLoadOptions={}),this._lastLoadOptions.system=e}get lastLoadOptions(){return this._lastLoadOptions}get activeRom(){return this._activeRom}async restart(){this._adapter&&(await this._adapter.restart(),this._isRunning=!0,this._isPaused=!1,this._startFpsMonitoring(),this.emit("resume"))}async destroy(){this._fpsTimer&&(clearInterval(this._fpsTimer),this._fpsTimer=null),await this.stop(),this._adapter&&(await this._adapter.destroy(),this._adapter=null),this.video.destroy(),this.input.destroy(),this.sram.destroy(),this.audio.destroy(),this.netplay.disconnect(),this.removeAllListeners(),this._activeRom=null}_startFpsMonitoring(){this._fpsTimer&&clearInterval(this._fpsTimer),this._fpsTimer=setInterval(()=>{if(this._isRunning&&!this._isPaused&&this._adapter){const e=this._adapter.rawGetFps()||60;this.emit("fps",{fps:e})}},1e3)}async dispose(){await this.destroy()}async switchCore(e){if(!N.getCore(e))throw new Error(`[RetroKit] Core "${e}" is not registered.`);if(!this._activeRom)throw new Error("[RetroKit] No ROM currently loaded to swap core for.");const s={...this._lastLoadOptions,core:e};await this.load(this._activeRom,s)}getCoreMetadata(){return this._adapter?N.getCore(this._adapter.id)||{id:this._adapter.id,name:this._adapter.name,system:this._adapter.system,family:"libretro",extensions:[],capabilities:this._adapter.capabilities}:{id:"none",name:"None",system:"unknown",family:"libretro",extensions:[],capabilities:Z}}isRunning(){return this._isRunning}isPaused(){return this._isPaused}_resolveCore(e){if(e!=null&&e.core){const s=N.getCore(e.core);if(s)return s}if(this._config.core&&this._config.core!=="auto"){const s=N.getCore(this._config.core);if(s)return s}const t=(e==null?void 0:e.system)||(e==null?void 0:e.platformTag)||(this._config.system&&this._config.system!=="auto"?this._config.system:void 0);if(e!=null&&e.fileName){const s=N.resolveCoreFromFileName(e.fileName,t);if(s)return s}if(typeof this._activeRom=="string"){const s=this._activeRom.split("?")[0].split("/").pop()||"",r=N.resolveCoreFromFileName(s,t);if(r)return r}if(t){const s=N.getCoresForSystem(t);if(s.length>0)return s[0]}}_resetCanvas(){const e=this._config.canvas;if(!e||typeof document>"u"||!e.parentNode)return e||null;const t=document.createElement("canvas");return e.id&&(t.id=e.id),e.className&&(t.className=e.className),t.width=e.width||640,t.height=e.height||480,t.tabIndex=e.tabIndex>=0?e.tabIndex:1,e.style.cssText&&(t.style.cssText=e.style.cssText),t.style.display="block",e.parentNode.replaceChild(t,e),this._config.canvas=t,t}_createAdapter(e){const t=N.getAdapterFactory(e.id);if(t)return t();switch(e.family){case"play":return new ae;case"ruffle":return new re;case"pico8":return new H;case"love":return new K;case"emulatorjs":return new te(e.id,e.name,e.system,e.capabilities);default:return new se(e.id,e.name,e.system,e.capabilities)}}}const Ee=Se;S.AchievementManager=ie,S.ArchiveExtractor=I,S.AudioManager=ne,S.BaseCoreBridge=k,S.BiosManager=oe,S.CheatManager=le,S.CoreOptionsManager=ce,S.CoreRegistry=N,S.DEFAULT_CAPABILITIES=Z,S.DiscManager=ue,S.EmuHeadless=Ee,S.EmulatorJSAdapter=te,S.EventEmitter=ge,S.InputManager=he,S.LibretroAdapter=se,S.LoveAdapter=K,S.NetplayManager=me,S.Pico8Adapter=H,S.PlayAdapter=ae,S.PlayerInputChannel=de,S.RetroKit=Se,S.RomPatcher=we,S.RuffleAdapter=re,S.SramManager=fe,S.StateManager=pe,S.TimingManager=_e,S.VideoManager=ye,S.crc32=Q,S.md5=W,Object.defineProperty(S,Symbol.toStringTag,{value:"Module"})}));
149
+ //# sourceMappingURL=retrokit.umd.cjs.map