c64-ready 3.2.0 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +24 -1
  2. package/bin/serve.mjs +41 -133
  3. package/dist/assets/ActionBiker-CWiKt9dn.js +1 -0
  4. package/dist/assets/Panther-D558qV3B.js +1 -0
  5. package/dist/assets/RainbowIslands-CgoxK_qP.js +1 -0
  6. package/dist/assets/RoadRunner-DR_cGZ-h.js +1 -0
  7. package/dist/assets/RocnRope-DrUGJ0pW.js +1 -0
  8. package/dist/assets/Thrust-rDKv3Thu.js +1 -0
  9. package/dist/assets/index-C84W-vN0.js +318 -0
  10. package/dist/assets/src-CNh6UV6R.js +2 -0
  11. package/dist/index.html +19 -4
  12. package/dist-ts/player/c64-player.d.ts +8 -0
  13. package/dist-ts/player/c64-player.d.ts.map +1 -1
  14. package/dist-ts/player/c64-player.js +14 -1
  15. package/dist-ts/player/c64-player.js.map +1 -1
  16. package/dist-ts/player/canvas-renderer.js +1 -1
  17. package/dist-ts/player/display-layout.d.ts +40 -0
  18. package/dist-ts/player/display-layout.d.ts.map +1 -0
  19. package/dist-ts/player/display-layout.js +76 -0
  20. package/dist-ts/player/display-layout.js.map +1 -0
  21. package/dist-ts/player/ui-controller.d.ts +15 -2
  22. package/dist-ts/player/ui-controller.d.ts.map +1 -1
  23. package/dist-ts/player/ui-controller.js +209 -93
  24. package/dist-ts/player/ui-controller.js.map +1 -1
  25. package/dist-ts/player/ultimate-bridge.d.ts +41 -0
  26. package/dist-ts/player/ultimate-bridge.d.ts.map +1 -0
  27. package/dist-ts/player/ultimate-bridge.js +117 -0
  28. package/dist-ts/player/ultimate-bridge.js.map +1 -0
  29. package/dist-ts/player/ultimate-panel.d.ts +32 -0
  30. package/dist-ts/player/ultimate-panel.d.ts.map +1 -0
  31. package/dist-ts/player/ultimate-panel.js +258 -0
  32. package/dist-ts/player/ultimate-panel.js.map +1 -0
  33. package/package.json +1 -1
  34. package/src/headless/agent-cli.mjs +7 -0
  35. package/src/headless/player-server.mjs +197 -0
  36. package/src/main.ts +5 -1
  37. package/src/player/canvas-renderer.ts +1 -1
  38. package/src/player/display-layout.ts +109 -0
  39. package/src/player/ui-controller.ts +226 -93
  40. package/dist/assets/RainbowIslands-BjfmJB8z.js +0 -1
  41. package/dist/assets/index-B8DSjPqI.js +0 -243
  42. package/dist/assets/src-_trgwTvp.js +0 -2
  43. /package/dist/assets/{BeachHead-CuSwFD4k.js → BeachHead-BLcSLEEh.js} +0 -0
  44. /package/dist/assets/{ChuckieEgg-CPqBnAOF.js → ChuckieEgg-Bv2nxhYv.js} +0 -0
  45. /package/dist/assets/{ForbiddenForest-DsQ9jsc8.js → ForbiddenForest-CWEFgjVq.js} +0 -0
  46. /package/dist/assets/{Galaga-Cutc3p9s.js → Galaga-DknmKlo5.js} +0 -0
  47. /package/dist/assets/{Gribbly-DdZ_hHFt.js → Gribbly-nFVwULpF.js} +0 -0
  48. /package/dist/assets/{Hercules-vZYKm7GG.js → Hercules-Dbx_KaEi.js} +0 -0
  49. /package/dist/assets/{LegendOfWilf-CxSMOjsj.js → LegendOfWilf-BBW1Y7LQ.js} +0 -0
  50. /package/dist/assets/{MariosCementFactory-z0IZ0q30.js → MariosCementFactory-DtpgUfFO.js} +0 -0
  51. /package/dist/assets/{MoleAttack-buC6ChYy.js → MoleAttack-D_2aAX2V.js} +0 -0
  52. /package/dist/assets/{MunchyWorm-D2Zv7i0Q.js → MunchyWorm-BqWD5x4j.js} +0 -0
  53. /package/dist/assets/{ParkPatrol-CVj7hyoB.js → ParkPatrol-9pwc_jcb.js} +0 -0
  54. /package/dist/assets/{PottyPigeon-0SYpIUBa.js → PottyPigeon-CZnjIrGr.js} +0 -0
  55. /package/dist/assets/{Stix-BU-qUCeC.js → Stix-o2hS_Ekr.js} +0 -0
  56. /package/dist/assets/{Tilt-C5KtKisF.js → Tilt-BKb_k_R2.js} +0 -0
  57. /package/dist/assets/{UpNDown-CATRO7Mz.js → UpNDown-BQXEmKfk.js} +0 -0
  58. /package/dist/assets/{Uridium-DanS2KoH.js → Uridium-9u86vh1V.js} +0 -0
  59. /package/dist/assets/{VegetablesDeluxe-C41ViimS.js → VegetablesDeluxe-DbmngV50.js} +0 -0
  60. /package/dist/assets/{marked.esm-fTuuvbcB.js → marked.esm-DhpYx7TE.js} +0 -0
  61. /package/dist/assets/{purify.es-CRM-GE0Y.js → purify.es-CWuqV7zK.js} +0 -0
@@ -0,0 +1,318 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/src-CNh6UV6R.js","assets/src-DX0rJQsE.js","assets/ActionBiker-CWiKt9dn.js","assets/string-utils-CMVABfx0.js","assets/BeachHead-BLcSLEEh.js","assets/ChuckieEgg-Bv2nxhYv.js","assets/ForbiddenForest-CWEFgjVq.js","assets/Galaga-DknmKlo5.js","assets/Gribbly-nFVwULpF.js","assets/Hercules-Dbx_KaEi.js","assets/LegendOfWilf-BBW1Y7LQ.js","assets/MariosCementFactory-DtpgUfFO.js","assets/MoleAttack-D_2aAX2V.js","assets/MunchyWorm-BqWD5x4j.js","assets/Panther-D558qV3B.js","assets/ParkPatrol-9pwc_jcb.js","assets/PottyPigeon-CZnjIrGr.js","assets/RainbowIslands-CgoxK_qP.js","assets/RoadRunner-DR_cGZ-h.js","assets/RocnRope-DrUGJ0pW.js","assets/Stix-o2hS_Ekr.js","assets/Thrust-rDKv3Thu.js","assets/Tilt-BKb_k_R2.js","assets/UpNDown-BQXEmKfk.js","assets/Uridium-9u86vh1V.js","assets/VegetablesDeluxe-DbmngV50.js"])))=>i.map(i=>d[i]);
2
+ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=class e{exports=null;heap=null;wasmMemory=null;static async load(t=`/src/emulator/c64.wasm`){let n=await fetch(t);if(!n.ok)throw Error(`Failed to fetch ${t}: ${n.status}`);let r=await n.arrayBuffer(),i=new e;return await i.instantiate(r),i}static DYNAMICTOP_PTR=5583504;static DYNAMIC_BASE=10826544;static INITIAL_PAGES=256;async instantiate(t,n){let r=new WebAssembly.Memory({initial:e.INITIAL_PAGES});this.wasmMemory=r;let i={env:{...this.makeEnvImports(r),...n??{}},wasi_snapshot_preview1:this.makeWasiImports(r)};try{this.exports=(await WebAssembly.instantiate(t,i)).instance.exports,this.updateHeapViews(),new DataView(r.buffer).setUint32(e.DYNAMICTOP_PTR,e.DYNAMIC_BASE,!0),this.exports.__wasm_call_ctors()}catch(e){throw Error(`WASM instantiation failed: ${e}`,{cause:e})}}allocAndWrite(e){if(!this.exports||!this.heap)throw Error(`WASM not ready`);let t=this.exports.malloc(e.length);return this.updateHeapViews(),this.heap.heapU8.set(e,t),t}free(e){this.exports?.free(e)}updateHeapViews(){if(!this.wasmMemory)throw Error(`WASM memory not initialized`);let e=this.wasmMemory.buffer;this.heap={heapU8:new Uint8Array(e),heapF32:new Float32Array(e),heapU32:new Uint32Array(e)}}makeEnvImports(t){return{memory:t,emscripten_get_sbrk_ptr:()=>e.DYNAMICTOP_PTR,emscripten_resize_heap:e=>{let n=65536,r=2147483648-n;if(e>r)return 0;let i=t.buffer.byteLength;for(let a=1;a<=4;a*=2){let o=i*(1+.2/a);o=Math.min(o,e+100663296);let s=Math.min(r,Math.ceil(Math.max(16777216,e,o)/n)*n);try{return t.grow(s-t.buffer.byteLength+65535>>>16),this.updateHeapViews(),1}catch{}}return 0},emscripten_memcpy_big:(e,n,r)=>(new Uint8Array(t.buffer).copyWithin(e,n,n+r),e),setTempRet0:e=>{},emscripten_asm_const_iii:(e,t,n)=>0,table:new WebAssembly.Table({initial:512,maximum:512,element:`anyfunc`})}}makeWasiImports(e){return{fd_write:(t,n,r,i)=>{let a=new DataView(e.buffer),o=new Uint8Array(e.buffer),s=0;for(let e=0;e<r;e++){let r=a.getUint32(n+e*8,!0),i=a.getUint32(n+e*8+4,!0);if(t===2){let e=new TextDecoder().decode(o.subarray(r,r+i));console.error(e)}s+=i}return a.setUint32(i,s,!0),0}}}};const t={0:`Normal cartridge`,1:`Action Replay`,2:`KCS Power Cartridge`,3:`Final Cartridge III`,4:`Simons BASIC`,5:`Ocean type 1`,6:`Expert Cartridge`,7:`Fun Play, Power Play`,8:`Super Games`,9:`Atomic Power`,10:`Epyx Fastload`,11:`Westermann Learning`,12:`Rex Utility`,13:`Final Cartridge I`,14:`Magic Formel`,15:`C64 Game System (SYSTEM 3)`,16:`Warp Speed`,17:`Dinamic`,18:`Zaxxon / Super Zaxxon (SEGA)`,19:`Magic Desk / Domark / HES Australia`,20:`Super Snapshot V5`,21:`Comal-80`,22:`Structured BASIC`,23:`Ross`,24:`Dela EP64`,25:`Dela EP7x8`,26:`Dela EP256`,27:`Rex EP256`,28:`Mikro Assembler`,29:`Final Cartridge Plus`,30:`Action Replay 4`,31:`Stardos`,32:`EasyFlash`,33:`EasyFlash Xbank`,34:`Capture`,35:`Action Replay 3`,36:`Retro Replay`,37:`MMC64`,38:`MMC Replay`,39:`IDE64`,40:`Super Snapshot V4`,41:`IEEE-488`,42:`Game Killer`,43:`Prophet64`,44:`EXOS`,45:`Freeze Frame`,46:`Freeze Machine`,47:`Snapshot64`,48:`Super Explode V5.0`,49:`Magic Voice`,50:`Action Replay 2`,51:`MACH 5`,52:`Diashow-Maker`,53:`Pagefox`,54:`Kingsoft`,55:`Silverrock 128K Longshot`,56:`Formel 64`,57:`RGCD`,58:`RR-Net MK3`,59:`Easy Calc`,60:`GMod2`,61:`MAX Basic`,62:`GMod3`,63:`ZIPP-CODE 48`,64:`Blackbox V8`,65:`Blackbox V3`,66:`Blackbox V4`,67:`REX RAM-Floppy`,68:`BIS-Plus`,69:`SD-BOX`,70:`MultiMAX`,71:`Blackbox V9`,72:`Lt. Kernal Host Adaptor`,73:`RAMLink`,74:`H.E.R.O.`,75:`IEEE Flash! 64`,76:`Turtle Graphics II`,77:`Freeze Frame MK2`,78:`Partner 64`};function n(e){return e.exrom===1&&e.game===0}function r(e){return n(e)&&e.hwType===0?`Unsupported CRT: Ultimax/MAX cartridges are not supported by this emulator.`:null}function i(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function a(e,t){return(e[t]<<8|e[t+1])>>>0}function o(e,n){if(!e||e.length<64||!String.fromCharCode(...Array.from(e.slice(0,16))).startsWith(`C64 CARTRIDGE`))return null;let r=i(e,16),o=a(e,22),s=e[24],c=e[25],l=``;for(let t=32;t<64&&e[t]!==0;t++)l+=String.fromCharCode(e[t]);l=l.trim();let u;u=s===0&&c===0?`16K (ROML+ROMH)`:s===0&&c===1?`8K (ROML only)`:s===1&&c===0?`Ultimax`:`inactive (pass-through)`;let d=0,f=0,p=Math.max(r,64);for(;p+16<=e.length&&String.fromCharCode(...Array.from(e.slice(p,p+4)))===`CHIP`;){let t=i(e,p+4);if(t<16)break;let n=a(e,p+14);d++,f+=n,p+=t}let m=t[o]??`Unknown(${o})`,h=n?` "${n}"`:``,g=l?` name="${l}"`:``,_=(f/1024).toFixed(0);return{line:`[C64 cart]${h} loading: hwType=${o}(${m}) | ${u} flags, ${_}K actual | ${d} CHIP(s) | ${e.length} bytes${g}`,hwType:o,hwName:m,exrom:s,game:c,bankConfig:u,cartName:l,chipCount:d,totalRomBytes:f}}var s=384,c=272,l=44100,u=class t{wasm;wasmUrl;config;running=!1;frameCount=0;crtPreloadChecksEnabled=!0;onFrame;onAudio;constructor(e,t,n={}){this.wasm=e,this.wasmUrl=t,this.config={videoWidth:s,videoHeight:c,sampleRate:l,audioChannels:1,cyclesPerFrame:50,...n}}static async load(n=`/src/emulator/c64.wasm`,r={}){let i=new t(await e.load(n),n,r);return i.init(),i}init(){let e=this.wasm.exports;if(!e)throw Error(`WASM exports not available`);if(e.c64_init(),this.config.sampleRate){let e=this.wasm.exports.sid_setSampleRate;typeof e==`function`&&e(this.config.sampleRate)}}start(){this.running=!0,this.wasm.exports?.debugger_play?.()}pause(){this.running=!1}isRunning(){return this.running}getFrameCount(){return this.frameCount}reset(){this.wasm.exports?.c64_reset(),this.frameCount=0}async reboot(){let t=this.running,n=await e.load(this.wasmUrl);this.running=!1,this.wasm=n,this.frameCount=0,this.init(),t&&this.start()}setCrtPreloadChecksEnabled(e){this.crtPreloadChecksEnabled=e}static AUDIO_BUFFER_SIZE=4096;tick(e=0){if(!this.running)return;let t=this.wasm.exports,n=t.debugger_update(e);if(this.frameCount++,n&&this.onFrame){let e=t.c64_getPixelBuffer(),n=this.wasm.heap.heapU8.subarray(e,e+s*c*4);this.onFrame({width:s,height:c,data:n,timestamp:this.frameCount})}}loadGame(e){let t=this.wasm.exports;if(!t||!this.wasm.heap)throw Error(`WASM not ready`);if(e.type===`snapshot`){t.c64_reset();let n=this.wasm.allocAndWrite(e.data);try{this.loadSnapshotData(n,e.data.length)}finally{this.wasm.free(n)}return}let n=this.wasm.allocAndWrite(e.data);try{switch(e.type){case`prg`:t.c64_loadPRG(n,e.data.length,1);break;case`d64`:t.c64_setDriveEnabled(1),t.c64_insertDisk(n,e.data.length);break;case`crt`:if(this.crtPreloadChecksEnabled){let t=o(e.data);if(!t)throw Error(`Invalid CRT file format`);let n=r(t);if(n)throw Error(n)}t.c64_loadCartridge(n,e.data.length);break}}finally{this.wasm.free(n)}}removeCartridge(){this.wasm.exports?.c64_removeCartridge(),this.wasm.exports?.c64_reset(),this.frameCount=0}handleInput(e){let t=this.wasm.exports;if(t){if(e.type===`key`&&e.key!==void 0)t.keyboard_keyPressed(Number(e.key));else if(e.type===`joystick`){let n=(e.joystickPort??1)-1;e.direction&&t.c64_joystick_push(n,{up:1,down:2,left:4,right:8}[e.direction]??0),e.fire1&&t.c64_joystick_push(n,16)}}}keyDown(e){this.wasm.exports?.keyboard_keyPressed(e)}keyUp(e){this.wasm.exports?.keyboard_keyReleased(e)}joystickPush(e,t){this.wasm.exports?.c64_joystick_push(e-1,t)}joystickRelease(e,t){this.wasm.exports?.c64_joystick_release(e-1,t)}mousePosition(e,t){this.wasm.exports?.c64_mouse_position(e,t)}setMousePortEnabled(e,t){this.wasm.exports?.c64_set_mouse_port_enabled(e-1,t?1:0)}ramRead(e){return this.wasm.exports?.c64_ramRead(e)??0}ramWrite(e,t){this.wasm.exports?.c64_ramWrite(e,t)}cpuRead(e){return this.wasm.exports?.c64_cpuRead(e)??0}cpuReadNS(e){return this.wasm.exports?.c64_cpuReadNS(e)??0}cpuWrite(e,t){this.wasm.exports?.c64_cpuWrite(e,t)}getPC(){return this.wasm.exports?.c64_getPC()??0}getRegA(){return this.wasm.exports?.c64_getRegA()??0}getRegX(){return this.wasm.exports?.c64_getRegX()??0}getRegY(){return this.wasm.exports?.c64_getRegY()??0}getSP(){return this.wasm.exports?.c64_getSP()??0}getCycleCount(){return this.wasm.exports?.c64_getCycleCount()??0}getFrameBuffer(){if(!this.wasm.exports||!this.wasm.heap)throw Error(`WASM not ready`);let e=this.wasm.exports.c64_getPixelBuffer();return{width:s,height:c,data:this.wasm.heap.heapU8.slice(e,e+s*c*4),timestamp:this.frameCount}}getSnapshot(){let e=this.wasm.exports;if(!e||!this.wasm.heap)throw Error(`WASM not ready`);let t=e.c64_getSnapshot(),n=e.c64_getSnapshotSize();return this.wasm.heap.heapU8.slice(t,t+n)}loadSnapshotData(e,t){let n=this.wasm.exports;if(!n)throw Error(`WASM not ready`);n.c64_loadSnapshot(e,t),this.frameCount=0}debuggerPause(){this.wasm.exports?.debugger_pause()}debuggerPlay(){this.wasm.exports?.debugger_play()}debuggerStep(){this.wasm.exports?.debugger_step()}debuggerIsRunning(){return(this.wasm.exports?.debugger_isRunning()??0)!==0}setDebugSpeed(e){this.wasm.exports?.debugger_set_speed(e)}setSampleRate(e){this.wasm.exports?.sid_setSampleRate(e)}getSidBuffer(){let e=this.wasm.exports;if(!e||!this.wasm.heap)return null;let n=e.sid_getAudioBuffer();return new Float32Array(this.wasm.heap.heapF32.subarray(n>>2,(n>>2)+t.AUDIO_BUFFER_SIZE))}setSIDModel(e){this.wasm.exports?.sid_setModel(e)}setVoiceEnabled(e,t){this.wasm.exports?.sid_setVoiceEnabled(e,t?1:0)}setDriveEnabled(e){this.wasm.exports?.c64_setDriveEnabled(e?1:0)}getDriveEnabled(){return(this.wasm.exports?.c64_getDriveEnabled()??0)!==0}};const d={ARROW_LEFT:0,ONE:1,TWO:2,THREE:3,FOUR:4,FIVE:5,SIX:6,SEVEN:7,EIGHT:8,NINE:9,ZERO:10,PLUS:11,MINUS:12,POUND:13,CLEAR_HOME:14,INS_DEL:15,CTRL:16,Q:17,W:18,E:19,R:20,T:21,Y:22,U:23,I:24,O:25,P:26,AT:27,STAR:28,ARROW_UP:29,RUN_STOP:30,A:31,S:32,D:33,F:34,G:35,H:36,J:37,K:38,L:39,COLON:40,SEMICOLON:41,EQUALS:42,RETURN:43,COMMODORE:44,SHIFT_LEFT:45,Z:46,X:47,C:48,V:49,B:50,N:51,M:52,COMMA:53,PERIOD:54,SLASH:55,SHIFT_RIGHT:56,CURSOR_UP_DOWN:57,CURSOR_LEFT_RIGHT:58,SPACE:59,F1:60,F3:61,F5:62,F7:63,RESTORE:64},f={UP:1,DOWN:2,LEFT:4,RIGHT:8},p=[`up`,`down`,`left`,`right`],m=[`a`,`b`,`x`,`y`,`lb`,`rb`,`lt`,`rt`],h={a:0,b:1,x:2,y:3,lb:4,rb:5,lt:6,rt:7,start:9,up:12,down:13,left:14,right:15};var g=.5;const _=Object.freeze({stick:`8way`,directions:Object.freeze({up:{joystick:`up`},down:{joystick:`down`},left:{joystick:`left`},right:{joystick:`right`}}),buttons:Object.freeze({a:{joystick:`fire`},b:{joystick:`up`},x:{key:d.SPACE},y:null,lb:null,rb:null,lt:null,rt:{key:d.RUN_STOP}})});var v=[`8way`,`4way`,`2way`],y=[`up`,`down`,`left`,`right`,`fire`],ee=new Set(Object.values(d));function te(e,t){if(e===void 0)return t;if(e===null)return null;if(typeof e!=`object`)return t;let{joystick:n,key:r}=e;return y.includes(n)?{joystick:n}:typeof r==`number`&&ee.has(r)?{key:r}:t}function b(e){let t=_,n=v.includes(e?.stick)?e.stick:t.stick,r={};for(let n of p)r[n]=te(e?.directions?.[n],t.directions[n]);let i={};for(let n of m)i[n]=te(e?.buttons?.[n],t.buttons[n]);return{stick:n,directions:r,buttons:i}}function x(e){let t=t=>!!e.buttons?.[t]?.pressed,n=t=>e.axes?.[t]??0,r={up:t(h.up)||n(1)<=-g||n(7)<=-g,down:t(h.down)||n(1)>=g||n(7)>=g,left:t(h.left)||n(0)<=-g||n(6)<=-g,right:t(h.right)||n(0)>=g||n(6)>=g,start:t(h.start)};for(let e of m)r[e]=t(h[e]);return r}function S(e,t,n={}){let r=!!e.up&&!e.down,i=!!e.down&&!e.up,a=!!e.left&&!e.right,o=!!e.right&&!e.left;if(t===`2way`)r=!1,i=!1;else if(t===`4way`&&(r||i)&&(a||o)){let e=r&&!!n.up||i&&!!n.down,t=a&&!!n.left||o&&!!n.right;e&&!t?(a=!1,o=!1):(r=!1,i=!1)}return{up:r,down:i,left:a,right:o}}var ne={up:f.UP,down:f.DOWN,left:f.LEFT,right:f.RIGHT,fire:16};const C=e=>`joystick`in e?`j${e.joystick}`:`k${e.key}`;function w(e,t){let n=new Map,r=e=>{if(!e)return;let t=`joystick`in e?{joystick:ne[e.joystick]}:{key:e.key};n.set(C(t),t)};for(let n of p)e[n]&&r(t.directions[n]);for(let n of m)e[n]&&r(t.buttons[n]);return n}var T=44100,E=class{ctx=null;workletNode=null;gainNode=null;_muted=!1;_volume=.75;_suspended=!0;_initialised=!1;_ready=!1;options;_readSidBuffer=null;onStateChange;constructor(e={}){this.options=e}get muted(){return this._muted}get volume(){return this._volume}get suspended(){return this._suspended}get ready(){return this._ready}get sampleRate(){return this.ctx?.sampleRate??T}async init(){if(this._initialised)return!this._suspended;this._initialised=!0;try{return this.ctx=new AudioContext({sampleRate:T}),this.gainNode=this.ctx.createGain(),this.gainNode.gain.value=this._volume,this.gainNode.connect(this.ctx.destination),this.ctx.addEventListener(`statechange`,()=>{let e=this._suspended;this._suspended=this.ctx?.state===`suspended`,e!==this._suspended&&(this.fireStateChange(),this.feedWorklet())}),this._suspended=this.ctx.state===`suspended`,await this.loadWorklet(),this._suspended&&=(this.ctx.resume().catch(()=>{}),this.ctx.state===`suspended`),this.fireStateChange(),!this._suspended}catch{return!1}}async loadWorklet(){if(!this.ctx||!this.gainNode)return;let e=this.options.assetBaseUrl??`/`,t=this.options.workletUrl??`${e.replace(/\/+$/,``)}/audio-worklet-processor.js`;await this.ctx.audioWorklet.addModule(t),this.workletNode=new AudioWorkletNode(this.ctx,`c64-audio-processor`,{outputChannelCount:[1]}),this.workletNode.connect(this.gainNode),this.workletNode.port.onmessage=()=>{this.feedWorklet()},this._ready=!0,this.feedWorklet()}setSidBufferReader(e){this._readSidBuffer=e,this.feedWorklet()}feedWorklet(){if(!this.workletNode||!this._readSidBuffer||this._suspended)return;let e=this._readSidBuffer();e&&e.length>0&&this.workletNode.port.postMessage(e)}async resume(){if(this.ctx)try{await this.ctx.resume(),this._suspended=this.ctx.state===`suspended`,this.fireStateChange(),this.feedWorklet()}catch(e){console.error(`AudioEngine: resume failed`,e)}}setMuted(e){this._muted=e,this.gainNode&&(this.gainNode.gain.value=e?0:this._volume),this.fireStateChange()}toggleMute(){this.setMuted(!this._muted)}setVolume(e){this._volume=Math.max(0,Math.min(1,e)),this.gainNode&&!this._muted&&(this.gainNode.gain.value=this._volume),this.fireStateChange()}adjustVolume(e){this.setVolume(this._volume+e)}async destroy(){this.workletNode?.disconnect(),this.gainNode?.disconnect(),await this.ctx?.close(),this.workletNode=null,this.gainNode=null,this.ctx=null,this._initialised=!1,this._ready=!1,this._suspended=!0,this._readSidBuffer=null}fireStateChange(){this.onStateChange?.({muted:this._muted,volume:this._volume,suspended:this._suspended})}};const D={ArrowUp:f.UP,ArrowDown:f.DOWN,ArrowLeft:f.LEFT,ArrowRight:f.RIGHT,ControlLeft:16},O={ArrowUp:f.UP,ArrowDown:f.DOWN,ArrowLeft:f.LEFT,ArrowRight:f.RIGHT,KeyZ:16,KeyX:32,KeyC:64,ControlLeft:16};var k={KeyX:32,KeyC:64};function A(e,t,n){let r=e.toLowerCase(),i=n===`keydown`,a=[],o=e=>a.push({key:e,action:`press`}),s=e=>a.push({key:e,action:`release`}),c=e=>a.push({key:e,action:i?`press`:`release`});switch(i&&(t?o(d.SHIFT_LEFT):r!==`arrowup`&&r!==`arrowleft`&&(s(d.SHIFT_LEFT),s(d.SHIFT_RIGHT))),r){case`a`:c(d.A);break;case`b`:c(d.B);break;case`c`:c(d.C);break;case`d`:c(d.D);break;case`e`:c(d.E);break;case`f`:c(d.F);break;case`g`:c(d.G);break;case`h`:c(d.H);break;case`i`:c(d.I);break;case`j`:c(d.J);break;case`k`:c(d.K);break;case`l`:c(d.L);break;case`m`:c(d.M);break;case`n`:c(d.N);break;case`o`:c(d.O);break;case`p`:c(d.P);break;case`q`:c(d.Q);break;case`r`:c(d.R);break;case`s`:c(d.S);break;case`t`:c(d.T);break;case`u`:c(d.U);break;case`v`:c(d.V);break;case`w`:c(d.W);break;case`x`:c(d.X);break;case`y`:c(d.Y);break;case`z`:c(d.Z);break;case`0`:c(d.ZERO);break;case`1`:c(d.ONE);break;case`2`:c(d.TWO);break;case`3`:c(d.THREE);break;case`4`:c(d.FOUR);break;case`5`:c(d.FIVE);break;case`6`:c(d.SIX);break;case`7`:c(d.SEVEN);break;case`8`:c(d.EIGHT);break;case`9`:c(d.NINE);break;case`!`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.ONE);break;case`"`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.TWO);break;case`#`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.THREE);break;case`$`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.FOUR);break;case`%`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.FIVE);break;case`&`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.SIX);break;case`'`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.SEVEN);break;case`(`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.EIGHT);break;case`)`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.NINE);break;case` `:c(d.SPACE);break;case`enter`:c(d.RETURN);break;case`backspace`:case`delete`:c(d.INS_DEL);break;case`escape`:c(d.RUN_STOP);break;case`-`:c(d.MINUS);break;case`=`:c(d.EQUALS);break;case`+`:i&&(s(d.SHIFT_LEFT),s(d.SHIFT_RIGHT)),c(d.PLUS);break;case`*`:i&&(s(d.SHIFT_LEFT),s(d.SHIFT_RIGHT)),c(d.STAR);break;case`@`:i&&(s(d.SHIFT_LEFT),s(d.SHIFT_RIGHT)),c(d.AT);break;case`^`:i&&(s(d.SHIFT_LEFT),s(d.SHIFT_RIGHT)),c(d.ARROW_UP);break;case"`":c(d.ARROW_LEFT);break;case`~`:c(d.ARROW_UP);break;case`\\`:c(d.POUND);break;case`,`:case`<`:c(d.COMMA);break;case`.`:case`>`:c(d.PERIOD);break;case`/`:case`?`:c(d.SLASH);break;case`;`:c(d.SEMICOLON);break;case`:`:i&&(s(d.SHIFT_LEFT),s(d.SHIFT_RIGHT)),c(d.COLON);break;case`[`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.COLON);break;case`]`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.SEMICOLON);break;case`shift`:c(d.SHIFT_LEFT);break;case`tab`:c(d.CTRL);break;case`control`:c(d.COMMODORE);break;case`capslock`:c(d.COMMODORE);break;case`home`:c(d.CLEAR_HOME);break;case`pageup`:c(d.RESTORE);break;case`f1`:c(d.F1);break;case`f2`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.F1);break;case`f3`:c(d.F3);break;case`f4`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.F3);break;case`f5`:c(d.F5);break;case`f6`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.F5);break;case`f7`:c(d.F7);break;case`f8`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.F7);break;case`arrowdown`:c(d.CURSOR_UP_DOWN);break;case`arrowup`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.CURSOR_UP_DOWN);break;case`arrowright`:c(d.CURSOR_LEFT_RIGHT);break;case`arrowleft`:i?o(d.SHIFT_LEFT):s(d.SHIFT_LEFT),c(d.CURSOR_LEFT_RIGHT);break;default:break}return a}var j=128,M=0,N=class{emulator;target;joystickPort;inputMode=`mixed`;updateFrame=-1;gamepadIndex=-1;gamepadMapping=b();physicalGamepadState={};virtualGamepadState={};heldGamepadDirections={};heldGamepadOutputs=new Map;keyboardJoystickMap={...D};mixedJoystickMap={...O};potFire2Pressed=!1;potFire3Pressed=!1;pressedControls=new Set;keyDownHandler=e=>{this.handleKeyDown(e)};keyUpHandler=e=>{this.handleKeyUp(e)};gamepadConnectedHandler=e=>{this.handleGamepadConnected(e)};gamepadDisconnectedHandler=e=>{this.handleGamepadDisconnected(e)};constructor(e,t=window,n=2){this.emulator=e,this.target=t,this.joystickPort=n}attach(){this.target.addEventListener(`gamepadconnected`,this.gamepadConnectedHandler),this.target.addEventListener(`gamepaddisconnected`,this.gamepadDisconnectedHandler),this.target.addEventListener(`keydown`,this.keyDownHandler),this.target.addEventListener(`keyup`,this.keyUpHandler)}detach(){this.target.removeEventListener(`gamepadconnected`,this.gamepadConnectedHandler),this.target.removeEventListener(`gamepaddisconnected`,this.gamepadDisconnectedHandler),this.target.removeEventListener(`keydown`,this.keyDownHandler),this.target.removeEventListener(`keyup`,this.keyUpHandler),this.releaseAll(),this.releaseAllGamepadButtons(),this.cancelUpdate()}step(){let e=navigator.getGamepads();if(!e)return;let t=e[this.gamepadIndex];if(!t){this.physicalGamepadState={},this.applyGamepadState(),this.cancelUpdate();return}this.physicalGamepadState=x(t),this.applyGamepadState(),this.updateFrame=requestAnimationFrame(this.step.bind(this))}applyGamepadState(){let e=this.physicalGamepadState,t=this.virtualGamepadState,n={};for(let r of[...p,...m])n[r]=!!e[r]||!!t[r];let r=S(n,this.gamepadMapping.stick,this.heldGamepadDirections);this.heldGamepadDirections=r;let i=w({...n,...r},this.gamepadMapping);e.start&&i.set(C({key:d.RUN_STOP}),{key:d.RUN_STOP});for(let[e,t]of this.heldGamepadOutputs)i.has(e)||this.releaseGamepadOutput(t);for(let[e,t]of i)this.heldGamepadOutputs.has(e)||this.pushGamepadOutput(t);this.heldGamepadOutputs=i}pushGamepadOutput(e){`joystick`in e?this.emulator.joystickPush(this.joystickPort,e.joystick):this.emulator.keyDown(e.key)}releaseGamepadOutput(e){`joystick`in e?this.emulator.joystickRelease(this.joystickPort,e.joystick):this.emulator.keyUp(e.key)}cancelUpdate(){cancelAnimationFrame(this.updateFrame),this.updateFrame=-1,this.gamepadIndex=-1}releaseAllGamepadButtons(){this.physicalGamepadState={},this.virtualGamepadState={},this.heldGamepadDirections={};for(let e of this.heldGamepadOutputs.values())this.releaseGamepadOutput(e);this.heldGamepadOutputs=new Map}findConnectedGamepadIndex(e){let t=navigator.getGamepads?.()??[];for(let n of t)if(n&&n.index!==e)return n.index;return-1}handleGamepadDisconnected(e){if(console.log(`Gamepad disconnected from index %d: %s`,e.gamepad.index,e.gamepad.id),this.gamepadIndex===e.gamepad.index){this.releaseAllGamepadButtons();let t=this.findConnectedGamepadIndex(e.gamepad.index);t>=0?(this.gamepadIndex=t,this.updateFrame<0&&this.step()):this.cancelUpdate()}let t=new CustomEvent(`c64-controller-disconnected`,{detail:{name:e.gamepad.id,index:e.gamepad.index}});this.target.dispatchEvent(t)}handleGamepadConnected(e){console.log(`Gamepad connected at index %d: %s. %d buttons, %d axes.`,e.gamepad.index,e.gamepad.id,e.gamepad.buttons.length,e.gamepad.axes.length),this.gamepadIndex<0&&(this.gamepadIndex=e.gamepad.index);let t=new CustomEvent(`c64-controller-connected`,{detail:{name:e.gamepad.id,index:e.gamepad.index}});this.target.dispatchEvent(t),this.updateFrame<0&&this.step()}handleKeyDown(e){if(re(e.target))return;if(this.inputMode===`keyboard`){let t=A(e.key,e.shiftKey,`keydown`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}return}if(this.inputMode===`mixed`){if(e.code in this.mixedJoystickMap){let t=this.mixedJoystickMap[e.code];this.pushJoystickInput(t),e.preventDefault()}else{let t=A(e.key,e.shiftKey,`keydown`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}}return}let t=this.getMappedControl(e);!t||this.pressedControls.has(t)||(this.pressedControls.add(t),this.pushJoystickInput(this.keyboardJoystickMap[t]),e.preventDefault())}handleKeyUp(e){if(re(e.target))return;if(this.inputMode===`keyboard`){let t=A(e.key,e.shiftKey,`keyup`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}return}if(this.inputMode===`mixed`){if(e.code in this.mixedJoystickMap){let t=this.mixedJoystickMap[e.code];this.releaseJoystickInput(t),e.preventDefault()}else{let t=A(e.key,e.shiftKey,`keyup`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}}return}let t=this.getMappedControl(e);t&&(this.pressedControls.delete(t),this.releaseJoystickInput(this.keyboardJoystickMap[t]),e.preventDefault())}getMappedControl(e){return e.code in this.keyboardJoystickMap?e.code:null}pushJoystickInput(e){if(e===32){this.potFire2Pressed=!0,this.syncPotFireButtons();return}if(e===64){this.potFire3Pressed=!0,this.syncPotFireButtons();return}this.emulator.joystickPush(this.joystickPort,e)}releaseJoystickInput(e){if(e===32){this.potFire2Pressed=!1,this.syncPotFireButtons();return}if(e===64){this.potFire3Pressed=!1,this.syncPotFireButtons();return}this.emulator.joystickRelease(this.joystickPort,e)}releaseAll(){for(let e of this.pressedControls)this.releaseJoystickInput(this.keyboardJoystickMap[e]);this.pressedControls.clear(),this.potFire2Pressed=!1,this.potFire3Pressed=!1,this.syncPotFireButtons()}syncPotFireButtons(){if(!this.potFire2Pressed&&!this.potFire3Pressed){this.emulator.setMousePortEnabled?.(this.joystickPort,!1);return}this.emulator.setMousePortEnabled?.(this.joystickPort,!0),this.emulator.mousePosition?.(this.potFire2Pressed?M:j,this.potFire3Pressed?M:j)}setKeyboardPort(e){this.joystickPort!==e&&(this.releaseAll(),this.releaseAllGamepadButtons(),this.joystickPort=e)}setInputMode(e){this.inputMode!==e&&(this.releaseAll(),this.releaseAllGamepadButtons(),this.inputMode=e)}getInputMode(){return this.inputMode}setKeyboardJoystickMap(e){this.releaseAll(),this.keyboardJoystickMap={...e},this.mixedJoystickMap={...e,...k}}isJoystickKeyCode(e){return e in this.keyboardJoystickMap||e in this.mixedJoystickMap}setActiveGamepadIndex(e){if(this.gamepadIndex!==e){if(!(navigator.getGamepads?.()??[])[e])throw Error(`Gamepad ${e} is not connected`);this.releaseAllGamepadButtons(),this.gamepadIndex=e,this.updateFrame<0&&this.step()}}getActiveGamepadIndex(){return this.gamepadIndex}setGamepadMapping(e){this.gamepadMapping=b(e),this.heldGamepadDirections={},this.applyGamepadState()}getGamepadMapping(){return this.gamepadMapping}setVirtualGamepadState(e){this.virtualGamepadState={...e},this.applyGamepadState()}};function re(e){return e instanceof Element?e instanceof HTMLInputElement?e.type!==`button`&&e.type!==`checkbox`&&e.type!==`radio`:e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLElement&&e.isContentEditable:!1}var ie=class{emulatorInput;options;captureKeyDown=e=>this.onCaptureKeyDown(e);captureKeyUp=e=>this.onCaptureKeyUp(e);constructor(e,t=window,n={}){this.emulatorInput=new N(e,t),this.options=n}attach(){window.addEventListener(`keydown`,this.captureKeyDown,!0),window.addEventListener(`keyup`,this.captureKeyUp,!0),this.emulatorInput.attach()}detach(){window.removeEventListener(`keydown`,this.captureKeyDown,!0),window.removeEventListener(`keyup`,this.captureKeyUp,!0),this.emulatorInput.detach()}setKeyboardJoystickPort(e){this.emulatorInput.setKeyboardPort(e)}setKeyboardJoystickMap(e){this.emulatorInput.setKeyboardJoystickMap(e)}setInputMode(e){this.emulatorInput.setInputMode(e)}getInputMode(){return this.emulatorInput.getInputMode()}setActiveGamepadIndex(e){this.emulatorInput.setActiveGamepadIndex(e)}getActiveGamepadIndex(){return this.emulatorInput.getActiveGamepadIndex()}setGamepadMapping(e){this.emulatorInput.setGamepadMapping(e)}getGamepadMapping(){return this.emulatorInput.getGamepadMapping()}setVirtualGamepadState(e){this.emulatorInput.setVirtualGamepadState(e)}onCaptureKeyDown(e){if(!P(e.target)&&!this.handleFastForwardShortcut(e)&&this.isJoystickKey(e)){try{if(typeof document<`u`){if(`hidden`in document){if(document.hidden){e.stopImmediatePropagation();return}}else if(typeof document.hasFocus==`function`&&!document.hasFocus()){e.stopImmediatePropagation();return}}}catch{}try{if(typeof document<`u`&&(document.querySelector(`.c64-help-overlay.visible`)||document.querySelector(`.c64-menu-overlay.visible`))){e.stopImmediatePropagation(),e.preventDefault();return}}catch{}}}onCaptureKeyUp(e){if(!P(e.target)&&this.isJoystickKey(e))try{if(typeof document<`u`){if(`hidden`in document){if(document.hidden){e.stopImmediatePropagation();return}}else if(typeof document.hasFocus==`function`&&!document.hasFocus()){e.stopImmediatePropagation();return}if(document.querySelector(`.c64-help-overlay.visible`)||document.querySelector(`.c64-menu-overlay.visible`)){e.stopImmediatePropagation(),e.preventDefault();return}}}catch{}}isJoystickKey(e){return this.emulatorInput.isJoystickKeyCode(e.code)}handleFastForwardShortcut(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.repeat)return!1;let t=e.key===`+`||e.key===`=`||e.code===`Equal`,n=e.key===`-`||e.code===`Minus`,r=e.key===`Backspace`||e.code===`Backspace`;return!t&&!n&&!r?!1:(t?this.options.onFastForwardIncrease?.():n?this.options.onFastForwardDecrease?.():this.options.onFastForwardReset?.(),e.preventDefault(),e.stopImmediatePropagation(),!0)}};function P(e){return e instanceof Element?e instanceof HTMLInputElement?e.type!==`button`&&e.type!==`checkbox`&&e.type!==`radio`:e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLElement&&e.isContentEditable:!1}const F=[{type:`crt`,label:`Cartridge (.crt)`,extensions:[`.crt`]},{type:`prg`,label:`Program (.prg)`,extensions:[`.prg`]},{type:`d64`,label:`Disk image (.d64)`,extensions:[`.d64`]},{type:`snapshot`,label:`Snapshot (.snapshot, .c64, .s64)`,extensions:[`.snapshot`,`.c64`,`.s64`]}];var ae=new Set(F.map(e=>e.type));function I(e){return typeof e==`string`&&ae.has(e)}function L(e){let t=e.toLowerCase();for(let e of F)if(e.extensions.some(e=>t.endsWith(e)))return e.type;return null}function oe(e,t,n=`crt`){return e===`auto`?L(t)??n:e}function se(e){return(e===`auto`?F.flatMap(e=>e.extensions):F.find(t=>t.type===e)?.extensions??[]).join(`,`)}function ce(e){return F.find(t=>t.type===e)?.label??e.toUpperCase()}var R=198,le=631,ue=8,de=650,fe=1500,pe=250,me=2e3,z=100,B=100,he=300,ge=class{emulator=null;inputHandler=null;gamepadMapping=null;disableCrtPreloadChecks=!1;destroyed=!1;diskSessionActive=!1;startupLoadInProgress=!1;startupDiskAutoloadPending=!1;debugSpeed=z;currentGame=null;audio;options;constructor(e){this.options={gameType:`crt`,...e},this.audio=new E(e.audio)}async start(){this.destroyed=!1;let{wasmUrl:e,gameUrl:t,gameData:n,gameSource:r,gameType:i,renderer:a,onProgress:o}=this.options;o?.(10,`INITIALISING WASM...`),this.emulator=await u.load(e),this.emulator.setCrtPreloadChecksEnabled(!this.disableCrtPreloadChecks),this.applyDebugSpeed(),this.attachInputAndRenderer(this.emulator,a);let s=!1;if(n!=null){this.startupLoadInProgress=!0;try{await this.loadGameData(n,i,r??`inline game data`,o)}finally{this.startupLoadInProgress=!1}s=i===`prg`}else if(t&&t!==`null`){this.startupLoadInProgress=!0;try{await this.loadGame(t,i,o)}finally{this.startupLoadInProgress=!1}s=i===`prg`}this.emulator.start(),s&&await this.autoRunPrgIfRunning(),this.startupDiskAutoloadPending&&(this.startupDiskAutoloadPending=!1,await this.autoLoadDiskIfRunning()),this.initAudio()}initAudio(){this.emulator&&(this.audio.onStateChange=e=>{window.dispatchEvent(new CustomEvent(`c64-audio-state`,{detail:e}))},this.audio.setSidBufferReader(()=>this.emulator?.getSidBuffer()??null),this.audio.init().then(e=>{this.emulator&&(this.emulator.setSampleRate(this.audio.sampleRate),e||window.dispatchEvent(new CustomEvent(`c64-audio-suspended`)))}))}async loadGame(e,t=`crt`,n){if(!this.emulator)throw Error(`Emulator not initialised — call start() first`);n?.(20,`LOADING GAME...`);let r=await fetch(e);if(!r.ok)throw Error(`Failed to fetch game: ${r.status}`);let i=Number(r.headers.get(`content-length`)??0),a;if(i>0&&r.body){let e=r.body.getReader(),t=[],o=0,s=await e.read();for(;!s.done;){t.push(s.value),o+=s.value.byteLength;let r=20+Math.round(o/i*65);n?.(r,`LOADING GAME... ${Math.round(o/i*100)}%`),s=await e.read()}a=new Uint8Array(o);let c=0;for(let e of t)a.set(e,c),c+=e.byteLength}else a=new Uint8Array(await r.arrayBuffer());n?.(90,`INSERTING ${ve(t)}...`),await this.insertGameData(a,t,e,{url:e},n)}async loadGameData(e,t=`crt`,n=`inline game data`,r=this.options.onProgress){if(!this.emulator)throw Error(`Emulator not initialised — call start() first`);r?.(20,`LOADING GAME DATA...`);let i=xe(e);r?.(90,`INSERTING ${ve(t)}...`),await this.insertGameData(i,t,n,{source:n},r)}async loadFile(e,t){if(!this.emulator)throw Error(`Emulator not initialised — call start() first`);let n=this.options.onProgress,r=t??L(e.name)??`crt`;try{n?.(20,`READING FILE ${e.name}...`);let t=await e.arrayBuffer(),i=new Uint8Array(t);n?.(90,`INSERTING ${ve(r)}...`),await this.insertGameData(i,r,e.name,{file:e.name},n),window.dispatchEvent(new CustomEvent(`c64-close-dialog`,{detail:{file:e.name,type:r}}))}catch(e){throw n?.(0,`FAILED`),e}}async loadTool(e,t){if(!this.emulator)throw Error(`Emulator not initialised — call start() first`);let n=this.options.onProgress,r=t??L(e)??`prg`;n?.(10,`PREPARING TOOL...`);try{this.emulator.removeCartridge()}catch{}this.emulator.reset(),this.emulator.start(),await V(120),await this.loadGame(e,r,n)}getCurrentGame(){return this.currentGame}detachCartridge(){if(this.emulator)try{this.emulator.removeCartridge(),this.diskSessionActive=!1,this.startupDiskAutoloadPending=!1,this.currentGame=null,window.dispatchEvent(new CustomEvent(`c64-detach`,{detail:{}})),window.dispatchEvent(new CustomEvent(`c64-close-menu`))}catch(e){console.error(`Failed to detach cartridge:`,e)}}hardReset(){if(this.emulator)try{this.emulator.reset(),this.emulator.start(),window.dispatchEvent(new CustomEvent(`c64-hard-reset`,{detail:{}})),window.dispatchEvent(new CustomEvent(`c64-close-menu`))}catch(e){console.error(`Failed to perform hard reset:`,e)}}async reboot(){if(this.emulator)try{await this.emulator.reboot(),this.attachInputAndRenderer(this.emulator,this.options.renderer),this.emulator.start(),this.diskSessionActive=!1,this.startupDiskAutoloadPending=!1,this.currentGame=null,this.emulator.setSampleRate(this.audio.sampleRate),this.applyDebugSpeed(),this.audio.setSidBufferReader(()=>this.emulator?.getSidBuffer()??null),window.dispatchEvent(new CustomEvent(`c64-reboot`,{detail:{}})),window.dispatchEvent(new CustomEvent(`c64-close-menu`))}catch(e){throw console.error(`Failed to reboot emulator:`,e),e}}async destroy(){if(!this.destroyed){this.destroyed=!0;try{this.emulator?.pause()}finally{this.inputHandler?.detach(),this.inputHandler=null,this.options.renderer.detach(),this.audio.onStateChange=void 0,this.audio.setSidBufferReader(()=>null),await this.audio.destroy(),this.emulator=null}}}setKeyboardJoystickPort(e){this.inputHandler?.setKeyboardJoystickPort(e)}setKeyboardJoystickMap(e){this.inputHandler?.setKeyboardJoystickMap(e)}setInputMode(e){this.inputHandler?.setInputMode(e)}setFastForwardSpeed(e){let t=ye(e);return t===this.debugSpeed?this.debugSpeed:(this.debugSpeed=t,this.applyDebugSpeed(),this.notifyDebugSpeedChanged(),this.debugSpeed)}incrementFastForwardSpeed(){return this.setFastForwardSpeed(this.debugSpeed+B)}decrementFastForwardSpeed(){return this.setFastForwardSpeed(this.debugSpeed-B)}resetFastForwardSpeed(){return this.setFastForwardSpeed(z)}getFastForwardSpeed(){return this.debugSpeed}setActiveGamepadIndex(e){this.inputHandler?.setActiveGamepadIndex(e)}getActiveGamepadIndex(){return this.inputHandler?.getActiveGamepadIndex()??-1}setGamepadMapping(e){this.gamepadMapping=e,this.inputHandler?.setGamepadMapping(e)}getGamepadMapping(){return this.inputHandler?.getGamepadMapping()??b(this.gamepadMapping)}setVirtualGamepadState(e){this.inputHandler?.setVirtualGamepadState(e)}getSnapshot(){if(!this.emulator)throw Error(`Emulator not initialised`);return this.emulator.getSnapshot()}ramRead(e){return this.emulator?.ramRead(e)??0}cpuRead(e){return this.emulator?.cpuRead(e)??0}cpuReadNS(e){return this.emulator?.cpuReadNS(e)??0}cpuWrite(e,t){this.emulator?.cpuWrite(e,t)}setVoiceEnabled(e,t){this.emulator?.setVoiceEnabled(e,t)}setCrtPreloadChecksDisabled(e){this.disableCrtPreloadChecks=e,this.emulator?.setCrtPreloadChecksEnabled(!e)}async autoRunPrgIfRunning(){!this.emulator||!this.emulator.isRunning()||(await V(de),await this.insertTextIntoKeyboardBuffer(`run
3
+ `))}async autoLoadDiskIfRunning(){!this.emulator||!this.emulator.isRunning()||(await V(fe),await this.insertTextIntoKeyboardBuffer(`LOAD"*",8,1`),await V(pe),await this.insertTextIntoKeyboardBuffer(`
4
+ `),await this.waitForKeyboardBufferEmpty(),await this.insertTextIntoKeyboardBuffer(`run
5
+ `))}async prepareFirstDiskLoad(){if(!(!this.emulator||this.startupLoadInProgress)){try{this.emulator.removeCartridge()}catch{this.emulator.reset()}this.emulator.start(),await V(120)}}async insertTextIntoKeyboardBuffer(e){if(!this.emulator)return;let t=be(e);for(;t.length>0;){await this.waitForKeyboardBufferEmpty();let e=t.splice(0,ue);this.emulator.cpuWrite(R,e.length);for(let t=0;t<e.length;t+=1)this.emulator.cpuWrite(le+t,e[t])}}async waitForKeyboardBufferEmpty(){let e=Date.now();for(;this.emulator?.cpuRead(R);){if(Date.now()-e>=me)throw Error(`Timed out waiting for C64 keyboard buffer before PRG auto-run`);await V(50)}}async insertGameData(e,t,n,r,i){if(!this.emulator)throw Error(`Emulator not initialised — call start() first`);this.assertSnapshotFormatSupported(e,t,n),this.emitSnapshotLoadInfo(t,n);try{t===`crt`&&this.handleCrtPreloadChecks(e,n,i);let a=t===`d64`&&!this.diskSessionActive;a&&await this.prepareFirstDiskLoad(),this.emulator.loadGame({type:t,data:e}),t===`prg`?(this.diskSessionActive=!1,await this.autoRunPrgIfRunning()):t===`d64`?(this.diskSessionActive=!0,a&&(this.startupLoadInProgress?this.startupDiskAutoloadPending=!0:await this.autoLoadDiskIfRunning())):this.diskSessionActive=!1;let o=Te(n);this.currentGame={name:o,type:t,data:e},i?.(100,`READY!`),window.dispatchEvent(new CustomEvent(`c64-load-success`,{detail:{...r,name:o,type:t}}))}catch(e){throw i?.(0,`FAILED`),console.error(`Failed to insert cartridge or load game:`,e),window.dispatchEvent(new CustomEvent(`c64-load-error`,{detail:{error:e instanceof Error?e.message:String(e),...r,type:t}})),e}}emitSnapshotLoadInfo(e,t){if(e!==`snapshot`)return;let n=`native`,r=`Loading native LVL snapshot (${t})`;console.info(`[snapshot] mode=${n} source=${t}`),window.dispatchEvent(new CustomEvent(`c64-load-info`,{detail:{mode:n,source:t,message:r}}))}assertSnapshotFormatSupported(e,t,n){if(t!==`snapshot`||!we(e))return;let r=Error(`Unsupported snapshot format for ${n}. VICE .vsf snapshots are disabled for now; use LVLLVL/native snapshots (.c64, .snapshot, .s64).`);throw console.error(r),window.dispatchEvent(new CustomEvent(`c64-load-info`,{detail:{mode:`warning`,source:n,message:`Snapshot must be LVLLVL/native format (.c64, .snapshot, .s64).`}})),r}attachInputAndRenderer(e,t){this.inputHandler?.detach(),this.inputHandler=new ie(e,window,{onFastForwardIncrease:()=>this.incrementFastForwardSpeed(),onFastForwardDecrease:()=>this.decrementFastForwardSpeed(),onFastForwardReset:()=>this.resetFastForwardSpeed()}),this.inputHandler.attach(),this.inputHandler.setGamepadMapping(this.gamepadMapping),t.attachTo(e)}applyDebugSpeed(){this.emulator?.setDebugSpeed(this.debugSpeed)}notifyDebugSpeedChanged(){let e=this.debugSpeed===z?`Fast-forward: normal speed`:`Fast-forward: ${this.debugSpeed/z}x`;window.dispatchEvent(new CustomEvent(`c64-load-info`,{detail:{mode:`info`,source:`keyboard`,message:e}}))}handleCrtPreloadChecks(e,t,n){if(!this.disableCrtPreloadChecks){_e(e,t,n);return}let i=o(e,t);if(!i)return;console.log(i.line);let a=r(i);a&&(n?.(90,`UNSAFE CRT LOAD`),console.warn(`${a} Proceeding because preload checks are disabled.`),window.dispatchEvent(new CustomEvent(`c64-load-info`,{detail:{mode:`warning`,source:t,message:`Preload checks are disabled. This cartridge is normally flagged as incompatible and may hang the emulator.`}})))}};function _e(e,t,n){let i=o(e,t);if(!i){n?.(0,`INVALID CRT`);let e=Error(`Invalid CRT file format`);throw console.error(e),e}console.log(i.line);let a=r(i);if(a){n?.(0,`UNSUPPORTED CRT`);let e=Error(a);throw console.error(e),e}}function ve(e){let t=ce(e),n=t.indexOf(` (`);return(n>0?t.slice(0,n):t).toUpperCase()}function V(e){return new Promise(t=>setTimeout(t,e))}function ye(e){if(!Number.isFinite(e))return z;let t=Math.round(e/B)*B;return Math.max(z,Math.min(he,t))}function be(e){let t=[],n=e.toUpperCase().replace(/\r\n/g,`
6
+ `);for(let e=0;e<n.length;e+=1){let r=n.charCodeAt(e);t.push(r===10?13:r)}return t}function xe(e){if(e instanceof Uint8Array)return e;if(typeof e!=`string`)return new Uint8Array(e);let t=e.trim(),n=t.match(/^data:[^,]*;base64,(.*)$/s),r=n?n[1]:t;return n||Ce(r)?Se(globalThis.atob(r.replace(/\s/g,``))):Se(e)}function Se(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function Ce(e){let t=e.replace(/\s/g,``);return t.length>0&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}function we(e){if(e.length<19)return!1;for(let t=0;t<19;t++)if(e[t]!==`VICE Snapshot File`.charCodeAt(t))return!1;return!0}function Te(e){return e.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||e}var Ee=`
7
+ .c64-loader {
8
+ position: relative;
9
+ width: min(768px, calc(100vw - 24px));
10
+ margin-top: 12px;
11
+ transition: opacity 0.6s ease, transform 0.6s ease;
12
+ }
13
+ .c64-loader.hidden {
14
+ opacity: 0;
15
+ transform: translateY(-6px);
16
+ pointer-events: none;
17
+ }
18
+ .c64-loader-label {
19
+ font-family: monospace;
20
+ font-size: 12px;
21
+ color: #7b71d5;
22
+ margin-bottom: 4px;
23
+ letter-spacing: 1px;
24
+ }
25
+ .c64-loader-track {
26
+ width: 100%;
27
+ height: 10px;
28
+ background: #222;
29
+ border: 1px solid #444;
30
+ border-radius: 2px;
31
+ overflow: hidden;
32
+ }
33
+ .c64-loader-fill {
34
+ height: 100%;
35
+ width: 0;
36
+ background: linear-gradient(90deg, #6c6cff 0%, #a8a8ff 50%, #6c6cff 100%);
37
+ background-size: 200% 100%;
38
+ border-radius: 2px;
39
+ transition: width 0.5s cubic-bezier(.22,.61,.36,1);
40
+ animation: c64-shimmer 1.5s linear infinite;
41
+ }
42
+ @keyframes c64-shimmer {
43
+ 0% { background-position: 200% 0; }
44
+ 100% { background-position: -200% 0; }
45
+ }
46
+ `,De=class{canvas;ctx;animationFrameId=null;attachedEmulator=null;loaderEl=null;loaderLabel=null;loaderFill=null;constructor(e){let t=typeof e==`string`?document.getElementById(e):e;if(!(t instanceof HTMLCanvasElement))throw Error(`Canvas not found: ${String(e)}`);let n=t.getContext(`2d`);if(!n)throw Error(`2D canvas context not available`);this.canvas=t,this.ctx=n}ensureLoader(){if(this.loaderEl)return;if(!document.querySelector(`style[data-c64-loader]`)){let e=document.createElement(`style`);e.setAttribute(`data-c64-loader`,``),e.textContent=Ee,document.head.appendChild(e)}let e=document.createElement(`div`);e.className=`c64-loader`;let t=document.createElement(`div`);t.className=`c64-loader-label`,t.textContent=`LOADING...`;let n=document.createElement(`div`);n.className=`c64-loader-track`;let r=document.createElement(`div`);r.className=`c64-loader-fill`,n.appendChild(r),e.appendChild(t),e.appendChild(n),this.canvas.insertAdjacentElement(`afterend`,e),this.loaderEl=e,this.loaderLabel=t,this.loaderFill=r}setProgress(e,t){this.ensureLoader(),this.loaderFill.style.width=`${Math.min(e,100)}%`,this.loaderLabel.textContent=t}setError(e){this.ensureLoader(),this.loaderFill.style.width=`0`,this.loaderFill.style.background=`#f44`,this.loaderLabel.textContent=e}showLoader(){this.ensureLoader(),this.loaderEl&&(this.loaderEl.classList.remove(`hidden`),this.loaderFill&&(this.loaderFill.style.width=`0`,this.loaderFill.style.background=``))}hideLoader(e=600){if(!this.loaderEl)return;let t=this.loaderEl;setTimeout(()=>{t.classList.add(`hidden`),t.addEventListener(`transitionend`,()=>t.remove(),{once:!0})},e),this.loaderEl=null,this.loaderLabel=null,this.loaderFill=null}render(e){(this.canvas.width!==e.width||this.canvas.height!==e.height)&&(this.canvas.width=e.width,this.canvas.height=e.height);let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);this.ctx.putImageData(t,0,0)}attachTo(e){this.detach(),this.attachedEmulator=e,e.onFrame=e=>{this.render(e)};let t=0,n=r=>{let i=t?r-t:0;t=r,e.tick(i),this.animationFrameId=requestAnimationFrame(n)};this.animationFrameId=requestAnimationFrame(n)}detach(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.attachedEmulator&&=(this.attachedEmulator.onFrame=void 0,null)}},Oe=`c64-ready-local-roms`,H=`rom-files`,ke=2;function Ae(e){let t=typeof e.romPath==`string`?e.romPath:e.rom?.path;return typeof t==`string`?t.trim():``}function je(e){return I(e.rom?.type)?e.rom.type:L(Ae(e))??void 0}async function Me(e,t){let n=await Fe(e);return n?{file:new File([n.blob],n.name,{type:n.blob.type}),type:t??n.type,romPath:e}:null}async function Ne(e,t){let n=window.showOpenFilePicker;if(!n)return null;let[r]=await n({multiple:!1,types:[{description:`C64 ROM files`,accept:{"application/octet-stream":se(t??`auto`).split(`,`)}}]});if(!r)return null;let i=await r.getFile();return await Pe(e,i,t),{file:i,type:t??L(i.name)??`crt`,romPath:e}}async function Pe(e,t,n){let r=n??L(t.name)??`crt`,i=await Ie();await new Promise((n,a)=>{let o=i.transaction(H,`readwrite`);o.objectStore(H).put({romPath:e,name:t.name,type:r,blob:t}),o.oncomplete=()=>n(),o.onerror=()=>a(o.error??Error(`Unable to store ROM file`))}),i.close()}async function Fe(e){if(typeof indexedDB>`u`)return null;let t=await Ie(),n=await new Promise((n,r)=>{let i=t.transaction(H,`readonly`).objectStore(H).get(e);i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error??Error(`Unable to read ROM file`))});return t.close(),!n?.blob||!n.name||!I(n.type)?null:n}function Ie(){return new Promise((e,t)=>{let n=indexedDB.open(Oe,ke);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(H)||e.createObjectStore(H,{keyPath:`romPath`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??Error(`Unable to open local ROM store`))})}function Le(e,t,n={}){if(!e)return n.disableDefault?``:`${t}games/cartridges/legend-of-wilf.crt`;let r=e.trim();return r?r.toLowerCase()===`null`?``:/^https?:\/\//i.test(r)||r.startsWith(`/`)?r:`${t}${r.replace(/^\/+/,``)}`:n.disableDefault?``:`${t}games/cartridges/legend-of-wilf.crt`}function Re(e,t){if(!e)return``;let n=e.trim();return n?/^https?:\/\//i.test(n)?n:n.startsWith(`/@fs/`)?`${t.replace(/\/+$/,``)}${n}`:n.startsWith(`/`)?n:`${t}${n.replace(/^\/+/,``)}`:``}function ze(e,t){let n=e.trim();if(!n)return``;if(/^https?:\/\//i.test(n))return n;let r=t.replace(/\/+$/,``);return n.startsWith(`${r}/@fs/`)?n.slice(r.length):n.startsWith(`/@fs/`)?n:n.startsWith(`/`)?`/@fs${n}`:n}function Be(e){return!e.has(`game`)&&!!e.get(`cheevos`)?.trim()&&!!e.get(`cheevosSet`)?.trim()}const Ve=[`prg`,`crt`,`d64`];var He=`c64-ultimate-bridge-url`,Ue=`c64-ultimate-ip`,We=`c64-ultimate-password`;function Ge(){return{bridgeUrl:et(He)||`http://localhost:6464`,ip:et(Ue),password:et(We)}}function Ke(e){e.bridgeUrl!==void 0&&tt(He,e.bridgeUrl||`http://localhost:6464`),e.ip!==void 0&&tt(Ue,e.ip),e.password!==void 0&&tt(We,e.password)}function qe(e){return typeof e==`string`&&Ve.includes(e)}function Je(e){let t=e.trim();return/^(?:\d{1,3}\.){3}\d{1,3}$/.test(t)&&t.split(`.`).every(e=>Number(e)<=255)}async function Ye(e){let{bridgeUrl:t,ip:n,password:r}=e;return await U(t,`/ultimate/info`,{ip:n,password:r})}async function Xe(e,t){let{bridgeUrl:n,ip:r,password:i}=e;await U(n,`/ultimate/launch`,{ip:r,password:i,fileType:t.fileType,filename:t.filename,fileBase64:$e(t.data),autoLoadCommand:t.autoLoadCommand??`LOAD"*",8,1
47
+ RUN`,joyPort:t.joyPort??2})}async function Ze(e){let{bridgeUrl:t,ip:n,password:r}=e;await U(t,`/ultimate/reboot`,{ip:n,password:r})}async function Qe(e){let{bridgeUrl:t,ip:n,password:r}=e;await U(t,`/ultimate/poweroff`,{ip:n,password:r,timeoutMs:1500},2500)}function $e(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}async function U(e,t,n,r){let i=(e||`http://localhost:6464`).replace(/\/$/,``),a=r?new AbortController:null,o=a?window.setTimeout(()=>a.abort(),r):null,s;try{s=await fetch(`${i}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n),signal:a?.signal})}catch(e){throw e?.name===`AbortError`?Error(`The Ultimate bridge at ${i} did not respond in time.`,{cause:e}):Error(`Could not reach the Ultimate bridge at ${i}. Start it with: npx @c64cade/ultimate-bridge`,{cause:e})}finally{o!==null&&window.clearTimeout(o)}let c=await s.json().catch(()=>null);if(!s.ok)throw Error(c?.error||`Bridge request failed: ${s.status}`);return c}function et(e){try{return window.localStorage.getItem(e)??``}catch{return``}}function tt(e,t){try{t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e)}catch{}}var nt=class{deviceInfo=null;busy=!1;els;container;getPlayer;constructor(e,t){this.container=e,this.getPlayer=t}init(){this.render(),this.bind(),this.updateCurrentGame(),this.updateControls(),Je(this.settings().ip)&&this.connect({silent:!0})}render(){let e=Ge();this.container.innerHTML=`
48
+ <label class="c64-section-label">Ultimate Player</label>
49
+ <div class="c64-section-hint">
50
+ Play games on a real Ultimate 64, C64 Ultimate or Ultimate II+. Run the
51
+ <a href="https://www.npmjs.com/package/@c64cade/ultimate-bridge" target="_blank" rel="noopener noreferrer">C64Cade Ultimate Bridge</a>
52
+ on this computer first: <code>npx @c64cade/ultimate-bridge</code>
53
+ </div>
54
+ <div class="c64-form-row">
55
+ <label for="c64-ultimate-bridge-url">Bridge URL</label>
56
+ <input id="c64-ultimate-bridge-url" class="c64-text-input" type="url" placeholder="http://localhost:6464" />
57
+ </div>
58
+ <div class="c64-form-row">
59
+ <label for="c64-ultimate-ip">Ultimate IP</label>
60
+ <input id="c64-ultimate-ip" class="c64-text-input" type="text" inputmode="decimal" placeholder="192.168.0.10" />
61
+ </div>
62
+ <div class="c64-form-row">
63
+ <label for="c64-ultimate-password">Password</label>
64
+ <input id="c64-ultimate-password" class="c64-text-input" type="password" autocomplete="off" placeholder="(optional)" />
65
+ </div>
66
+ <div class="c64-menu-actions">
67
+ <button class="c64-btn" id="c64-ultimate-connect" type="button">Connect</button>
68
+ <span class="c64-inline-status" id="c64-ultimate-device">Not connected</span>
69
+ </div>
70
+
71
+ <div class="c64-tools-section">
72
+ <label class="c64-section-label">Launch on Ultimate</label>
73
+ <div class="c64-form-row">
74
+ <button class="c64-btn" id="c64-ultimate-send-current" type="button">Send Current Game</button>
75
+ <span class="c64-inline-status" id="c64-ultimate-current-game"></span>
76
+ </div>
77
+ <div class="c64-form-row">
78
+ <button class="c64-btn" id="c64-ultimate-send-file" type="button">Send File…</button>
79
+ <span class="c64-inline-status">.prg, .crt or .d64</span>
80
+ <input id="c64-ultimate-file" class="c64-file-input" type="file" accept=".prg,.crt,.d64" />
81
+ </div>
82
+ </div>
83
+
84
+ <div class="c64-tools-section">
85
+ <label class="c64-section-label">Device</label>
86
+ <div class="c64-system-actions">
87
+ <button class="c64-btn" id="c64-ultimate-reboot" type="button">Reboot Ultimate</button>
88
+ <button class="c64-btn" id="c64-ultimate-poweroff" type="button">Power Off</button>
89
+ </div>
90
+ </div>
91
+ <div class="c64-cheat-status" id="c64-ultimate-status" role="status"></div>
92
+ `;let t=e=>this.container.querySelector(e);this.els={bridgeUrl:t(`#c64-ultimate-bridge-url`),ip:t(`#c64-ultimate-ip`),password:t(`#c64-ultimate-password`),connectBtn:t(`#c64-ultimate-connect`),device:t(`#c64-ultimate-device`),currentGame:t(`#c64-ultimate-current-game`),sendCurrentBtn:t(`#c64-ultimate-send-current`),sendFileBtn:t(`#c64-ultimate-send-file`),fileInput:t(`#c64-ultimate-file`),rebootBtn:t(`#c64-ultimate-reboot`),powerOffBtn:t(`#c64-ultimate-poweroff`),status:t(`#c64-ultimate-status`)},this.els.bridgeUrl.value=e.bridgeUrl===`http://localhost:6464`?``:e.bridgeUrl,this.els.ip.value=e.ip,this.els.password.value=e.password}bind(){[this.els.bridgeUrl,this.els.ip,this.els.password].forEach(e=>{e.addEventListener(`input`,()=>this.saveFields()),e.addEventListener(`change`,()=>{this.saveFields(),this.deviceInfo=null,this.updateControls()})}),this.els.connectBtn.addEventListener(`click`,()=>void this.connect()),this.els.sendCurrentBtn.addEventListener(`click`,()=>void this.sendCurrentGame()),this.els.sendFileBtn.addEventListener(`click`,()=>this.els.fileInput.click()),this.els.fileInput.addEventListener(`change`,()=>{let e=this.els.fileInput.files?.[0];this.els.fileInput.value=``,e&&this.sendFile(e)}),this.els.rebootBtn.addEventListener(`click`,()=>void this.reboot()),this.els.powerOffBtn.addEventListener(`click`,()=>void this.powerOff());let e=()=>{this.updateCurrentGame(),this.updateControls()};window.addEventListener(`c64-load-success`,e),window.addEventListener(`c64-detach`,e),window.addEventListener(`c64-reboot`,e)}settings(){return{bridgeUrl:this.els.bridgeUrl.value.trim()||`http://localhost:6464`,ip:this.els.ip.value.trim(),password:this.els.password.value}}saveFields(){Ke({bridgeUrl:this.els.bridgeUrl.value.trim(),ip:this.els.ip.value.trim(),password:this.els.password.value})}async connect({silent:e=!1}={}){await this.run(e?``:`Connecting to Ultimate…`,async()=>{this.saveFields();let t=this.settings();if(!Je(t.ip))throw Error(`Enter your Ultimate's IPv4 address, e.g. 192.168.0.10.`);return this.deviceInfo=null,this.deviceInfo=await Ye(t),e?``:`Connected to ${this.describeDevice()}`},{silentErrors:e})}async sendCurrentGame(){let e=this.currentGame();if(e){if(!qe(e.type)){this.setStatus(`Ultimate can't launch ${e.type} files — only .prg, .crt and .d64.`,`error`);return}await this.launch(e.name,e.type,e.data)}}async sendFile(e){let t=L(e.name);if(!qe(t)){this.setStatus(`${e.name} isn't a .prg, .crt or .d64 file.`,`error`);return}await this.launch(e.name,t,new Uint8Array(await e.arrayBuffer()))}async launch(e,t,n){await this.run(`Sending ${e} to Ultimate…`,async()=>(await Xe(this.settings(),{filename:e,fileType:t,data:n}),`Launched ${e} on ${this.describeDevice()}`))}async reboot(){confirm(`Reboot the Ultimate? Anything running on it will be lost.`)&&await this.run(`Rebooting Ultimate…`,async()=>(await Ze(this.settings()),`Ultimate rebooted`))}async powerOff(){confirm(`Power off the Ultimate? You will need to switch it back on by hand.`)&&await this.run(`Powering off Ultimate…`,async()=>(await Qe(this.settings()),this.deviceInfo=null,`Ultimate powered off`))}async run(e,t,{silentErrors:n=!1}={}){if(!this.busy){this.busy=!0,e&&this.setStatus(e),this.updateControls();try{let n=await t();n?this.setStatus(n,`ok`):e&&this.setStatus(``)}catch(e){n?this.setStatus(``):this.setStatus(rt(e),`error`)}finally{this.busy=!1,this.updateControls()}}}describeDevice(){let e=this.deviceInfo?.product||`Ultimate`,t=this.settings().ip;return t?`${e} at ${t}`:e}currentGame(){return this.getPlayer()?.getCurrentGame?.()??null}updateCurrentGame(){let e=this.currentGame();this.els.currentGame.textContent=e?e.name:`No game loaded`}updateControls(){if(this.deviceInfo){let e=this.deviceInfo,t=[e.firmware_version&&`firmware ${e.firmware_version}`,e.fpga_version&&`FPGA ${e.fpga_version}`].filter(Boolean);this.els.device.textContent=`● ${this.describeDevice()}${t.length?` (${t.join(`, `)})`:``}`,this.els.device.dataset.connected=`true`}else this.els.device.textContent=`Not connected`,delete this.els.device.dataset.connected;let e=!!this.deviceInfo,t=this.currentGame();this.els.connectBtn.disabled=this.busy,this.els.connectBtn.textContent=e?`Reconnect`:`Connect`,this.els.sendCurrentBtn.disabled=this.busy||!e||!t,this.els.sendFileBtn.disabled=this.busy||!e,this.els.rebootBtn.disabled=this.busy||!e,this.els.powerOffBtn.disabled=this.busy||!e}setStatus(e,t=`info`){this.els.status.textContent=e,this.els.status.hidden=!e,this.els.status.dataset.mode=t}};function rt(e){return e instanceof Error?e.message:String(e)}const it=[`standard`,`full`,`stretch`],at=`c64-display-mode`;function ot(e){return typeof e==`string`&&it.includes(e)}function st(e,t){return e===`stretch`?`stretch`:e===`full`||t.fullscreen?`contain`:t.touch?t.portrait?`fill-width`:`contain`:`standard`}function ct(e){return e===`contain`||e===`stretch`}const lt=`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>`;function ut(e=document){let t=e,n=t.documentElement,r=typeof n.requestFullscreen==`function`||typeof n.webkitRequestFullscreen==`function`,i=t.fullscreenEnabled??t.webkitFullscreenEnabled??r;return r&&i!==!1}function dt(e=document){let t=e;return!!(t.fullscreenElement??t.webkitFullscreenElement)}async function ft(e=document){let t=e;if(dt(t)){await(t.exitFullscreen?t.exitFullscreen():t.webkitExitFullscreen?.());return}let n=t.documentElement;n.requestFullscreen?await n.requestFullscreen({navigationUI:`hide`}):await n.webkitRequestFullscreen?.()}var pt=`modulepreload`,mt=function(e){return`/c64-ready/`+e},ht={};const W=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=mt(t,n),t in ht)return;ht[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:pt,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})};var gt=`
93
+ .c64-help-btn,.c64-hamburger,.c64-unmute-btn{position:fixed;top:12px;width:36px;height:36px;border-radius:6px;border:2px solid #444;background:#111;color:#ddd;cursor:pointer;display:flex;align-items:center;justify-content:center;z-index:1000}.c64-help-btn{right:12px;border-radius:50%;color:#7b71d5;font-family:monospace;font-size:18px;font-weight:bold}.c64-hamburger{left:12px;font-family:monospace}.c64-unmute-btn{left:56px;color:#f44;z-index:1010}.c64-unmute-btn.hidden{opacity:0;pointer-events:none}.c64-help-overlay,.c64-menu-overlay{position:fixed;inset:0;background:rgba(0,0,0,.7);display:flex;align-items:center;justify-content:center;z-index:1001;opacity:0;transition:opacity .25s ease;pointer-events:none}.c64-help-overlay.visible,.c64-menu-overlay.visible{opacity:1;pointer-events:auto}.c64-help-dialog,.c64-menu-panel{background:#1a1a2e;border:2px solid #555;border-radius:6px;padding:24px 32px;max-width:760px;width:90%;font-family:monospace;color:#ccc;position:relative}.c64-changelog-dialog{max-height:70vh;overflow:auto}.c64-help-dialog h2{margin:0 0 8px;font-size:16px;color:#7b71d5;letter-spacing:1px}.c64-help-dialog p{margin:0 0 16px;font-size:13px;line-height:1.5;color:#aaa}.c64-help-dialog a{color:#a8a8ff;text-decoration:none}.c64-help-controls,.c64-help-special{margin:0 0 12px;padding:0;list-style:none;font-size:13px}.c64-help-controls li,.c64-help-special li{display:flex;justify-content:space-between;padding:4px 0;border-bottom:1px solid #2a2a3e}.c64-help-key{background:#2a2a3e;border:1px solid #444;border-radius:3px;padding:1px 8px;font-size:12px;color:#ddd}.c64-help-close{position:absolute;top:10px;right:14px;background:none;border:none;color:#888;font-size:20px;cursor:pointer}.c64-version{display:flex;justify-content:end;font-size:12px;color:#999;margin-top:36px}.c64-menu-overlay{align-items:flex-start;justify-content:flex-start;padding:48px 24px;background:rgba(0,0,0,.5);z-index:1002}.c64-menu-panel{min-width:320px;max-width:520px;padding:16px;background:#0f0f1a;border-color:#333}.c64-menu-header{display:flex;align-items:center;justify-content:space-between}.c64-settings-tabs,.c64-menu-actions,.c64-system-actions,.c64-radio-row,.c64-gamepad-list{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px}.c64-settings-tab,.c64-btn,.c64-mute-btn{background:#222;border:1px solid #444;color:#ddd;padding:6px 10px;border-radius:4px;cursor:pointer}.c64-settings-tab.active,.c64-gamepad-btn.active{border-color:#7b71d5;color:#fff;background:#25253d}.c64-select{background:#171729;color:#ddd;border:1px solid #444;border-radius:4px;padding:4px 8px;font-family:monospace}.c64-form-row,.c64-audio-row,.c64-cart-preview{display:flex;align-items:center;gap:10px;margin-bottom:10px}.c64-section-label,.c64-audio-section label{display:block;margin:0 0 8px;font-size:13px;color:#aaa}.c64-section-hint,.c64-volume-label,.c64-cart-type{font-size:11px;color:#888}.c64-dragarea{border:2px dashed #2a2a3e;border-radius:6px;padding:12px;margin-top:12px;text-align:center;color:#aaa}.c64-dragarea.dragover{border-color:#7b71d5;color:#fff}.c64-file-input{display:none}.c64-volume-slider{flex:1}.c64-cart-filename{font-size:13px;color:#ccc;word-break:break-all}.c64-checkbox-row{display:inline-flex;gap:8px;align-items:center;color:#ccc;font-size:13px}
94
+ .c64-menu-overlay{align-items:center;justify-content:center;padding:0;background:rgba(0,0,0,.7)}
95
+ .c64-menu-panel{max-width:760px;width:90%;min-width:0;max-height:82vh;overflow:auto;padding:24px 32px;background:#1a1a2e;border:2px solid #555;border-radius:6px;color:#ccc;font-family:monospace;box-shadow:none}
96
+ .c64-menu-header{display:block;margin:0 0 16px;padding:0;border:0}.c64-menu-header h2{margin:0;font-size:16px;color:#7b71d5;letter-spacing:1px;text-transform:none}.c64-menu-close{position:absolute;top:10px;right:14px;background:none;border:none;color:#888;font-size:20px;cursor:pointer}
97
+ .c64-settings-tabs{display:flex;gap:8px;flex-wrap:wrap;margin:0 0 18px;padding:0;border:0;background:transparent}.c64-settings-tab{background:#2a2a3e;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:12px;padding:4px 10px;cursor:pointer}.c64-settings-tab.active{background:#3a335f;border-color:#7b71d5;color:#fff}
98
+ .c64-section-label{display:block;margin:0 0 8px;color:#7b71d5;font-size:13px;letter-spacing:1px;text-transform:uppercase}.c64-form-row,.c64-radio-row,.c64-system-actions,.c64-menu-actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:0 0 12px}.c64-form-row label{color:#aaa;font-size:13px}
99
+ .c64-select,.c64-file-input{background:#111827;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:13px;padding:5px 8px}.c64-btn{background:#2a2a3e;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:12px;padding:5px 10px;cursor:pointer}.c64-btn:hover:not(:disabled){border-color:#7b71d5;color:#fff}.c64-btn:disabled,.c64-select:disabled{opacity:.55;cursor:not-allowed}
100
+ .c64-btn.active{background:#3a335f;border-color:#7b71d5;color:#fff}
101
+ .c64-dragarea{border:1px dashed #555;border-radius:6px;background:#111827;color:#aaa;padding:18px;margin:0 0 12px;text-align:center}.c64-dragarea.dragover{border-color:#7b71d5;background:#1f1b38;color:#fff}.c64-cart-preview,.c64-tools-section{background:#151527;border:1px solid #2a2a3e;border-radius:6px;padding:12px;margin:12px 0}.c64-section-hint{color:#888;font-size:12px;line-height:1.4;margin:4px 0 12px}.c64-checkbox-row{display:flex;align-items:center;gap:8px;color:#ccc;font-size:13px;margin:14px 0 4px}
102
+ .c64-text-input,.c64-textarea{background:#111827;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:13px;padding:5px 8px}.c64-text-input{min-width:180px}.c64-textarea{box-sizing:border-box;width:100%;min-height:120px;resize:vertical}.c64-cheevos-json-file{display:none}.c64-inline-status{color:#888;font-size:12px}
103
+ .c64-cheat-list{display:grid;gap:12px;margin:0 0 12px}.c64-cheat-card{background:#151527;border:1px solid #2a2a3e;border-radius:6px;padding:12px}.c64-cheat-card-header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 10px;color:#ddd;font-size:13px}.c64-cheat-remove{background:none;border:0;color:#ff9a9a;cursor:pointer;font:inherit;font-size:12px}.c64-cheat-grid{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:8px 10px;align-items:center}.c64-cheat-input{background:#111827;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:13px;min-width:0;padding:5px 8px}.c64-cheat-error{color:#ff9a9a;font-size:12px;margin:8px 0 0}.c64-cheat-status{color:#aaa;font-size:12px;line-height:1.4;margin:8px 0 0}.c64-cheat-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}@media (max-width:600px){.c64-cheat-grid{grid-template-columns:1fr}.c64-cheat-grid label{margin-top:4px}}
104
+ .c64-help-dialog,.c64-menu-panel{box-sizing:border-box;max-height:calc(100vh - 32px);max-height:calc(100dvh - 32px);overflow-y:auto;overscroll-behavior:contain;-webkit-overflow-scrolling:touch}.c64-menu-panel{max-height:min(82vh,calc(100dvh - 32px))}.c64-changelog-dialog{max-height:min(70vh,calc(100dvh - 32px))}
105
+ .c64-help-controls{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:24px;margin:0 0 8px}.c64-help-controls li{align-items:center;gap:8px;padding:3px 0}.c64-help-keys{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:4px}.c64-help-key{font-family:inherit;white-space:nowrap}.c64-help-dialog p.c64-help-note{margin:4px 0 0;font-size:12px;color:#888}.c64-help-dialog .c64-version{margin-top:16px}.c64-help-dialog h3{margin:16px 0 6px;font-size:13px;color:#a8a8ff;letter-spacing:1px;text-transform:uppercase}.c64-help-key-note{font-size:12px;color:#888;font-style:italic}.c64-keymap-dialog .c64-help-close{position:sticky;top:0;float:right;margin:-12px -18px 0 0}
106
+ @media (max-width:560px){.c64-help-controls{grid-template-columns:1fr}.c64-help-dialog,.c64-menu-panel{padding:20px 16px;width:calc(100% - 24px)}}
107
+ .c64-cheat-status[data-mode=ok]{color:#8fd694}.c64-cheat-status[data-mode=error]{color:#f77}#c64-ultimate-device[data-connected]{color:#8fd694}.c64-settings-section .c64-section-hint a{color:#a8a8ff;text-decoration:none}
108
+ `;function _t(e,t){return`${(e??`/`).replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}var vt=[[`Joystick`,[`↑`,`↓`,`←`,`→`]],[`Fire`,[`Z`,`Left Ctrl`]],[`Fast-forward`,[`Alt +`,`Alt −`]],[`Normal speed`,[`Alt ⌫`]],[`Run/Stop`,[`Esc`]],[`Inst/Del`,[`⌫`,`Del`]],[`Clr/Home`,[`Home`]],[`Commodore`,[`Ctrl`,`Caps Lock`]],[`Control`,[`Tab`]],[`£`,[`\\`]],[`← / ↑ glyphs`,["`",`^`]],[`F1–F8`,[`F1–F8`]]],yt=[[`Joystick`,[[`Up / Down`,[`↑`,`↓`]],[`Left / Right`,[`←`,`→`]],[`Fire`,[`Z`,`Left Ctrl`]]]],[`Emulator`,[[`Faster`,[`Alt +`]],[`Slower`,[`Alt −`]],[`Normal speed`,[`Alt ⌫`]]]],[`C64 keyboard`,[[`Run/Stop`,[`Esc`]],[`Restore`,[],`not supported yet`],[`Return`,[`Enter`]],[`Shift`,[`Shift`]],[`Inst/Del`,[`⌫`,`Del`]],[`Clr/Home`,[`Home`]],[`Commodore`,[`Ctrl`,`Caps Lock`]],[`Control`,[`Tab`]],[`F1–F8`,[`F1–F8`]],[`← (arrow left)`,["`"]],[`↑ (arrow up)`,[`^`,`~`]],[`£ (pound)`,[`\\`]],[`Colon / Semicolon`,[`:`,`;`,`[`,`]`]],[`Slash`,[`/`,`?`]],[`Comma / Period`,[`,`,`.`,`<`,`>`]],[`Letters, numbers, + − * = @`,[],`as typed`]]]];function bt([e,t,n]){return`<li><span>${e}</span><span class="c64-help-keys">${t.map(e=>`<kbd class="c64-help-key">${e}</kbd>`).join(``)}${n?`<span class="c64-help-key-note">${n}</span>`:``}</span></li>`}var xt=`c64-disable-crt-preload-checks`,St=`c64-cheevos-dev-detector`,Ct=`c64-cheevos-dev-json-path`,wt=`c64-cheevos-tracker-visible`,Tt=`c64cade.cheatMode.v1`,Et=1800,Dt=[{value:`increment`,label:`Increment`},{value:`decrement`,label:`Decrement`},{value:`set`,label:`Set`}];function Ot(e=new Date){let t=e=>String(e).padStart(2,`0`);return`snapshot-${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}.c64`}function kt(e={}){return{id:e.id??`cheat-${Date.now()}-${Math.random().toString(36).slice(2)}`,address:typeof e.address==`string`?e.address:`0x004e`,action:Dt.some(t=>t.value===e.action)?e.action:`increment`,setValue:typeof e.setValue==`string`?e.setValue:`0xff`,keyBinding:Rt(e.keyBinding)}}function At(e){return!e||typeof e!=`object`?null:kt(e)}function jt(e){return!!e}function Mt(){let e=[kt()];try{let t=localStorage.getItem(Tt),n=t?JSON.parse(t):null,r=Array.isArray(n?.cheats)?n.cheats.map(At).filter(jt):[At(n)].filter(jt);return r.length?r:e}catch(t){return console.warn(`Failed to load cheat config:`,t),e}}function Nt(e){return e.reduce((e,t)=>{let n=String(t.id).match(/^cheat-(\d+)$/);return n?Math.max(e,Number(n[1])+1):e},1)}function Pt(e){let t=e.trim().toLowerCase();if(!t)return null;let n=t.startsWith(`0x`)?t.slice(2):t.startsWith(`$`)?t.slice(1):t;if(!/^[0-9a-f]{1,4}$/.test(n))return null;let r=Number.parseInt(n,16);return Number.isInteger(r)&&r>=0&&r<=65535?r:null}function Ft(e){let t=e.trim().toLowerCase();if(!t)return null;let n=t.startsWith(`0x`)?t.slice(2):t.startsWith(`$`)?t.slice(1):t;if(!/^[0-9a-f]{1,2}$/.test(n))return null;let r=Number.parseInt(n,16);return Number.isInteger(r)&&r>=0&&r<=255?r:null}function It(e){return`0x${(e&255).toString(16).padStart(2,`0`)}`}function Lt(e){return`0x${(e&65535).toString(16).padStart(4,`0`)}`}function Rt(e){if(!e||typeof e!=`object`||!(`code`in e))return null;let t=e;return t.code?{code:String(t.code),key:String(t.key||t.code),label:String(t.label||Bt(t.key,t.code))}:null}function zt(e){return{code:e.code||e.key,key:e.key,label:Bt(e.key,e.code)}}function Bt(e,t){return t===`ControlLeft`?`Left Ctrl`:t===`ControlRight`?`Right Ctrl`:e===` `?`Space`:e?.startsWith(`Arrow`)?e.replace(`Arrow`,`Arrow `):/^Key[A-Z]$/.test(t||``)?(t||``).slice(3):/^Digit[0-9]$/.test(t||``)?(t||``).slice(5):e||t||``}function Vt(e){let t=e,n=t?.tagName?.toLowerCase();return n===`input`||n===`select`||n===`textarea`||!!t?.isContentEditable}function Ht(e=new Date){return`c64-ready-${e.toISOString().replace(/[-:]/g,``).replace(/\.\d{3}z$/i,`z`)}-ram.bin`}var Ut=class e{static activeController=null;helpOverlay=null;settingsOverlay=null;fileInput=null;player=null;options;cheats=Mt();recordingCheatId=null;nextCheatId=Nt(this.cheats);cheatStatus=``;cheatNoticeTimer=null;handleCheatKeyDown=t=>{if(e.activeController!==this||this.recordingCheatId||t.repeat||Vt(t.target))return;let n=this.cheats.find(e=>this.matchesCheatKey(t,e));n&&(t.preventDefault(),t.stopPropagation(),this.applyCheatAction(n))};displayMode=`standard`;fullscreenBtn=null;keymapOverlay=null;touchQuery=null;portraitQuery=null;connectedGamepads=new Map;handleControllerConnected=e=>{let t=e.detail;typeof t?.index==`number`&&(this.connectedGamepads.set(t.index,{index:t.index,name:t.name??`Gamepad ${t.index}`}),this.renderGamepadButtons())};handleControllerDisconnected=e=>{let t=e.detail;typeof t?.index==`number`&&(this.connectedGamepads.delete(t.index),this.renderGamepadButtons())};constructor(e={}){this.options=e}init(t){e.activeController=this,this.player=t??null,this.syncConnectedGamepads(),this.injectCSS(),this.createButton(),this.createDialog(),this.createHamburger(),this.createMenu(),this.createUnmuteButton(),this.createFullscreenButton(),this.initDisplayLayout(),window.addEventListener(`keydown`,this.handleCheatKeyDown,!0),window.addEventListener(`c64-controller-connected`,this.handleControllerConnected),window.addEventListener(`c64-controller-disconnected`,this.handleControllerDisconnected)}syncConnectedGamepads(){this.connectedGamepads.clear();let e=navigator.getGamepads?.()??[];for(let t of e)t&&this.connectedGamepads.set(t.index,{index:t.index,name:t.id})}getConnectedGamepads(){return Array.from(this.connectedGamepads.values()).sort((e,t)=>e.index-t.index)}getGamepadLabel(e){let t=e.name.replace(/\s*\([^)]*\)\s*$/u,``).trim()||e.name.trim()||`Gamepad ${e.index}`;return`${e.index}: ${t}`}renderGamepadButtons(){let e=document.getElementById(`c64-gamepad-list`),t=document.getElementById(`c64-gamepad-empty`);if(!e||!t)return;let n=this.getConnectedGamepads(),r=this.player?.getActiveGamepadIndex()??-1;e.replaceChildren(...n.map(e=>{let t=document.createElement(`button`),n=e.index===r;return t.type=`button`,t.className=`c64-btn c64-gamepad-btn${n?` active`:``}`,t.textContent=this.getGamepadLabel(e),t.setAttribute(`aria-pressed`,n?`true`:`false`),t.addEventListener(`click`,()=>{this.player&&(this.player.setActiveGamepadIndex(e.index),this.renderGamepadButtons())}),t})),t.hidden=n.length>0}downloadSnapshot(e){let t=new Uint8Array(e.byteLength);t.set(e);let n=new Blob([t],{type:`application/bin`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=Ot(),document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(r)}downloadBytes(e,t){let n=new Uint8Array(t.byteLength);n.set(t);let r=new Blob([n],{type:`application/octet-stream`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=e,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(i)}promptForCheevosJsonUrl(e,t,n){let r=e,i=r.path||r.webkitRelativePath||``;if(i){this.updateCheevosJsonUrl(i,e.name,t,n);return}let a=localStorage.getItem(Ct)??``,o=window.prompt(`Optional: enter the absolute path to this cheevos JSON to update the URL for refresh.`,a);o?.trim()&&this.updateCheevosJsonUrl(o,e.name,t,n)}updateCheevosJsonUrl(e,t,n,r){let i=ze(e,this.options.assetBaseUrl??`/`);if(!i)return;localStorage.setItem(Ct,e.trim());let a=new URLSearchParams(window.location.search),o=n?.value.trim()??``;o&&a.set(`cheevos`,o),a.set(`cheevosSet`,i),a.has(`game`)||a.delete(`game`);let s=a.toString();window.history.replaceState(null,``,`${window.location.pathname}${s?`?${s}`:``}${window.location.hash}`),r.textContent=`Loaded JSON from ${t}; updated URL cheevosSet=${i}`}saveCheatConfig(){localStorage.setItem(Tt,JSON.stringify({cheats:this.cheats.map(e=>({id:e.id,address:e.address,action:e.action,setValue:e.setValue,keyBinding:e.keyBinding}))}))}getCheatAddressError(e){return e.address.trim()?Pt(e.address)===null?`Use a valid address from 0x0000 to 0xffff.`:``:`Enter a C64 memory address.`}getCheatSetValueError(e){return e.action===`set`?e.setValue.trim()?Ft(e.setValue)===null?`Use a valid byte value from 0x00 to 0xff.`:``:`Enter a byte value to set.`:``}isCheatReady(e){return!this.getCheatAddressError(e)&&!this.getCheatSetValueError(e)&&!!e.keyBinding?.code}matchesCheatKey(e,t){let n=t.keyBinding;return!n?.code||!this.isCheatReady(t)?!1:e.code===n.code?!0:!!n.key&&e.key?.toLowerCase()===n.key.toLowerCase()}setCheatStatus(e){this.cheatStatus=e;let t=document.getElementById(`c64-cheat-status`);t&&(t.textContent=e,t.hidden=!e),this.cheatNoticeTimer!==null&&window.clearTimeout(this.cheatNoticeTimer),this.cheatNoticeTimer=window.setTimeout(()=>{this.cheatNoticeTimer=null},Et)}applyCheatAction(e){let t=Pt(e.address);if(t===null){this.setCheatStatus(this.getCheatAddressError(e));return}let n=e.action===`set`?Ft(e.setValue):null;if(e.action===`set`&&n===null){this.setCheatStatus(this.getCheatSetValueError(e));return}if(!this.player||typeof this.player.cpuRead!=`function`||typeof this.player.cpuWrite!=`function`){this.setCheatStatus(`Emulator memory is not ready yet.`);return}let r=this.player.cpuRead(t)&255,i=e.action===`set`?n:e.action===`decrement`?r+255&255:r+1&255;this.player.cpuWrite(t,i);let a=Dt.find(t=>t.value===e.action)?.label??`Updated`;this.setCheatStatus(`${a} ${Lt(t)}: ${It(r)} -> ${It(i)}`)}addCheat(){this.cheats=[...this.cheats,kt({id:`cheat-${this.nextCheatId++}`,address:``})],this.saveCheatConfig(),this.renderCheats()}removeCheat(e){this.cheats.length<=1||(this.cheats=this.cheats.filter(t=>t.id!==e),this.recordingCheatId===e&&(this.recordingCheatId=null),this.saveCheatConfig(),this.renderCheats())}renderCheats(){let e=document.getElementById(`c64-cheat-list`);if(!e)return;e.replaceChildren(...this.cheats.map((e,t)=>{let n=document.createElement(`article`);n.className=`c64-cheat-card`,n.addEventListener(`keydown`,e=>e.stopPropagation()),n.addEventListener(`keyup`,e=>e.stopPropagation());let r=document.createElement(`div`);r.className=`c64-cheat-card-header`;let i=document.createElement(`span`);if(i.textContent=`Cheat ${t+1}`,r.appendChild(i),this.cheats.length>1){let t=document.createElement(`button`);t.type=`button`,t.className=`c64-cheat-remove`,t.textContent=`Remove`,t.addEventListener(`click`,()=>this.removeCheat(e.id)),r.appendChild(t)}let a=document.createElement(`div`);a.className=`c64-cheat-grid`;let o=document.createElement(`input`);o.id=`c64-cheat-address-${e.id}`,o.className=`c64-cheat-input`,o.type=`text`,o.inputMode=`text`,o.spellcheck=!1,o.autocomplete=`off`,o.placeholder=`0x004e`,o.value=e.address,o.addEventListener(`input`,()=>{e.address=o.value,this.saveCheatConfig()}),a.appendChild(this.makeLabel(o.id,`Memory address`)),a.appendChild(o);let s=document.createElement(`select`);s.id=`c64-cheat-action-${e.id}`,s.className=`c64-cheat-input`;for(let t of Dt){let n=document.createElement(`option`);n.value=t.value,n.textContent=t.label,n.selected=e.action===t.value,s.appendChild(n)}if(s.addEventListener(`change`,()=>{e.action=s.value,this.saveCheatConfig(),this.renderCheats()}),a.appendChild(this.makeLabel(s.id,`Action`)),a.appendChild(s),e.action===`set`){let t=document.createElement(`input`);t.id=`c64-cheat-set-value-${e.id}`,t.className=`c64-cheat-input`,t.type=`text`,t.inputMode=`text`,t.spellcheck=!1,t.autocomplete=`off`,t.placeholder=`0xff`,t.value=e.setValue,t.addEventListener(`input`,()=>{e.setValue=t.value,this.saveCheatConfig()}),a.appendChild(this.makeLabel(t.id,`Set value`)),a.appendChild(t)}let c=document.createElement(`button`);c.id=`c64-cheat-key-${e.id}`,c.type=`button`,c.className=`c64-btn${this.recordingCheatId===e.id?` active`:``}`,c.textContent=this.recordingCheatId===e.id?`Press a key...`:e.keyBinding?.label??`Choose key...`,c.addEventListener(`click`,()=>{this.recordingCheatId=e.id,this.renderCheats(),document.getElementById(c.id)?.focus()}),c.addEventListener(`keydown`,t=>{this.recordingCheatId===e.id&&(t.preventDefault(),t.stopPropagation(),e.keyBinding=zt(t),this.recordingCheatId=null,this.saveCheatConfig(),this.renderCheats())}),a.appendChild(this.makeLabel(c.id,`Key press`)),a.appendChild(c);let l=document.createElement(`div`);l.className=`c64-cheat-actions`;let u=document.createElement(`button`);if(u.type=`button`,u.className=`c64-btn`,u.textContent=`Apply Now`,u.disabled=!this.isCheatReady(e),u.addEventListener(`click`,()=>this.applyCheatAction(e)),l.appendChild(u),this.recordingCheatId===e.id){let e=document.createElement(`button`);e.type=`button`,e.className=`c64-btn`,e.textContent=`Cancel Key`,e.addEventListener(`click`,()=>{this.recordingCheatId=null,this.renderCheats()}),l.appendChild(e)}if(e.keyBinding){let t=document.createElement(`button`);t.type=`button`,t.className=`c64-btn`,t.textContent=`Clear Key`,t.addEventListener(`click`,()=>{e.keyBinding=null,this.saveCheatConfig(),this.renderCheats()}),l.appendChild(t)}let d=this.getCheatAddressError(e)||this.getCheatSetValueError(e);if(n.appendChild(r),n.appendChild(a),n.appendChild(l),d){let e=document.createElement(`p`);e.className=`c64-cheat-error`,e.textContent=d,n.appendChild(e)}return n}));let t=document.getElementById(`c64-cheat-status`);t&&(t.textContent=this.cheatStatus,t.hidden=!this.cheatStatus)}makeLabel(e,t){let n=document.createElement(`label`);return n.htmlFor=e,n.textContent=t,n}dumpC64Ram(){if(!this.player||typeof this.player.ramRead!=`function`){this.setCheatStatus(`Emulator RAM is not ready yet.`);return}try{let e=new Uint8Array(65536);for(let t=0;t<=65535;t+=1)e[t]=this.player.ramRead(t)&255;let t=Ht();this.downloadBytes(t,e),this.setCheatStatus(`Dumped 64K RAM to ${t}`)}catch(e){this.setCheatStatus(e instanceof Error?e.message:`Failed to dump C64 RAM.`)}}injectCSS(){if(document.querySelector(`style[data-c64-help]`))return;let e=document.createElement(`style`);e.setAttribute(`data-c64-help`,``),e.textContent=gt+`
109
+ html[data-c64-layout=fill-width] #c64-screen{border:none;width:100vw;height:auto}
110
+ html[data-c64-layout=contain] #c64-screen{border:none;height:auto;width:min(100vw,calc(100vh * 384 / 272));width:min(100vw,calc(100dvh * 384 / 272))}
111
+ html[data-c64-layout=stretch] #c64-screen{border:none;aspect-ratio:auto;object-fit:fill;width:100vw;height:100vh;height:100dvh}
112
+ html[data-c64-fill],html[data-c64-fill] body{overflow:hidden;overscroll-behavior:none}
113
+ html[data-c64-fill] body{height:100vh;height:100dvh;min-height:0}
114
+ html[data-c64-fill] .c64-help-btn,html[data-c64-fill] .c64-hamburger,html[data-c64-fill] .c64-fullscreen-btn,html[data-c64-fill] .c64-unmute-btn:not(.hidden){opacity:.4;transition:opacity .2s ease}
115
+ html[data-c64-fill] .c64-help-btn:hover,html[data-c64-fill] .c64-hamburger:hover,html[data-c64-fill] .c64-fullscreen-btn:hover,html[data-c64-fill] .c64-unmute-btn:not(.hidden):hover,html[data-c64-fill] .c64-help-btn:focus-visible,html[data-c64-fill] .c64-hamburger:focus-visible,html[data-c64-fill] .c64-fullscreen-btn:focus-visible{opacity:1}
116
+ html[data-c64-fill] .c64-loader{position:fixed;left:50%;bottom:16px;margin:0;translate:-50% 0;z-index:950}
117
+ .c64-fullscreen-btn{position:fixed;top:12px;right:56px;width:36px;height:36px;padding:0;border-radius:6px;border:2px solid #444;background:#111;color:#ddd;cursor:pointer;display:flex;align-items:center;justify-content:center;z-index:1000}
118
+ .c64-fullscreen-btn svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
119
+ `,document.head.appendChild(e)}getVersionLabel(){let e=this.options.appVersion??`0.0.0`,t=this.options.gitHash;return`v${e}${t?` (build: ${t})`:``}`}createButton(){let e=document.createElement(`button`);e.className=`c64-help-btn`,e.textContent=`?`,e.title=`Help`,e.addEventListener(`click`,()=>this.open()),document.body.appendChild(e)}createDialog(){let e=document.createElement(`div`);e.className=`c64-help-overlay`,e.addEventListener(`click`,t=>{t.target===e&&this.close()}),e.innerHTML=`
120
+ <div class="c64-help-dialog">
121
+ <button class="c64-help-close">&times;</button>
122
+ <h2>C64 READY</h2>
123
+ <p>A Commodore 64 emulator running in the browser via WebAssembly.</p>
124
+ <p><a href="https://github.com/hayesmaker/c64-ready" target="_blank" rel="noopener">Source code on GitHub</a> · <a href="#" id="c64-view-changelog">View changelog</a></p>
125
+ <h2>CONTROLS</h2>
126
+ <ul class="c64-help-controls">${vt.map(([e,t])=>bt([e,t])).join(``)}</ul>
127
+ <p class="c64-help-note">Other keys type as on your keyboard. <a href="#" id="c64-view-keymap">Full keyboard map &rarr;</a></p>
128
+ <div class="c64-version">${this.getVersionLabel()}</div>
129
+ </div>
130
+ `,e.querySelector(`.c64-help-close`).addEventListener(`click`,()=>this.close()),document.body.appendChild(e),this.helpOverlay=e;let t=document.createElement(`div`);t.className=`c64-help-overlay`,t.style.zIndex=`1003`,t.innerHTML=`
131
+ <div class="c64-help-dialog c64-changelog-dialog">
132
+ <button class="c64-help-close">&times;</button>
133
+ <h2>CHANGELOG</h2>
134
+ <div id="c64-changelog-content">Loading...</div>
135
+ </div>
136
+ `,t.querySelector(`.c64-help-close`).addEventListener(`click`,()=>t.classList.remove(`visible`)),document.body.appendChild(t);let n=e.querySelector(`#c64-view-changelog`);n&&n.addEventListener(`click`,e=>{e.preventDefault(),this.loadAndShowChangelog(t)});let r=yt.map(([e,t])=>`<h3>${e}</h3><ul class="c64-help-controls">${t.map(bt).join(``)}</ul>`).join(``),i=document.createElement(`div`);i.className=`c64-help-overlay c64-keymap-overlay`,i.style.zIndex=`1003`,i.innerHTML=`
137
+ <div class="c64-help-dialog c64-keymap-dialog">
138
+ <button class="c64-help-close" aria-label="Close">&times;</button>
139
+ <h2>KEYBOARD MAP</h2>
140
+ <p class="c64-help-note">Mixed input mode (the default): arrows and Z / Left Ctrl drive the joystick, every other key goes to the C64 keyboard. Change it under Settings &rarr; Input.</p>
141
+ ${r}
142
+ </div>
143
+ `;let a=()=>i.classList.remove(`visible`);i.addEventListener(`click`,e=>{e.target===i&&a()}),i.querySelector(`.c64-help-close`).addEventListener(`click`,a),document.body.appendChild(i),this.keymapOverlay=i,e.querySelector(`#c64-view-keymap`).addEventListener(`click`,e=>{e.preventDefault();let t=i.querySelector(`.c64-help-dialog`);t&&(t.scrollTop=0),i.classList.add(`visible`)})}async loadAndShowChangelog(e){e.classList.add(`visible`);try{let t=await fetch(this.options.changelogUrl??_t(this.options.assetBaseUrl,`CHANGELOG.md`),{cache:`no-store`});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=(await t.text()).split(`
144
+ `).filter(e=>{let t=e.trim();return t.startsWith(`- `)?/^- (feat|fix)[:(]/.test(t):!0}).join(`
145
+ `),[{marked:r},i]=await Promise.all([W(()=>import(`./marked.esm-DhpYx7TE.js`),[]),W(()=>import(`./purify.es-CWuqV7zK.js`),[])]),a=i.default.sanitize(r.parse(n)),o=e.querySelector(`#c64-changelog-content`);o.innerHTML=a}catch{let t=e.querySelector(`#c64-changelog-content`);t.innerHTML=`<p>No changelog found.</p>`}}initDisplayLayout(){let e=null;try{e=window.localStorage.getItem(at)}catch{}this.displayMode=ot(e)?e:`standard`,typeof window.matchMedia==`function`&&(this.touchQuery=window.matchMedia(`(hover: none) and (pointer: coarse)`),this.portraitQuery=window.matchMedia(`(orientation: portrait)`),this.touchQuery.addEventListener?.(`change`,this.applyDisplayLayout),this.portraitQuery.addEventListener?.(`change`,this.applyDisplayLayout)),document.addEventListener(`fullscreenchange`,this.applyDisplayLayout),document.addEventListener(`webkitfullscreenchange`,this.applyDisplayLayout),this.setDisplayMode(this.displayMode,{persist:!1})}setDisplayMode(e,{persist:t=!0}={}){if(this.displayMode=e,t)try{window.localStorage.setItem(at,e)}catch{}let n=document.querySelector(`input[name="c64-display-mode"][value="${e}"]`);n&&(n.checked=!0),document.getElementById(`c64-screen`)?.setAttribute(`data-display-mode`,e),this.applyDisplayLayout(),window.dispatchEvent(new CustomEvent(`c64-display-mode-changed`,{detail:{mode:e}}))}getDisplayMode(){return this.displayMode}applyDisplayLayout=()=>{let e=dt(),t=st(this.displayMode,{fullscreen:e,touch:this.touchQuery?.matches??!1,portrait:this.portraitQuery?.matches??!1}),n=document.documentElement;n.setAttribute(`data-c64-layout`,t),n.toggleAttribute(`data-c64-fill`,ct(t)),n.toggleAttribute(`data-c64-fullscreen`,e),this.fullscreenBtn&&(this.fullscreenBtn.innerHTML=e?`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>`:lt,this.fullscreenBtn.title=e?`Exit fullscreen`:`Fullscreen`,this.fullscreenBtn.setAttribute(`aria-label`,this.fullscreenBtn.title))};async toggleFullscreen(){try{await ft()}catch(e){console.warn(`[c64-ready] fullscreen request failed:`,e)}}createFullscreenButton(){if(!ut())return;let e=document.createElement(`button`);e.className=`c64-fullscreen-btn`,e.type=`button`,e.innerHTML=lt,e.title=`Fullscreen`,e.setAttribute(`aria-label`,`Fullscreen`),e.addEventListener(`click`,()=>{e.blur(),this.toggleFullscreen()}),document.body.appendChild(e),this.fullscreenBtn=e}createHamburger(){let e=document.createElement(`button`);e.className=`c64-hamburger`,e.innerHTML=`&#9776;`,e.title=`Menu`,e.addEventListener(`click`,()=>this.toggleMenu()),document.body.appendChild(e)}createMenu(){let e=document.createElement(`div`);e.className=`c64-menu-overlay`,e.addEventListener(`click`,t=>{t.target===e&&this.closeMenu()});let t=[{id:`load`,label:`Load`},{id:`input`,label:`Input`},{id:`display`,label:`Display`},{id:`audio`,label:`Audio`},{id:`cheevos`,label:`Cheevos`},{id:`cheats`,label:`Cheats`},{id:`ultimate`,label:`Ultimate`},{id:`system`,label:`System`}],n=F.map(e=>`<option value="${e.type}">${e.label}</option>`).join(``),r=document.createElement(`div`);r.className=`c64-menu-panel`,r.innerHTML=`
146
+ <div class="c64-menu-header">
147
+ <h2>Settings</h2>
148
+ <button class="c64-menu-close">&times;</button>
149
+ </div>
150
+ <div class="c64-menu-body">
151
+ <div class="c64-settings-tabs" role="tablist" aria-label="Settings sections">
152
+ ${t.map((e,t)=>`<button class="c64-settings-tab${t===0?` active`:``}" data-settings-tab="${e.id}" role="tab" aria-selected="${t===0?`true`:`false`}">${e.label}</button>`).join(``)}
153
+ </div>
154
+
155
+ <div class="c64-settings-sections">
156
+ <section class="c64-settings-section" data-settings-section="load">
157
+ <label class="c64-section-label">Load Game</label>
158
+ <div class="c64-form-row">
159
+ <label for="c64-load-format">Format</label>
160
+ <select id="c64-load-format" class="c64-select">
161
+ <option value="auto">Auto detect (recommended)</option>
162
+ ${n}
163
+ </select>
164
+ </div>
165
+ <div class="c64-dragarea" id="c64-dragarea">
166
+ <span id="c64-dragarea-copy">Drop a game file here or</span>
167
+ <button class="c64-btn" id="c64-browse">Browse</button>
168
+ </div>
169
+ <input class="c64-file-input" id="c64-file-input" type="file" />
170
+ <div class="c64-cart-preview" id="c64-cart-preview" hidden>
171
+ <div class="c64-cart-icon" id="c64-cart-icon" aria-hidden="true">
172
+ <svg width="48" height="32" viewBox="0 0 48 32" xmlns="http://www.w3.org/2000/svg"><rect x="2" y="4" width="44" height="24" rx="3" fill="#222" stroke="#555"/><rect x="6" y="8" width="36" height="12" fill="#2b2b3d"/></svg>
173
+ </div>
174
+ <div>
175
+ <div class="c64-cart-filename" id="c64-cart-filename"></div>
176
+ <div class="c64-cart-type" id="c64-cart-type"></div>
177
+ </div>
178
+ </div>
179
+ <div class="c64-menu-actions">
180
+ <button class="c64-btn" id="c64-load-btn">Load</button>
181
+ <button class="c64-btn" id="c64-close-menu">Close</button>
182
+ </div>
183
+ <div class="c64-tools-section">
184
+ <label class="c64-section-label">Tools</label>
185
+ <div class="c64-form-row">
186
+ <select id="c64-tool-select" class="c64-select c64-tool-select" disabled>
187
+ <option value="">No tools found</option>
188
+ </select>
189
+ <button class="c64-btn" id="c64-load-tool-btn" disabled>Load Tool</button>
190
+ </div>
191
+ <div class="c64-section-hint" id="c64-tools-status">Loading tools…</div>
192
+ </div>
193
+ </section>
194
+
195
+ <section class="c64-settings-section" data-settings-section="input" hidden>
196
+ <label class="c64-section-label">Input Port</label>
197
+ <div class="c64-radio-row">
198
+ <label><input type="radio" name="c64-joy-port" value="1" /> Port 1</label>
199
+ <label><input type="radio" name="c64-joy-port" value="2" checked /> Port 2</label>
200
+ </div>
201
+ <label class="c64-section-label">Input Mode</label>
202
+ <div class="c64-radio-row c64-radio-row-wrap">
203
+ <label><input type="radio" name="c64-input-mode" value="joystick" /> Joystick</label>
204
+ <label><input type="radio" name="c64-input-mode" value="keyboard" /> Keyboard</label>
205
+ <label><input type="radio" name="c64-input-mode" value="mixed" checked /> Mixed</label>
206
+ </div>
207
+ <div id="c64-input-mode-hint" class="c64-section-hint">Arrows + Z + Ctrl = joystick &amp; all other keys &rarr; C64 keyboard</div>
208
+ <label class="c64-section-label">Gamepads</label>
209
+ <div id="c64-gamepad-list" class="c64-gamepad-list"></div>
210
+ <div id="c64-gamepad-empty" class="c64-section-hint">To use a gamepad, connect it to your computer and press any button.</div>
211
+ </section>
212
+
213
+ <section class="c64-settings-section" data-settings-section="display" hidden>
214
+ <label class="c64-section-label">Display Mode</label>
215
+ <div class="c64-radio-row">
216
+ <label><input type="radio" name="c64-display-mode" value="standard" checked /> Standard</label>
217
+ <label><input type="radio" name="c64-display-mode" value="full" /> Full</label>
218
+ <label><input type="radio" name="c64-display-mode" value="stretch" /> Stretch</label>
219
+ </div>
220
+ <div class="c64-section-hint">Standard: 2x size on desktop; fills the screen width on phones in portrait and the screen height in landscape. Full: as large as the window allows. Stretch: fills the window, ignoring the aspect ratio.</div>
221
+ <div class="c64-menu-actions">
222
+ <button class="c64-btn" id="c64-fullscreen-toggle" type="button">Toggle Fullscreen</button>
223
+ </div>
224
+ </section>
225
+
226
+ <section class="c64-settings-section" data-settings-section="audio" hidden>
227
+ <div id="c64-audio-section-anchor"></div>
228
+ </section>
229
+
230
+ <section class="c64-settings-section" data-settings-section="cheevos" hidden>
231
+ <label class="c64-section-label">Cheevos Dev</label>
232
+ <div class="c64-section-hint">Load a c64-cheevos detector and optional achievement set JSON for local development.</div>
233
+ <div class="c64-form-row">
234
+ <label for="c64-cheevos-detector">Detector ID</label>
235
+ <input id="c64-cheevos-detector" class="c64-text-input" type="text" placeholder="uridium" />
236
+ </div>
237
+ <div class="c64-form-row">
238
+ <button class="c64-btn" id="c64-cheevos-browse-json-btn" type="button">Load JSON File</button>
239
+ <span class="c64-inline-status" id="c64-cheevos-json-filename">No JSON file loaded</span>
240
+ <input id="c64-cheevos-json-file" class="c64-cheevos-json-file" type="file" accept="application/json,.json" />
241
+ </div>
242
+ <textarea id="c64-cheevos-json" class="c64-textarea" spellcheck="false" placeholder='{ "_id": "set1", "cheevos": [{ "_id": "zinc", "title": "Zinc", "description": "Clear level 1" }] }'></textarea>
243
+ <div class="c64-menu-actions">
244
+ <button class="c64-btn" id="c64-cheevos-enable-btn">Enable</button>
245
+ <button class="c64-btn" id="c64-cheevos-disable-btn">Disable</button>
246
+ <button class="c64-btn" id="c64-cheevos-choose-rom-btn" type="button" disabled>Choose ROM File</button>
247
+ <button class="c64-btn" id="c64-cheevos-clear-popped-btn">Clear Unlocks</button>
248
+ <button class="c64-btn" id="c64-cheevos-clear-scores-btn">Clear Scores</button>
249
+ </div>
250
+ <input id="c64-cheevos-rom-file" class="c64-cheevos-json-file" type="file" accept=".crt,.prg,.d64" />
251
+ <label class="c64-checkbox-row" for="c64-cheevos-tracker-visible">
252
+ <input type="checkbox" id="c64-cheevos-tracker-visible" />
253
+ Show tracker panel
254
+ </label>
255
+ <div class="c64-section-hint">Shows the cheevos tracker beside the emulator in Standard display mode.</div>
256
+ <div class="c64-section-hint" id="c64-cheevos-status">Cheevos dev tracking is disabled.</div>
257
+ </section>
258
+
259
+ <section class="c64-settings-section" data-settings-section="cheats" hidden>
260
+ <label class="c64-section-label">Cheat Mode</label>
261
+ <div class="c64-section-hint">Bind keys to change C64 memory bytes while the game is running. Values wrap between 0x00 and 0xff.</div>
262
+ <div class="c64-cheat-list" id="c64-cheat-list"></div>
263
+ <div class="c64-menu-actions">
264
+ <button class="c64-btn" id="c64-add-cheat-btn" type="button">Add Cheat</button>
265
+ </div>
266
+ <div class="c64-tools-section">
267
+ <label class="c64-section-label">Memory Tools</label>
268
+ <div class="c64-menu-actions">
269
+ <button class="c64-btn" id="c64-dump-ram-btn" type="button">Dump 64K RAM</button>
270
+ </div>
271
+ <div class="c64-section-hint">Downloads raw C64 RAM from $0000-$ffff as a .bin file for address inspection.</div>
272
+ <div class="c64-cheat-status" id="c64-cheat-status" hidden></div>
273
+ </div>
274
+ </section>
275
+
276
+ <section class="c64-settings-section" data-settings-section="ultimate" hidden>
277
+ <div id="c64-ultimate-section-anchor"></div>
278
+ </section>
279
+
280
+ <section class="c64-settings-section" data-settings-section="system" hidden>
281
+ <label class="c64-section-label">System Actions</label>
282
+ <div class="c64-system-actions">
283
+ <button class="c64-btn" id="c64-save-snapshot-btn">Save Snapshot</button>
284
+ <button class="c64-btn" id="c64-detach-btn">Detach Cartridge</button>
285
+ <button class="c64-btn" id="c64-reset-btn">Hard Reset</button>
286
+ <button class="c64-btn" id="c64-reboot-btn">Reboot Emulator</button>
287
+ </div>
288
+ <label class="c64-checkbox-row" for="c64-disable-crt-preload-checks">
289
+ <input type="checkbox" id="c64-disable-crt-preload-checks" />
290
+ Disable crt preload checks
291
+ </label>
292
+ <div class="c64-section-hint">Allows any .crt file and skips compatibility prechecks.</div>
293
+ </section>
294
+ </div>
295
+ </div>
296
+ `,r.querySelector(`.c64-menu-close`).addEventListener(`click`,()=>this.closeMenu()),r.querySelector(`#c64-close-menu`).addEventListener(`click`,()=>this.closeMenu()),e.appendChild(r),document.body.appendChild(e),this.settingsOverlay=e;let i=r.querySelectorAll(`[data-settings-tab]`),a=r.querySelectorAll(`[data-settings-section]`),o=e=>{i.forEach(t=>{let n=t.getAttribute(`data-settings-tab`)===e;t.classList.toggle(`active`,n),t.setAttribute(`aria-selected`,n?`true`:`false`)}),a.forEach(t=>{t.hidden=t.getAttribute(`data-settings-section`)!==e})};i.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.getAttribute(`data-settings-tab`);t&&o(t)})}),this.fileInput=r.querySelector(`#c64-file-input`);let s=r.querySelector(`#c64-dragarea`),c=r.querySelector(`#c64-dragarea-copy`),l=r.querySelector(`#c64-browse`),u=r.querySelector(`#c64-load-format`),d=r.querySelector(`#c64-tool-select`),f=r.querySelector(`#c64-load-tool-btn`),p=r.querySelector(`#c64-tools-status`),m=r.querySelector(`#c64-cart-preview`),h=r.querySelector(`#c64-cart-filename`),g=r.querySelector(`#c64-cart-type`),_=()=>{let e=u.value??`auto`;this.fileInput.accept=se(e),e===`auto`?c.textContent=`Drop a game file here or`:c.textContent=`Drop a ${ce(e)} file here or`};_(),u.addEventListener(`change`,_);let v=e=>{let t=oe(u.value??`auto`,e.name);m.hidden=!1,h.textContent=e.name,g.textContent=ce(t);let n=new CustomEvent(`c64-load-file`,{detail:{file:e,type:t}});window.dispatchEvent(n)};s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`dragover`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`dragover`)}),s.addEventListener(`drop`,e=>{e.preventDefault(),s.classList.remove(`dragover`);let t=e.dataTransfer?.files?.[0];t&&v(t)}),l.addEventListener(`click`,()=>this.fileInput?.click()),this.fileInput.addEventListener(`change`,()=>{let e=this.fileInput?.files?.[0];e&&v(e)}),r.querySelector(`#c64-load-btn`).addEventListener(`click`,()=>{let e=this.fileInput?.files?.[0];e?v(e):this.fileInput?.click()});let y=[],ee=()=>{if(d.innerHTML=``,y.length===0){let e=document.createElement(`option`);e.value=``,e.textContent=`No tools found`,d.appendChild(e),d.disabled=!0,f.disabled=!0;return}y.forEach((e,t)=>{let n=document.createElement(`option`);n.value=String(t),n.textContent=e.name,d.appendChild(n)}),d.disabled=!1,f.disabled=!1},te=e=>(Array.isArray(e)?e:e&&typeof e==`object`&&Array.isArray(e.tools)?e.tools:[]).map(e=>{let t=typeof e==`string`?e:e&&typeof e==`object`?e.path:void 0;if(!t||typeof t!=`string`)return null;let n=t.split(`/`).pop()??t,r=L(n);if(!r)return null;let i=t.split(`/`).map(e=>encodeURIComponent(e)).join(`/`).replace(/^\/+/,``);return{name:n,url:_t(this.options.assetBaseUrl,`tools/${i}`),type:r}}).filter(e=>!!e);f.addEventListener(`click`,()=>{let e=Number(d.value);if(!Number.isFinite(e))return;let t=y[e];t&&window.dispatchEvent(new CustomEvent(`c64-load-tool`,{detail:t}))}),(async()=>{try{let e=_t(this.options.assetBaseUrl,`tools/tools.json`),t=await fetch(e,{cache:`no-store`});if(!t.ok)throw Error(`HTTP ${t.status}`);y=te(await t.json()),ee(),p.textContent=y.length>0?`Found ${y.length} tool${y.length===1?``:`s`} in /public/tools`:`No compatible tools found in manifest`}catch(e){y=[],ee(),p.textContent=`Unable to load tools manifest: ${String(e?.message??e)}`}})().catch(()=>{});let b=r.querySelector(`#c64-cheevos-detector`),x=r.querySelector(`#c64-cheevos-json`),S=r.querySelector(`#c64-cheevos-json-file`),ne=r.querySelector(`#c64-cheevos-browse-json-btn`),C=r.querySelector(`#c64-cheevos-json-filename`),w=r.querySelector(`#c64-cheevos-status`),T=r.querySelector(`#c64-cheevos-tracker-visible`),E=r.querySelector(`#c64-cheevos-choose-rom-btn`),D=r.querySelector(`#c64-cheevos-rom-file`),O=``,k,A=window.localStorage.getItem(St)??``;b&&(b.value=A);let j=window.localStorage.getItem(wt)!==`0`;T&&(T.checked=j,window.dispatchEvent(new CustomEvent(`c64-cheevos-tracker-toggle`,{detail:{visible:j}})),T.addEventListener(`change`,()=>{let e=T.checked;window.localStorage.setItem(wt,e?`1`:`0`),window.dispatchEvent(new CustomEvent(`c64-cheevos-tracker-toggle`,{detail:{visible:e}}))})),ne?.addEventListener(`click`,()=>{S?.click()}),S?.addEventListener(`change`,async()=>{let e=S.files?.[0];if(!(!e||!x||!w))try{x.value=await e.text(),C&&(C.textContent=e.name),w.textContent=`Loaded JSON from ${e.name}`,this.promptForCheevosJsonUrl(e,b,w)}catch(e){w.textContent=`Unable to read JSON file: ${String(e?.message??e)}`}}),r.querySelector(`#c64-cheevos-enable-btn`)?.addEventListener(`click`,()=>{let e=b?.value.trim()??``,t=x?.value.trim()??``;if(!e){w&&(w.textContent=`Enter a detector ID first.`);return}window.localStorage.setItem(St,e),window.dispatchEvent(new CustomEvent(`c64-cheevos-enable`,{detail:{detectorId:e,jsonText:t}})),w&&(w.textContent=`Enabling ${e}...`)}),r.querySelector(`#c64-cheevos-disable-btn`)?.addEventListener(`click`,()=>{window.dispatchEvent(new CustomEvent(`c64-cheevos-disable`)),w&&(w.textContent=`Cheevos dev tracking is disabled.`)});let M=(e,t,n)=>{let r=n??L(e.name)??`crt`;window.dispatchEvent(new CustomEvent(`c64-cheevos-rom-file`,{detail:{file:e,type:r,romPath:t}})),w&&(w.textContent=`Loading ROM ${e.name} for ${t}`)};E?.addEventListener(`click`,async()=>{if(O){if(`showOpenFilePicker`in window)try{let e=await Ne(O,k);e&&M(e.file,e.romPath,e.type);return}catch(e){if(e?.name===`AbortError`)return;w&&(w.textContent=`Unable to remember ROM file: ${String(e?.message??e)}`);return}D?.click()}}),D?.addEventListener(`change`,async()=>{let e=D.files?.[0];if(!(!e||!O)){try{await Pe(O,e,k)}catch(e){w&&(w.textContent=`Unable to remember ROM file: ${String(e?.message??e)}`)}M(e,O,k)}}),r.querySelector(`#c64-cheevos-clear-popped-btn`)?.addEventListener(`click`,()=>{window.dispatchEvent(new CustomEvent(`c64-cheevos-clear-popped`,{detail:{detectorId:b?.value.trim()??``}})),w&&(w.textContent=`Local unlocks cleared.`)}),r.querySelector(`#c64-cheevos-clear-scores-btn`)?.addEventListener(`click`,()=>{window.dispatchEvent(new CustomEvent(`c64-cheevos-clear-scores`,{detail:{detectorId:b?.value.trim()??``}})),w&&(w.textContent=`Local scores cleared.`)}),window.addEventListener(`c64-cheevos-status`,e=>{if(!w)return;let t=e.detail;t?.status===`enabled`&&(w.textContent=`Tracking ${t.detectorId??`cheevos`} (${t.cheevosCount??0} achievements)`)}),window.addEventListener(`c64-cheevos-json-loaded`,e=>{let t=e.detail;!t?.jsonText||!x||(x.value=t.jsonText,C&&(C.textContent=t.source??`URL-loaded JSON`),w&&(w.textContent=`Loaded JSON from ${t.source??`URL`}`))}),window.addEventListener(`c64-cheevos-rom-needed`,e=>{let t=e.detail;O=t?.romPath?.trim()??``,k=I(t?.type)?t.type:void 0,E&&(E.disabled=!O),w&&O&&(w.textContent=`${t?.reason??`Choose local ROM file`}: ${O}`)}),window.addEventListener(`c64-cheevos-error`,e=>{w&&(w.textContent=`Cheevos error: ${e.detail?.error??`Unknown error`}`)}),r.querySelector(`#c64-add-cheat-btn`)?.addEventListener(`click`,()=>this.addCheat()),r.querySelector(`#c64-dump-ram-btn`)?.addEventListener(`click`,()=>this.dumpC64Ram()),this.renderCheats();let N=r.querySelector(`[data-settings-section="system"]`),re=N?.querySelector(`#c64-save-snapshot-btn`),ie=N?.querySelector(`#c64-detach-btn`),P=N?.querySelector(`#c64-reset-btn`),ae=N?.querySelector(`#c64-reboot-btn`),R=N?.querySelector(`#c64-disable-crt-preload-checks`),le=window.localStorage.getItem(xt)===`1`;this.player?.setCrtPreloadChecksDisabled(le),R&&(R.checked=le,R.addEventListener(`change`,()=>{let e=R.checked;window.localStorage.setItem(xt,e?`1`:`0`),this.player?.setCrtPreloadChecksDisabled(e)})),re&&re.addEventListener(`click`,()=>{if(!this.player||typeof this.player.getSnapshot!=`function`)return;let e=document.getElementById(`status`);try{this.downloadSnapshot(this.player.getSnapshot()),e&&(e.textContent=`Snapshot saved`)}catch(t){e&&(e.textContent=`Snapshot save failed: ${String(t?.message??t)}`)}}),ie&&ie.addEventListener(`click`,()=>{if(!this.player||!confirm(`Detach cartridge?`))return;this.player.detachCartridge();let e=document.getElementById(`status`);e&&(e.textContent=`Cartridge detached`)}),P&&P.addEventListener(`click`,()=>{if(!this.player||!confirm(`Perform hard reset? This will restart the emulator.`))return;this.player.hardReset();let e=document.getElementById(`status`);e&&(e.textContent=`Hard reset performed`)}),ae&&ae.addEventListener(`click`,async()=>{if(!this.player||!confirm(`Perform full reboot? This re-instantiates the emulator with no game loaded.`))return;let e=document.getElementById(`status`);e&&(e.textContent=`Rebooting emulator...`);try{await this.player.reboot(),e&&(e.textContent=`Emulator rebooted (no game loaded)`)}catch(t){e&&(e.textContent=`Reboot failed: ${String(t?.message??t)}`)}});let ue=r.querySelector(`#c64-audio-section-anchor`);this.createAudioSection(ue),new nt(r.querySelector(`#c64-ultimate-section-anchor`),()=>this.player).init();let de=r.querySelectorAll(`input[name="c64-joy-port"]`),fe=e=>{if(window.dispatchEvent(new CustomEvent(`c64-set-keyboard-joy-port`,{detail:{port:e}})),this.player&&typeof this.player.setKeyboardJoystickPort==`function`)try{this.player.setKeyboardJoystickPort(e)}catch{}};de.forEach(e=>{e.addEventListener(`change`,()=>{e.checked&&fe(Number(e.value))})});let pe={joystick:`Arrows + Ctrl = joystick only`,keyboard:`All keys &rarr; C64 keyboard matrix`,mixed:`Arrows + Z + Ctrl = joystick &amp; all other keys &rarr; C64 keyboard`},me=r.querySelectorAll(`input[name="c64-input-mode"]`),z=r.querySelector(`#c64-input-mode-hint`),B=e=>{if(z&&(z.innerHTML=pe[e]??``),window.dispatchEvent(new CustomEvent(`c64-set-input-mode`,{detail:{mode:e}})),this.player&&typeof this.player.setInputMode==`function`)try{this.player.setInputMode(e)}catch{}};me.forEach(e=>{e.addEventListener(`change`,()=>{e.checked&&B(e.value)})}),this.renderGamepadButtons(),r.querySelectorAll(`input[name="c64-display-mode"]`).forEach(e=>{e.addEventListener(`change`,()=>{e.checked&&ot(e.value)&&this.setDisplayMode(e.value)})});let he=r.querySelector(`#c64-fullscreen-toggle`);ut()?he.addEventListener(`click`,()=>{this.closeMenu(),this.toggleFullscreen()}):he.hidden=!0,window.addEventListener(`c64-close-dialog`,()=>{this.closeMenu()}),window.addEventListener(`c64-load-error`,()=>{this.settingsOverlay?.classList.remove(`visible`)})}createUnmuteButton(){let e=document.createElement(`button`);e.className=`c64-unmute-btn hidden`,e.innerHTML=`&#128263;`,e.title=`Click to enable audio`,e.addEventListener(`click`,async()=>{this.player&&(await this.player.audio.resume(),this.player.audio.suspended||e.classList.add(`hidden`))}),document.body.appendChild(e),window.addEventListener(`c64-audio-suspended`,()=>{e.classList.remove(`hidden`)}),window.addEventListener(`c64-audio-state`,(t=>{let n=t.detail;n.suspended||e.classList.add(`hidden`),this.syncAudioControls(n)}))}createAudioSection(e){let t=document.createElement(`div`);t.className=`c64-audio-section`,t.innerHTML=`
297
+ <label>Audio</label>
298
+ <div class="c64-audio-row">
299
+ <button class="c64-mute-btn" id="c64-mute-btn" title="Toggle mute">&#128264;</button>
300
+ <input type="range" class="c64-volume-slider" id="c64-volume-slider" min="0" max="100" value="75" />
301
+ <span class="c64-volume-label" id="c64-volume-label">75%</span>
302
+ </div>
303
+ `,e.appendChild(t);let n=t.querySelector(`#c64-mute-btn`),r=t.querySelector(`#c64-volume-slider`),i=t.querySelector(`#c64-volume-label`);n.addEventListener(`click`,()=>{this.player&&(this.player.audio.toggleMute(),this.player.audio.suspended&&this.player.audio.resume())}),r.addEventListener(`input`,()=>{if(!this.player)return;let e=Number(r.value)/100;this.player.audio.setVolume(e),i.textContent=`${r.value}%`,this.player.audio.suspended&&this.player.audio.resume()})}syncAudioControls(e){let t=document.getElementById(`c64-mute-btn`),n=document.getElementById(`c64-volume-slider`),r=document.getElementById(`c64-volume-label`);t&&(t.innerHTML=e.muted?`&#128263;`:`&#128264;`,t.classList.toggle(`muted`,e.muted)),n&&(n.value=String(Math.round(e.volume*100))),r&&(r.textContent=`${Math.round(e.volume*100)}%`)}toggleMenu(){this.settingsOverlay?.classList.toggle(`visible`)}closeMenu(){this.settingsOverlay?.classList.remove(`visible`)}open(){this.helpOverlay?.classList.add(`visible`)}close(){this.helpOverlay?.classList.remove(`visible`),this.keymapOverlay?.classList.remove(`visible`)}},Wt=`c64-cheevos-dev`,Gt=class{player;enabled=!1;detectorId=``;cheevosSet={cheevos:[]};instance=null;rafId=0;lastSnapshotKey=``;constructor(e){this.player=e}getState(){return{enabled:this.enabled,detectorId:this.detectorId,cheevosSet:this.cheevosSet}}async enable(e,t={cheevos:[]}){let n=e.trim().toLowerCase();if(!n)throw Error(`Cheevos detector ID is required`);this.disable(),this.detectorId=n,this.cheevosSet=qt(t,n);let{createCheevos:r}=await W(async()=>{let{createCheevos:e}=await import(`./src-CNh6UV6R.js`);return{createCheevos:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])),i=this.getPoppedCheevos(n),a=await r(n,{gameId:n,user:{id:`dev-user`,username:`Developer`},cheevosSet:this.cheevosSet,poppedCheevos:i,postScore:this.postScore,popCheevo:this.popCheevo});a.cpuReadNS=e=>this.player?.cpuReadNS(e)??0,a.cpuRead=e=>this.player?.cpuRead(e)??0,a.ramRead=e=>this.player?.ramRead(e)??0,this.attachWatcher(a),this.instance=a,this.enabled=!0,this.dispatchStatus(`enabled`,{cheevosCount:this.cheevosSet.cheevos?.length??0,cheevosSet:this.cheevosSet,poppedCheevos:i}),this.tick()}async enableFromJson(e,t){await this.enable(e,Kt(t))}disable(){this.rafId&&=(cancelAnimationFrame(this.rafId),0),this.enabled=!1,this.instance=null,this.lastSnapshotKey=``}destroy(){this.disable(),this.player=null}clearPopped(e=this.detectorId){let t=e.trim().toLowerCase();t&&(localStorage.removeItem(Zt(t)),this.dispatchStatus(`popped-cleared`,{poppedCheevos:[]}))}clearScores(e=this.detectorId){let t=e.trim().toLowerCase();t&&(localStorage.removeItem(Xt(t)),this.dispatchStatus(`scores-cleared`))}tick=()=>{if(this.enabled){try{this.instance?.execute?.(),this.dispatchSnapshot()}catch(e){this.disable(),window.dispatchEvent(new CustomEvent(`c64-cheevos-error`,{detail:{detectorId:this.detectorId,error:Qt(e)}}));return}this.rafId=requestAnimationFrame(this.tick)}};postScore=async(e,t,n,r,i)=>{let a={gameId:e,score:t,userId:n,username:r,variant:i,at:new Date().toISOString()},o=Yt(Xt(this.detectorId),[]);return o.push(a),localStorage.setItem(Xt(this.detectorId),JSON.stringify(o)),window.dispatchEvent(new CustomEvent(`c64-cheevos-score`,{detail:{detectorId:this.detectorId,score:a}})),{ok:!0}};popCheevo=async(e,t,n)=>{let r=this.findAchievement(n)??{_id:n,title:n,description:`Unlocked in c64-ready dev mode`},i=this.getPoppedCheevos(this.detectorId);return i.some(e=>e.achievement._id===n)||(i.push({achievement:r}),localStorage.setItem(Zt(this.detectorId),JSON.stringify(i))),window.dispatchEvent(new CustomEvent(`c64-cheevos-popped`,{detail:{detectorId:this.detectorId,achievement:r,poppedCheevos:i}})),{achievement:r}};dispatchSnapshot(){let e=this.instance;if(!e)return;let t=Object.fromEntries((this.cheevosSet.trackerFields??[]).map(t=>{let n=t.field??t.key;return[t.key,$t(e[n])]})),n={detectorId:this.detectorId,score:$t(e.score),lives:$t(e.lives),isGameOver:typeof e.isGameOver==`boolean`?e.isGameOver:void 0,fields:t},r=JSON.stringify(n);r!==this.lastSnapshotKey&&(this.lastSnapshotKey=r,window.dispatchEvent(new CustomEvent(`c64-cheevos-snapshot`,{detail:n})))}attachWatcher(e){let t=e.watcher;if(typeof t?.on==`function`)for(let e of[`cheevo`,`gameOver`,`livesChange`,`newGame`])t.on(e,t=>{let n={detectorId:this.detectorId,type:e,payload:t};window.dispatchEvent(new CustomEvent(`c64-cheevos-event`,{detail:n}))})}findAchievement(e){return this.cheevosSet.cheevos?.find(t=>t._id===e)}getPoppedCheevos(e){return Yt(Zt(e),[])}dispatchStatus(e,t={}){window.dispatchEvent(new CustomEvent(`c64-cheevos-status`,{detail:{detectorId:this.detectorId,status:e,...t}}))}};function Kt(e){let t=JSON.parse(e);if(!t||typeof t!=`object`)throw Error(`Cheevos JSON must be an object`);return qt(t)}function qt(e,t=`dev`){let n=Array.isArray(e.cheevos)?e.cheevos:[],r=Array.isArray(e.trackerFields)?e.trackerFields:[],i=Jt(e.romPath??e.rom?.path),a=Jt(e.rom?.type);return{_id:e._id??`${t}-dev-set`,...i?{romPath:i}:{},...i||a?{rom:{...i?{path:i}:{},...a?{type:a}:{}}}:{},trackerFields:r.map((e,t)=>({key:String(e.key??e.field??`field-${t+1}`),label:e.label?String(e.label):void 0,source:`field`,field:e.field?String(e.field):void 0,display:e.display===`bar`?`bar`:`text`,max:typeof e.max==`number`&&Number.isFinite(e.max)?e.max:void 0})),cheevos:n.map((e,t)=>({_id:String(e._id??`dev-${t+1}`),title:String(e.title??e._id??`Achievement ${t+1}`),description:e.description?String(e.description):``}))}}function Jt(e){if(typeof e==`string`)return e.trim()||void 0}function Yt(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function Xt(e){return`${Wt}:${e}:scores`}function Zt(e){return`${Wt}:${e}:popped`}function Qt(e){return e instanceof Error?e.message:String(e)}function $t(e){if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e}const en=`c64-cheevos-tracker-visible`;var tn=6,nn=`
304
+ .c64-cheevos-tracker{position:fixed;inset-block-start:50%;inset-inline-start:calc(50% + 410px);transform:translateY(-50%);box-sizing:border-box;inline-size:min(520px,calc(50vw - 430px));max-block-size:calc(100dvh - 48px);overflow:auto;scrollbar-gutter:stable;background:#101623;border:2px solid #333e5f;border-radius:8px;color:#d8def6;font-family:monospace;font-size:13px;padding:14px;z-index:900;box-shadow:0 12px 36px rgba(0,0,0,.35)}.c64-cheevos-tracker.hidden{display:none}.c64-cheevos-tracker h2{margin:0 0 4px;color:#8da2ff;font-size:15px;letter-spacing:.08em;text-transform:uppercase}.c64-cheevos-tracker-subtitle{color:#8790aa;font-size:12px;margin:0 0 10px}.c64-cheevos-tracker-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin:0 0 10px}.c64-cheevos-stat{background:#151d2e;border:1px solid #26314c;border-radius:5px;padding:7px}.c64-cheevos-stat-label{display:block;color:#8995b5;font-size:11px;text-transform:uppercase}.c64-cheevos-stat-value{display:block;color:#fff;font-size:16px;margin-block-start:2px;overflow:hidden;text-overflow:ellipsis}.c64-cheevos-field-list{display:grid;gap:7px;margin:0 0 10px}.c64-cheevos-field{background:#151d2e;border:1px solid #26314c;border-radius:5px;padding:7px}.c64-cheevos-field-row{display:flex;justify-content:space-between;gap:8px}.c64-cheevos-bar{block-size:7px;background:#26314c;border-radius:999px;margin-block-start:6px;overflow:hidden}.c64-cheevos-bar-fill{block-size:100%;background:#8da2ff;border-radius:inherit}.c64-cheevos-list-header{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:10px 0 6px}.c64-cheevos-list-title{margin:0;color:#8da2ff;font-size:12px;text-transform:uppercase}.c64-cheevos-list-toggle{background:transparent;border:1px solid #38486f;border-radius:4px;color:#b8c4ff;cursor:pointer;font:inherit;font-size:11px;padding:2px 6px}.c64-cheevos-list-toggle:hover{border-color:#8da2ff;color:#fff}.c64-cheevos-list{display:grid;gap:6px;margin:0;padding:0;list-style:none}.c64-cheevos-list.cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.c64-cheevos-list.cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.c64-cheevos-item{background:#151d2e;border:1px solid #26314c;border-radius:5px;padding:6px;min-inline-size:0}.c64-cheevos-item.popped{border-color:#557a36;background:#152416}.c64-cheevos-item-title{display:block;color:#f1f4ff;overflow:hidden;text-overflow:ellipsis}.c64-cheevos-item-description{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;line-clamp:2;overflow:clip;color:#8790aa;font-size:11px;margin-block-start:2px}.c64-cheevos-empty{color:#8790aa;font-size:12px;margin:0}.c64-cheevos-message{color:#f3c36b;font-size:12px;margin:10px 0 0}@media (max-width:1480px){.c64-cheevos-tracker{inline-size:min(360px,calc(50vw - 430px))}.c64-cheevos-list.cols-3{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (max-width:1180px){.c64-cheevos-tracker{display:none}}
305
+ `,rn=class{root=null;state={detectorId:``,enabled:!1,visiblePreference:localStorage.getItem(en)!==`0`,displayMode:`standard`,cheevosSet:{cheevos:[],trackerFields:[]},popped:[],fields:{},lastMessage:``,expandedLists:{}};init(){this.injectCSS(),this.root=document.createElement(`aside`),this.root.className=`c64-cheevos-tracker hidden`,this.root.setAttribute(`aria-label`,`Cheevos tracker`),document.body.appendChild(this.root),this.render(),window.addEventListener(`c64-cheevos-status`,this.handleStatus),window.addEventListener(`c64-cheevos-event`,this.handleCheevosEvent),window.addEventListener(`c64-cheevos-score`,this.handleScore),window.addEventListener(`c64-cheevos-popped`,this.handlePopped),window.addEventListener(`c64-cheevos-snapshot`,this.handleSnapshot),window.addEventListener(`c64-cheevos-error`,this.handleError),window.addEventListener(`c64-cheevos-tracker-toggle`,this.handleToggle),window.addEventListener(`c64-display-mode-changed`,this.handleDisplayMode),this.root.addEventListener(`click`,this.handleClick)}destroy(){window.removeEventListener(`c64-cheevos-status`,this.handleStatus),window.removeEventListener(`c64-cheevos-event`,this.handleCheevosEvent),window.removeEventListener(`c64-cheevos-score`,this.handleScore),window.removeEventListener(`c64-cheevos-popped`,this.handlePopped),window.removeEventListener(`c64-cheevos-snapshot`,this.handleSnapshot),window.removeEventListener(`c64-cheevos-error`,this.handleError),window.removeEventListener(`c64-cheevos-tracker-toggle`,this.handleToggle),window.removeEventListener(`c64-display-mode-changed`,this.handleDisplayMode),this.root?.removeEventListener(`click`,this.handleClick),this.root?.remove(),this.root=null}handleStatus=e=>{let t=e.detail;if(t.status===`enabled`){this.state.enabled=!0,this.state.detectorId=t.detectorId??``,this.state.cheevosSet=t.cheevosSet??{cheevos:[],trackerFields:[]},this.state.popped=cn(t.poppedCheevos??[]),this.state.isGameOver=void 0,this.state.lastMessage=``,this.state.expandedLists={},this.render();return}t.status===`popped-cleared`&&(this.state.popped=[],this.render())};handleCheevosEvent=e=>{let t=e.detail;t.type===`newGame`?(this.state.isGameOver=!1,this.state.lastMessage=`New game started`):t.type===`gameOver`?(this.state.isGameOver=!0,this.state.score=ln(t.payload?.score)??this.state.score,this.state.lastMessage=`Game over`):t.type===`livesChange`?this.state.lives=ln(t.payload?.lives)??this.state.lives:t.type===`cheevo`&&(this.state.lastMessage=String(t.payload?.title??`Achievement unlocked`)),this.render()};handleScore=e=>{let t=e.detail;this.state.score=t.score?.score??this.state.score,this.render()};handlePopped=e=>{let t=e.detail;t.poppedCheevos?this.state.popped=cn(t.poppedCheevos):t.achievement&&!this.state.popped.some(e=>e._id===t.achievement?._id)&&(this.state.popped=[...this.state.popped,t.achievement]),t.achievement&&(this.state.lastMessage=`Popped: ${t.achievement.title}`),this.render()};handleSnapshot=e=>{let t=e.detail;t.score!==void 0&&(this.state.score=t.score),t.lives!==void 0&&(this.state.lives=t.lives),t.isGameOver!==void 0&&(this.state.isGameOver=t.isGameOver),t.fields&&(this.state.fields=t.fields),this.render()};handleError=e=>{let t=e.detail;this.state.lastMessage=`Error: ${t.error??`Unknown error`}`,this.render()};handleToggle=e=>{let t=e.detail;this.state.visiblePreference=t.visible!==!1,localStorage.setItem(en,this.state.visiblePreference?`1`:`0`),this.render()};handleDisplayMode=e=>{let t=e.detail;this.state.displayMode=t.mode??`standard`,this.render()};handleClick=e=>{let t=e.target;if(!(t instanceof HTMLElement))return;let n=t.closest(`[data-cheevos-list-toggle]`);if(!n)return;let r=n.dataset.cheevosListToggle;r&&(this.state.expandedLists={...this.state.expandedLists,[r]:!this.state.expandedLists[r]},this.render())};render(){if(!this.root)return;this.root.classList.toggle(`hidden`,!this.state.enabled||!this.state.visiblePreference||this.state.displayMode!==`standard`);let e=this.state.cheevosSet.cheevos??[],t=new Set(this.state.popped.map(e=>e._id)),n=e.filter(e=>!t.has(e._id));this.root.innerHTML=`
306
+ <h2>Cheevos</h2>
307
+ <p class="c64-cheevos-tracker-subtitle">${K(this.state.detectorId||`No detector`)}</p>
308
+ <div class="c64-cheevos-tracker-grid">
309
+ ${G(`Score`,this.state.score??`-`)}
310
+ ${G(`Lives`,this.state.lives??`-`)}
311
+ ${G(`Status`,this.state.isGameOver?`Game Over`:this.state.isGameOver===!1?`Playing`:`Waiting`)}
312
+ ${G(`Popped`,`${this.state.popped.length}/${e.length}`)}
313
+ </div>
314
+ ${this.renderFields()}
315
+ ${on(`popped`,`Popped`,this.state.popped,!0,!!this.state.expandedLists.popped)}
316
+ ${on(`remaining`,`Remaining`,n,!1,!!this.state.expandedLists.remaining)}
317
+ ${this.state.lastMessage?`<p class="c64-cheevos-message">${K(this.state.lastMessage)}</p>`:``}
318
+ `}renderFields(){let e=this.state.cheevosSet.trackerFields??[];return e.length===0?``:`<div class="c64-cheevos-field-list">${e.map(e=>an(e,this.state.fields[e.key])).join(``)}</div>`}injectCSS(){if(document.querySelector(`style[data-c64-cheevos-tracker]`))return;let e=document.createElement(`style`);e.setAttribute(`data-c64-cheevos-tracker`,``),e.textContent=nn,document.head.appendChild(e)}};function G(e,t){return`<div class="c64-cheevos-stat"><span class="c64-cheevos-stat-label">${K(e)}</span><span class="c64-cheevos-stat-value">${K(String(t))}</span></div>`}function an(e,t){let n=e.label??e.key,r=t??`-`,i=e.display===`bar`&&typeof t==`number`&&typeof e.max==`number`&&e.max>0?`<div class="c64-cheevos-bar"><div class="c64-cheevos-bar-fill" style="inline-size:${Math.max(0,Math.min(100,t/e.max*100))}%"></div></div>`:``;return`<div class="c64-cheevos-field"><div class="c64-cheevos-field-row"><span>${K(n)}</span><strong>${K(String(r))}</strong></div>${i}</div>`}function on(e,t,n,r,i){let a=n.length>tn,o=i?n:n.slice(0,tn),s=sn(o.length),c=o.map(e=>`<li class="c64-cheevos-item${r?` popped`:``}"><span class="c64-cheevos-item-title">${K(e.title)}</span>${e.description?`<span class="c64-cheevos-item-description" title="${e.description}">${K(e.description)}</span>`:``}</li>`).join(``),l=a?`<button class="c64-cheevos-list-toggle" type="button" data-cheevos-list-toggle="${K(e)}">${i?`Show less`:`Show all ${n.length}`}</button>`:``;return`<div class="c64-cheevos-list-header"><h3 class="c64-cheevos-list-title">${K(t)}</h3>${l}</div>${c?`<ul class="c64-cheevos-list ${s}">${c}</ul>`:`<p class="c64-cheevos-empty">None</p>`}`}function sn(e){return e>=9?`cols-3`:e>=4?`cols-2`:`cols-1`}function cn(e){return e.map(e=>e.achievement).filter(Boolean)}function ln(e){if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e}function K(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}var q=document.getElementById(`status`),J=new De(`c64-screen`),Y=`/c64-ready/`,X=new URLSearchParams(window.location.search),un=Le(X.get(`game`),Y,{disableDefault:Be(X)}),dn=L(un||``)??`crt`,Z=new ge({wasmUrl:`${Y}c64.wasm`,gameUrl:un,gameType:dn,renderer:J,audio:{assetBaseUrl:Y},onProgress:(e,t)=>J.setProgress(e,t)}),Q=new Gt(Z);new rn().init(),new Ut({assetBaseUrl:Y,appVersion:`3.2.0`,gitHash:`d80ffb0`}).init(Z),Z.start().then(async()=>{un||(q.textContent=`Autoload disabled (?game=null)`,q.style.color=`#9ecbff`),J.hideLoader(),await mn()}).catch(e=>{console.error(e),J.setError(`ERROR`),q.textContent=`Error: ${$(String(e))}`,q.style.color=`#f44`});var fn=()=>{let e=document.hidden,t=document.querySelector(`link[rel~='icon']`),n=`${Y}${e?`led-off.svg`:`led-on.svg`}`.replace(/\/+/g,`/`);t&&(t.href=n)};document.addEventListener(`visibilitychange`,fn),window.addEventListener(`focus`,fn),window.addEventListener(`blur`,fn),fn(),window.addEventListener(`c64-load-file`,async e=>{let t=e.detail,n=t.file,r=t.type,i=r===`auto`?void 0:r;if(n)try{J.showLoader(),await Z.loadFile(n,I(i)?i:void 0),J.hideLoader()}catch(e){console.error(e),J.setError(`LOAD ERROR`),q.textContent=`Load error: ${$(String(e))}`,q.style.color=`#f44`}}),window.addEventListener(`c64-controller-connected`,e=>{let t=e.detail;q.textContent=`Controller Connected: ${t.index} - ${t.name}`,q.style.color=`#9ecbff`}),window.addEventListener(`c64-controller-disconnected`,e=>{let t=e.detail;q.textContent=`Controller Disconnected : ${t.index} - ${t.name}`,q.style.color=`#9ecbff`}),window.addEventListener(`c64-load-tool`,async e=>{let t=e.detail;if(!t?.url)return;let n=I(t.type)?t.type:void 0;try{q.textContent=`Loading tool: ${t.name??t.url}`,q.style.color=`#9ecbff`,J.showLoader(),await Z.loadTool(t.url,n),J.hideLoader()}catch(e){console.error(e),J.setError(`LOAD ERROR`),q.textContent=`Tool load error: ${$(String(e))}`,q.style.color=`#f44`}}),window.addEventListener(`c64-cheevos-enable`,async e=>{let t=e.detail,n=t?.detectorId?.trim()??``;if(n)try{if(t?.jsonText?.trim()){let e=Kt(t.jsonText);await Q.enable(n,e),await hn(e)}else await Q.enable(n)}catch(e){let t=$(String(e?.message??e));window.dispatchEvent(new CustomEvent(`c64-cheevos-error`,{detail:{detectorId:n,error:t}}))}}),window.addEventListener(`c64-cheevos-rom-file`,async e=>{let t=e.detail,n=t?.file;if(!n)return;let r=I(t?.type)?t.type:void 0;try{q.textContent=`Loading cheevos ROM: ${t?.romPath??n.name}`,q.style.color=`#9ecbff`,J.showLoader(),await Z.loadFile(n,r),J.hideLoader()}catch(e){console.error(e),J.setError(`LOAD ERROR`),q.textContent=`Cheevos ROM load error: ${$(String(e))}`,q.style.color=`#f44`}}),window.addEventListener(`c64-cheevos-disable`,()=>{Q.disable(),q.textContent=`Cheevos dev tracking disabled`,q.style.color=`#9ecbff`}),window.addEventListener(`c64-cheevos-clear-popped`,e=>{let t=e.detail;Q.clearPopped(t?.detectorId)}),window.addEventListener(`c64-cheevos-clear-scores`,e=>{let t=e.detail;Q.clearScores(t?.detectorId)}),window.addEventListener(`c64-load-error`,e=>{let t=e.detail,n=$(t?.error??`Unknown load error`);console.error(`C64 load error event:`,t),pn=!1,J.setError(`LOAD ERROR`),q.textContent=`Load error: ${n}`,q.style.color=`#f44`});var pn=!1;window.addEventListener(`c64-load-success`,e=>{let t=e.detail;if(pn){pn=!1;return}q.textContent=`Loaded: ${t?.name??`game`}`,q.style.color=`#9ecbff`}),window.addEventListener(`c64-detach`,()=>{q.textContent=`Cartridge detached (no game loaded)`,q.style.color=`#9ecbff`}),window.addEventListener(`c64-load-info`,e=>{let t=e.detail;t?.message&&(pn=t.mode===`warning`,q.textContent=t.message,q.style.color=t.mode===`warning`?`#f9c74f`:`#9ecbff`,console.info(`C64 load info event:`,t))}),window.addEventListener(`c64-cheevos-status`,e=>{let t=e.detail;t?.status===`enabled`&&(q.textContent=`Cheevos tracking enabled: ${t.detectorId??`unknown`} (${t.cheevosCount??0} achievements)`,q.style.color=`#9ecbff`)}),window.addEventListener(`c64-cheevos-error`,e=>{let t=e.detail;q.textContent=`Cheevos error${t?.detectorId?` (${t.detectorId})`:``}: ${t?.error??`Unknown error`}`,q.style.color=`#f44`}),window.addEventListener(`c64-cheevos-score`,e=>{let t=e.detail;q.textContent=`Cheevos score captured${t?.detectorId?` for ${t.detectorId}`:``}: ${t?.score?.score??0}`,q.style.color=`#9ecbff`}),window.addEventListener(`c64-cheevos-event`,e=>{let t=e.detail;if(t?.type){if(t.type===`cheevo`)q.textContent=`${t.payload?.title??`Achievement`}: ${t.payload?.message??`Unlocked`}`;else if(t.type===`gameOver`)q.textContent=`Game over${t.detectorId?` (${t.detectorId})`:``}: ${t.payload?.score??0}`;else return;q.style.color=`#9ecbff`}}),window.addEventListener(`c64-reboot`,()=>{q.textContent=`Emulator rebooted. Load a cartridge to continue.`,q.style.color=`#9ecbff`,J.hideLoader(0)});function $(e){let t=String(e??``).trim();for(;/^(uncaught\s+)?error\s*:\s*/i.test(t);)t=t.replace(/^(uncaught\s+)?error\s*:\s*/i,``).trim();return t||`Unknown load error`}async function mn(){let e=X.get(`cheevos`)?.trim();if(!e)return;let t=Re(X.get(`cheevosSet`),Y);try{if(t){let n=await fetch(t,{cache:`no-store`});if(!n.ok)throw Error(`Failed to fetch cheevos set: ${n.status}`);let r=await n.text();window.dispatchEvent(new CustomEvent(`c64-cheevos-json-loaded`,{detail:{jsonText:r,source:t}}));let i=Kt(r);await Q.enable(e,i),await hn(i);return}await Q.enable(e)}catch(t){let n=$(String(t?.message??t));window.dispatchEvent(new CustomEvent(`c64-cheevos-error`,{detail:{detectorId:e,error:n}}))}}async function hn(e){let t=Ae(e);if(!t)return;let n=je(e);try{let e=await Me(t,n);if(!e){gn(t,n,`Choose local ROM file`);return}q.textContent=`Loading cheevos ROM: ${t}`,q.style.color=`#9ecbff`,J.showLoader(),await Z.loadFile(e.file,e.type),J.hideLoader()}catch(e){gn(t,n,`Unable to auto-load ROM (${$(String(e?.message??e))})`)}}function gn(e,t,n){window.dispatchEvent(new CustomEvent(`c64-cheevos-rom-needed`,{detail:{romPath:e,type:t,reason:n}})),q.textContent=`${n}: ${e}`,q.style.color=`#f9c74f`}export{W as t};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BeachHead-BLcSLEEh.js","assets/src-DX0rJQsE.js","assets/string-utils-CMVABfx0.js","assets/ChuckieEgg-Bv2nxhYv.js","assets/ForbiddenForest-CWEFgjVq.js","assets/Galaga-DknmKlo5.js","assets/Gribbly-nFVwULpF.js","assets/Hercules-Dbx_KaEi.js","assets/LegendOfWilf-BBW1Y7LQ.js","assets/MariosCementFactory-DtpgUfFO.js","assets/MoleAttack-D_2aAX2V.js","assets/MunchyWorm-BqWD5x4j.js","assets/ParkPatrol-9pwc_jcb.js","assets/PottyPigeon-CZnjIrGr.js","assets/RainbowIslands-CgoxK_qP.js","assets/Stix-o2hS_Ekr.js","assets/Tilt-BKb_k_R2.js","assets/UpNDown-BQXEmKfk.js","assets/Uridium-9u86vh1V.js","assets/VegetablesDeluxe-DbmngV50.js","assets/ActionBiker-CWiKt9dn.js","assets/Thrust-rDKv3Thu.js","assets/RoadRunner-DR_cGZ-h.js","assets/Panther-D558qV3B.js","assets/RocnRope-DrUGJ0pW.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./index-C84W-vN0.js";import{t}from"./src-DX0rJQsE.js";import"./string-utils-CMVABfx0.js";import"./ActionBiker-CWiKt9dn.js";import"./BeachHead-BLcSLEEh.js";import"./ChuckieEgg-Bv2nxhYv.js";import"./ForbiddenForest-CWEFgjVq.js";import"./Galaga-DknmKlo5.js";import"./Gribbly-nFVwULpF.js";import"./Hercules-Dbx_KaEi.js";import"./LegendOfWilf-BBW1Y7LQ.js";import"./MariosCementFactory-DtpgUfFO.js";import"./MoleAttack-D_2aAX2V.js";import"./MunchyWorm-BqWD5x4j.js";import"./Panther-D558qV3B.js";import"./ParkPatrol-9pwc_jcb.js";import"./PottyPigeon-CZnjIrGr.js";import"./RainbowIslands-CgoxK_qP.js";import"./RoadRunner-DR_cGZ-h.js";import"./RocnRope-DrUGJ0pW.js";import"./Stix-o2hS_Ekr.js";import"./Thrust-rDKv3Thu.js";import"./Tilt-BKb_k_R2.js";import"./UpNDown-BQXEmKfk.js";import"./Uridium-9u86vh1V.js";import"./VegetablesDeluxe-DbmngV50.js";var n=19245,r=19235,i=class{constructor({gameId:e,user:n,cheevosSet:r={cheevos:[]},poppedCheevos:i=[],popCheevo:a=async()=>{},postScore:o=async()=>({})}){console.log(`GenericTemplate::constructor`,e),this._popCheevo=a,this.name=`Generic Game`,this.postScore=o,this.user=n,this.gameId=e,this.watcher=t(),this.cheevosSet=r,this.cheevosMap=r.cheevos.map((e,t)=>{let n=i.some(t=>t.achievement._id===e._id);return{title:e.title,message:e.description,isPopped:n,check:()=>{},cheevoId:e._id}}),this.resetGameVars()}resetGameVars(){this.score=0,this.lives=0,this.isGameOver=!0}newGameVars(){this.isGameOver=!1,this.score=this.getScore(),this.lives=this.getLives(),console.log(`Start New Game`,this.score,this.lives)}getScore(){}getIsDead(){return parseInt(this.cpuReadNS(r),10)===0}getLives(){return parseInt(this.cpuReadNS(n).toString(16),10)}newGameCheck(){}execute(){let e=this.getScore();e!==this.score&&(this.score=e,console.log(`Template.score=`,this.score)),this.newGameCheck()&&this.newGameVars();let t=this.getLives();t!==this.lives&&(this.lives=t,console.log(`Template.lives=`,this.lives)),t===0&&this.getIsDead()&&!this.isGameOver&&(this.isGameOver=!0,this.watcher.dispatch(`gameOver`,{score:this.score}),this.postScore(this.gameId,this.score,this.user.id,this.user.username).then(e=>{console.log(`Score posted successfully`,e),this.watcher.dispatch(`cheevo`,{title:`Score Submit Success`,message:`Your score of ${this.score} has been submitted to the ${this.name} Leaderboard!`})})),this.cheevosMap.forEach(e=>{!e.isPopped&&e.check()&&(e.isPopped=!0,console.log(`Pop Cheevo::`,e.title,e.message),this.popCheevo(e.cheevoId))})}async popCheevo(e){let t=await this._popCheevo(this.cheevosSet._id,this.user.id,e);console.log(`res popCheevo`,t),this.watcher.dispatch(`cheevo`,{title:t.achievement.title,message:t.achievement.description,thumbnailUrl:t.thumbnailUrl})}};const a={"beach-head":()=>e(()=>import(`./BeachHead-BLcSLEEh.js`),__vite__mapDeps([0,1,2])),"chuckie-egg":()=>e(()=>import(`./ChuckieEgg-Bv2nxhYv.js`),__vite__mapDeps([3,1,2])),"forbidden-forest":()=>e(()=>import(`./ForbiddenForest-CWEFgjVq.js`),__vite__mapDeps([4,1,2])),galaga:()=>e(()=>import(`./Galaga-DknmKlo5.js`),__vite__mapDeps([5,1,2])),gribbly:()=>e(()=>import(`./Gribbly-nFVwULpF.js`),__vite__mapDeps([6,1,2])),hercules:()=>e(()=>import(`./Hercules-Dbx_KaEi.js`),__vite__mapDeps([7,1,2])),"legend-of-wilf":()=>e(()=>import(`./LegendOfWilf-BBW1Y7LQ.js`),__vite__mapDeps([8,1])),"mario-cf":()=>e(()=>import(`./MariosCementFactory-DtpgUfFO.js`),__vite__mapDeps([9,1,2])),"mole-attack":()=>e(()=>import(`./MoleAttack-D_2aAX2V.js`),__vite__mapDeps([10,1,2])),"munchy-worm":()=>e(()=>import(`./MunchyWorm-BqWD5x4j.js`),__vite__mapDeps([11,1,2])),"park-patrol":()=>e(()=>import(`./ParkPatrol-9pwc_jcb.js`),__vite__mapDeps([12,1,2])),"potty-pigeon":()=>e(()=>import(`./PottyPigeon-CZnjIrGr.js`),__vite__mapDeps([13,1,2])),"rainbow-islands":()=>e(()=>import(`./RainbowIslands-CgoxK_qP.js`),__vite__mapDeps([14,1,2])),stix:()=>e(()=>import(`./Stix-o2hS_Ekr.js`),__vite__mapDeps([15,1,2])),tilt:()=>e(()=>import(`./Tilt-BKb_k_R2.js`),__vite__mapDeps([16,1,2])),"up-n-down":()=>e(()=>import(`./UpNDown-BQXEmKfk.js`),__vite__mapDeps([17,1,2])),uridium:()=>e(()=>import(`./Uridium-9u86vh1V.js`),__vite__mapDeps([18,1,2])),"vegetables-deluxe":()=>e(()=>import(`./VegetablesDeluxe-DbmngV50.js`),__vite__mapDeps([19,1,2])),"action-biker":()=>e(()=>import(`./ActionBiker-CWiKt9dn.js`),__vite__mapDeps([20,1,2])),thrust:()=>e(()=>import(`./Thrust-rDKv3Thu.js`),__vite__mapDeps([21,1,2])),"road-runner":()=>e(()=>import(`./RoadRunner-DR_cGZ-h.js`),__vite__mapDeps([22,1,2])),panther:()=>e(()=>import(`./Panther-D558qV3B.js`),__vite__mapDeps([23,1,2])),"roc-n-rope":()=>e(()=>import(`./RocnRope-DrUGJ0pW.js`),__vite__mapDeps([24,1]))};var o=e=>String(e??``).trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);async function s(e,t={}){let n=a[o(e)];if(!n)return new i(t);let{default:r}=await n();return new r(t)}export{s as createCheevos};