c64-ready 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) 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/player-server.mjs +197 -0
  35. package/src/main.ts +5 -1
  36. package/src/player/canvas-renderer.ts +1 -1
  37. package/src/player/display-layout.ts +109 -0
  38. package/src/player/ui-controller.ts +226 -93
  39. package/dist/assets/RainbowIslands-BjfmJB8z.js +0 -1
  40. package/dist/assets/index-B8DSjPqI.js +0 -243
  41. package/dist/assets/src-_trgwTvp.js +0 -2
  42. /package/dist/assets/{BeachHead-CuSwFD4k.js → BeachHead-BLcSLEEh.js} +0 -0
  43. /package/dist/assets/{ChuckieEgg-CPqBnAOF.js → ChuckieEgg-Bv2nxhYv.js} +0 -0
  44. /package/dist/assets/{ForbiddenForest-DsQ9jsc8.js → ForbiddenForest-CWEFgjVq.js} +0 -0
  45. /package/dist/assets/{Galaga-Cutc3p9s.js → Galaga-DknmKlo5.js} +0 -0
  46. /package/dist/assets/{Gribbly-DdZ_hHFt.js → Gribbly-nFVwULpF.js} +0 -0
  47. /package/dist/assets/{Hercules-vZYKm7GG.js → Hercules-Dbx_KaEi.js} +0 -0
  48. /package/dist/assets/{LegendOfWilf-CxSMOjsj.js → LegendOfWilf-BBW1Y7LQ.js} +0 -0
  49. /package/dist/assets/{MariosCementFactory-z0IZ0q30.js → MariosCementFactory-DtpgUfFO.js} +0 -0
  50. /package/dist/assets/{MoleAttack-buC6ChYy.js → MoleAttack-D_2aAX2V.js} +0 -0
  51. /package/dist/assets/{MunchyWorm-D2Zv7i0Q.js → MunchyWorm-BqWD5x4j.js} +0 -0
  52. /package/dist/assets/{ParkPatrol-CVj7hyoB.js → ParkPatrol-9pwc_jcb.js} +0 -0
  53. /package/dist/assets/{PottyPigeon-0SYpIUBa.js → PottyPigeon-CZnjIrGr.js} +0 -0
  54. /package/dist/assets/{Stix-BU-qUCeC.js → Stix-o2hS_Ekr.js} +0 -0
  55. /package/dist/assets/{Tilt-C5KtKisF.js → Tilt-BKb_k_R2.js} +0 -0
  56. /package/dist/assets/{UpNDown-CATRO7Mz.js → UpNDown-BQXEmKfk.js} +0 -0
  57. /package/dist/assets/{Uridium-DanS2KoH.js → Uridium-9u86vh1V.js} +0 -0
  58. /package/dist/assets/{VegetablesDeluxe-C41ViimS.js → VegetablesDeluxe-DbmngV50.js} +0 -0
  59. /package/dist/assets/{marked.esm-fTuuvbcB.js → marked.esm-DhpYx7TE.js} +0 -0
  60. /package/dist/assets/{purify.es-CRM-GE0Y.js → purify.es-CWuqV7zK.js} +0 -0
@@ -0,0 +1,258 @@
1
+ import { inferLoadTypeFromFilename } from './load-formats.js';
2
+ import { DEFAULT_BRIDGE_URL, ULTIMATE_BRIDGE_PACKAGE_URL, getSavedUltimateSettings, getUltimateInfo, isUltimateFileType, isValidUltimateIp, launchOnUltimate, powerOffUltimate, rebootUltimate, saveUltimateSettings, } from './ultimate-bridge.js';
3
+ /**
4
+ * Settings section for playing games on a real Ultimate 64 / C64 Ultimate / Ultimate II+
5
+ * through the C64Cade Ultimate Bridge npm package running on the user's machine.
6
+ */
7
+ export default class UltimatePanel {
8
+ deviceInfo = null;
9
+ busy = false;
10
+ els;
11
+ container;
12
+ getPlayer;
13
+ constructor(container, getPlayer) {
14
+ this.container = container;
15
+ this.getPlayer = getPlayer;
16
+ }
17
+ init() {
18
+ this.render();
19
+ this.bind();
20
+ this.updateCurrentGame();
21
+ this.updateControls();
22
+ if (isValidUltimateIp(this.settings().ip))
23
+ void this.connect({ silent: true });
24
+ }
25
+ render() {
26
+ const saved = getSavedUltimateSettings();
27
+ this.container.innerHTML = `
28
+ <label class="c64-section-label">Ultimate Player</label>
29
+ <div class="c64-section-hint">
30
+ Play games on a real Ultimate 64, C64 Ultimate or Ultimate II+. Run the
31
+ <a href="${ULTIMATE_BRIDGE_PACKAGE_URL}" target="_blank" rel="noopener noreferrer">C64Cade Ultimate Bridge</a>
32
+ on this computer first: <code>npx @c64cade/ultimate-bridge</code>
33
+ </div>
34
+ <div class="c64-form-row">
35
+ <label for="c64-ultimate-bridge-url">Bridge URL</label>
36
+ <input id="c64-ultimate-bridge-url" class="c64-text-input" type="url" placeholder="${DEFAULT_BRIDGE_URL}" />
37
+ </div>
38
+ <div class="c64-form-row">
39
+ <label for="c64-ultimate-ip">Ultimate IP</label>
40
+ <input id="c64-ultimate-ip" class="c64-text-input" type="text" inputmode="decimal" placeholder="192.168.0.10" />
41
+ </div>
42
+ <div class="c64-form-row">
43
+ <label for="c64-ultimate-password">Password</label>
44
+ <input id="c64-ultimate-password" class="c64-text-input" type="password" autocomplete="off" placeholder="(optional)" />
45
+ </div>
46
+ <div class="c64-menu-actions">
47
+ <button class="c64-btn" id="c64-ultimate-connect" type="button">Connect</button>
48
+ <span class="c64-inline-status" id="c64-ultimate-device">Not connected</span>
49
+ </div>
50
+
51
+ <div class="c64-tools-section">
52
+ <label class="c64-section-label">Launch on Ultimate</label>
53
+ <div class="c64-form-row">
54
+ <button class="c64-btn" id="c64-ultimate-send-current" type="button">Send Current Game</button>
55
+ <span class="c64-inline-status" id="c64-ultimate-current-game"></span>
56
+ </div>
57
+ <div class="c64-form-row">
58
+ <button class="c64-btn" id="c64-ultimate-send-file" type="button">Send File…</button>
59
+ <span class="c64-inline-status">.prg, .crt or .d64</span>
60
+ <input id="c64-ultimate-file" class="c64-file-input" type="file" accept=".prg,.crt,.d64" />
61
+ </div>
62
+ </div>
63
+
64
+ <div class="c64-tools-section">
65
+ <label class="c64-section-label">Device</label>
66
+ <div class="c64-system-actions">
67
+ <button class="c64-btn" id="c64-ultimate-reboot" type="button">Reboot Ultimate</button>
68
+ <button class="c64-btn" id="c64-ultimate-poweroff" type="button">Power Off</button>
69
+ </div>
70
+ </div>
71
+ <div class="c64-cheat-status" id="c64-ultimate-status" role="status"></div>
72
+ `;
73
+ const q = (sel) => this.container.querySelector(sel);
74
+ this.els = {
75
+ bridgeUrl: q('#c64-ultimate-bridge-url'),
76
+ ip: q('#c64-ultimate-ip'),
77
+ password: q('#c64-ultimate-password'),
78
+ connectBtn: q('#c64-ultimate-connect'),
79
+ device: q('#c64-ultimate-device'),
80
+ currentGame: q('#c64-ultimate-current-game'),
81
+ sendCurrentBtn: q('#c64-ultimate-send-current'),
82
+ sendFileBtn: q('#c64-ultimate-send-file'),
83
+ fileInput: q('#c64-ultimate-file'),
84
+ rebootBtn: q('#c64-ultimate-reboot'),
85
+ powerOffBtn: q('#c64-ultimate-poweroff'),
86
+ status: q('#c64-ultimate-status'),
87
+ };
88
+ this.els.bridgeUrl.value = saved.bridgeUrl === DEFAULT_BRIDGE_URL ? '' : saved.bridgeUrl;
89
+ this.els.ip.value = saved.ip;
90
+ this.els.password.value = saved.password;
91
+ }
92
+ bind() {
93
+ [this.els.bridgeUrl, this.els.ip, this.els.password].forEach((input) => {
94
+ // Save as the user types so a reload or closed tab never loses the IP
95
+ input.addEventListener('input', () => this.saveFields());
96
+ input.addEventListener('change', () => {
97
+ this.saveFields();
98
+ this.deviceInfo = null;
99
+ this.updateControls();
100
+ });
101
+ });
102
+ this.els.connectBtn.addEventListener('click', () => void this.connect());
103
+ this.els.sendCurrentBtn.addEventListener('click', () => void this.sendCurrentGame());
104
+ this.els.sendFileBtn.addEventListener('click', () => this.els.fileInput.click());
105
+ this.els.fileInput.addEventListener('change', () => {
106
+ const file = this.els.fileInput.files?.[0];
107
+ this.els.fileInput.value = '';
108
+ if (file)
109
+ void this.sendFile(file);
110
+ });
111
+ this.els.rebootBtn.addEventListener('click', () => void this.reboot());
112
+ this.els.powerOffBtn.addEventListener('click', () => void this.powerOff());
113
+ const onGameChanged = () => {
114
+ this.updateCurrentGame();
115
+ this.updateControls();
116
+ };
117
+ window.addEventListener('c64-load-success', onGameChanged);
118
+ window.addEventListener('c64-detach', onGameChanged);
119
+ window.addEventListener('c64-reboot', onGameChanged);
120
+ }
121
+ settings() {
122
+ return {
123
+ bridgeUrl: this.els.bridgeUrl.value.trim() || DEFAULT_BRIDGE_URL,
124
+ ip: this.els.ip.value.trim(),
125
+ password: this.els.password.value,
126
+ };
127
+ }
128
+ saveFields() {
129
+ saveUltimateSettings({
130
+ bridgeUrl: this.els.bridgeUrl.value.trim(),
131
+ ip: this.els.ip.value.trim(),
132
+ password: this.els.password.value,
133
+ });
134
+ }
135
+ async connect({ silent = false } = {}) {
136
+ await this.run(silent ? '' : 'Connecting to Ultimate…', async () => {
137
+ this.saveFields();
138
+ const settings = this.settings();
139
+ if (!isValidUltimateIp(settings.ip)) {
140
+ throw new Error("Enter your Ultimate's IPv4 address, e.g. 192.168.0.10.");
141
+ }
142
+ this.deviceInfo = null;
143
+ this.deviceInfo = await getUltimateInfo(settings);
144
+ return silent ? '' : `Connected to ${this.describeDevice()}`;
145
+ }, { silentErrors: silent });
146
+ }
147
+ async sendCurrentGame() {
148
+ const game = this.currentGame();
149
+ if (!game)
150
+ return;
151
+ if (!isUltimateFileType(game.type)) {
152
+ this.setStatus(`Ultimate can't launch ${game.type} files — only .prg, .crt and .d64.`, 'error');
153
+ return;
154
+ }
155
+ await this.launch(game.name, game.type, game.data);
156
+ }
157
+ async sendFile(file) {
158
+ const type = inferLoadTypeFromFilename(file.name);
159
+ if (!isUltimateFileType(type)) {
160
+ this.setStatus(`${file.name} isn't a .prg, .crt or .d64 file.`, 'error');
161
+ return;
162
+ }
163
+ await this.launch(file.name, type, new Uint8Array(await file.arrayBuffer()));
164
+ }
165
+ async launch(filename, fileType, data) {
166
+ await this.run(`Sending ${filename} to Ultimate…`, async () => {
167
+ await launchOnUltimate(this.settings(), { filename, fileType, data });
168
+ return `Launched ${filename} on ${this.describeDevice()}`;
169
+ });
170
+ }
171
+ async reboot() {
172
+ if (!confirm('Reboot the Ultimate? Anything running on it will be lost.'))
173
+ return;
174
+ await this.run('Rebooting Ultimate…', async () => {
175
+ await rebootUltimate(this.settings());
176
+ return 'Ultimate rebooted';
177
+ });
178
+ }
179
+ async powerOff() {
180
+ if (!confirm('Power off the Ultimate? You will need to switch it back on by hand.'))
181
+ return;
182
+ await this.run('Powering off Ultimate…', async () => {
183
+ await powerOffUltimate(this.settings());
184
+ this.deviceInfo = null;
185
+ return 'Ultimate powered off';
186
+ });
187
+ }
188
+ /** Runs a bridge request with the buttons disabled, reporting progress and errors. */
189
+ async run(pending, task, { silentErrors = false } = {}) {
190
+ if (this.busy)
191
+ return;
192
+ this.busy = true;
193
+ if (pending)
194
+ this.setStatus(pending);
195
+ this.updateControls();
196
+ try {
197
+ const done = await task();
198
+ if (done)
199
+ this.setStatus(done, 'ok');
200
+ else if (pending)
201
+ this.setStatus('');
202
+ }
203
+ catch (err) {
204
+ if (silentErrors)
205
+ this.setStatus('');
206
+ else
207
+ this.setStatus(errorText(err), 'error');
208
+ }
209
+ finally {
210
+ this.busy = false;
211
+ this.updateControls();
212
+ }
213
+ }
214
+ describeDevice() {
215
+ const product = this.deviceInfo?.product || 'Ultimate';
216
+ const ip = this.settings().ip;
217
+ return ip ? `${product} at ${ip}` : product;
218
+ }
219
+ currentGame() {
220
+ return this.getPlayer()?.getCurrentGame?.() ?? null;
221
+ }
222
+ updateCurrentGame() {
223
+ const game = this.currentGame();
224
+ this.els.currentGame.textContent = game ? game.name : 'No game loaded';
225
+ }
226
+ updateControls() {
227
+ if (this.deviceInfo) {
228
+ const info = this.deviceInfo;
229
+ const versions = [
230
+ info.firmware_version && `firmware ${info.firmware_version}`,
231
+ info.fpga_version && `FPGA ${info.fpga_version}`,
232
+ ].filter(Boolean);
233
+ this.els.device.textContent = `● ${this.describeDevice()}${versions.length ? ` (${versions.join(', ')})` : ''}`;
234
+ this.els.device.dataset.connected = 'true';
235
+ }
236
+ else {
237
+ this.els.device.textContent = 'Not connected';
238
+ delete this.els.device.dataset.connected;
239
+ }
240
+ const connected = !!this.deviceInfo;
241
+ const game = this.currentGame();
242
+ this.els.connectBtn.disabled = this.busy;
243
+ this.els.connectBtn.textContent = connected ? 'Reconnect' : 'Connect';
244
+ this.els.sendCurrentBtn.disabled = this.busy || !connected || !game;
245
+ this.els.sendFileBtn.disabled = this.busy || !connected;
246
+ this.els.rebootBtn.disabled = this.busy || !connected;
247
+ this.els.powerOffBtn.disabled = this.busy || !connected;
248
+ }
249
+ setStatus(message, mode = 'info') {
250
+ this.els.status.textContent = message;
251
+ this.els.status.hidden = !message;
252
+ this.els.status.dataset.mode = mode;
253
+ }
254
+ }
255
+ function errorText(err) {
256
+ return err instanceof Error ? err.message : String(err);
257
+ }
258
+ //# sourceMappingURL=ultimate-panel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ultimate-panel.js","sourceRoot":"","sources":["../../src/player/ultimate-panel.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EACL,kBAAkB,EAClB,2BAA2B,EAC3B,wBAAwB,EACxB,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,EACd,oBAAoB,GAIrB,MAAM,mBAAmB,CAAC;AAI3B;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,aAAa;IACxB,UAAU,GAA8B,IAAI,CAAC;IAC7C,IAAI,GAAG,KAAK,CAAC;IACb,GAAG,CAaT;IAEe,SAAS,CAAc;IACvB,SAAS,CAAyB;IAEnD,YAAY,SAAsB,EAAE,SAAiC;QACnE,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED,IAAI;QACF,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACzB,IAAI,CAAC,cAAc,EAAE,CAAC;QACtB,IAAI,iBAAiB,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC;YAAE,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IACjF,CAAC;IAEO,MAAM;QACZ,MAAM,KAAK,GAAG,wBAAwB,EAAE,CAAC;QAEzC,IAAI,CAAC,SAAS,CAA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AAI,CAAC;QACpE,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,QAAQ,GAAG,IAAI,CAAC,IAAI,IAAI,CAAC,SAAS,CAAC;QACxD,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,QAAQ,GAAG,IAAI,CAAC,IAAI,IAAI,CAAC,SAAS,CAAC;QACtD,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,QAAQ,GAAG,IAAI,CAAC,IAAI,IAAI,CAAC,SAAS,CAAC;IAC1D,CAAC;IAEO,SAAS,CAAC,OAAe,EAAE,OAAmB,MAAM;QAC1D,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,WAAW,GAAG,OAAO,CAAC;QACtC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,OAAO,CAAC;QAClC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IACtC,CAAC;CACF;AAED,SAAS,SAAS,CAAC,GAAY;IAC7B,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1D,CAAC"}
package/package.json CHANGED
@@ -14,7 +14,7 @@
14
14
  "agent"
15
15
  ],
16
16
  "license": "MIT",
17
- "version": "3.2.0",
17
+ "version": "3.3.0",
18
18
  "type": "module",
19
19
  "engines": {
20
20
  "node": ">=24.14"
@@ -0,0 +1,197 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 hayesmaker
3
+ // See LICENSE in the project root for full license information.
4
+ /**
5
+ * player-server.mjs — static HTTP server for the built browser player (`c64-ready` CLI).
6
+ *
7
+ * Optionally serves one local game file (.prg/.d64/.crt/.c64/…) next to the player so the
8
+ * player can boot straight into it via `?game=`. The file is read from disk on every
9
+ * request, so reloading the page picks up a fresh build.
10
+ */
11
+
12
+ import { createServer } from 'node:http';
13
+ import { createReadStream, existsSync, statSync } from 'node:fs';
14
+ import { basename, extname, join, resolve, normalize, sep } from 'node:path';
15
+ import { spawn } from 'node:child_process';
16
+
17
+ export const BASE_PATH = '/c64-ready/';
18
+ export const LOCAL_GAME_PREFIX = `${BASE_PATH}local/`;
19
+ export const GAME_EXTENSIONS = ['.prg', '.d64', '.crt', '.c64', '.s64', '.snapshot'];
20
+
21
+ const MIME = {
22
+ '.html': 'text/html; charset=utf-8',
23
+ '.js': 'application/javascript',
24
+ '.mjs': 'application/javascript',
25
+ '.ts': 'application/javascript',
26
+ '.css': 'text/css',
27
+ '.wasm': 'application/wasm',
28
+ '.svg': 'image/svg+xml',
29
+ '.png': 'image/png',
30
+ '.gif': 'image/gif',
31
+ '.ico': 'image/x-icon',
32
+ '.json': 'application/json',
33
+ '.ttf': 'font/ttf',
34
+ '.map': 'application/json',
35
+ };
36
+
37
+ export const HELP = `
38
+ c64-ready — serve the C64 browser player
39
+
40
+ Usage:
41
+ c64-ready [game-file] [--port <n>] [--host] [--open] [--help]
42
+
43
+ Arguments:
44
+ game-file A .prg, .d64, .crt or .c64 snapshot to boot straight into. It is
45
+ re-read on every page load, so rebuild and refresh to see changes.
46
+
47
+ Options:
48
+ --port <n> HTTP port (default: 5173, 0 = any free port)
49
+ --host Bind to 0.0.0.0 so the player is reachable on your LAN
50
+ --open Open the player in your default browser
51
+ --help Show this help
52
+
53
+ Examples:
54
+ npx c64-ready
55
+ npx c64-ready build/main.prg --open
56
+ npx c64-ready --port 8080 --host
57
+ `.trim();
58
+
59
+ /** Parse CLI arguments. Throws on invalid input. */
60
+ export function parseServeArgs(argv) {
61
+ const o = { help: false, port: 5173, host: false, open: false, file: null };
62
+ for (let i = 0; i < argv.length; i++) {
63
+ const a = argv[i];
64
+ if (a === '--help' || a === '-h') o.help = true;
65
+ else if (a === '--host') o.host = true;
66
+ else if (a === '--open') o.open = true;
67
+ else if (a === '--port') {
68
+ const v = argv[++i];
69
+ const n = Number(v);
70
+ if (v === undefined || !Number.isInteger(n) || n < 0 || n > 65535) {
71
+ throw new Error(`--port needs a number between 0 and 65535`);
72
+ }
73
+ o.port = n;
74
+ } else if (a.startsWith('-')) throw new Error(`Unknown option: ${a}`);
75
+ else if (o.file) throw new Error(`Only one game file can be served (got ${o.file} and ${a})`);
76
+ else o.file = a;
77
+ }
78
+ if (o.file) {
79
+ const abs = resolve(o.file);
80
+ if (!existsSync(abs) || !statSync(abs).isFile()) throw new Error(`File not found: ${o.file}`);
81
+ const ext = extname(abs).toLowerCase();
82
+ if (!GAME_EXTENSIONS.includes(ext)) {
83
+ throw new Error(
84
+ `Unsupported file type ${ext || '(none)'}: expected ${GAME_EXTENSIONS.join(', ')}`,
85
+ );
86
+ }
87
+ o.file = abs;
88
+ }
89
+ return o;
90
+ }
91
+
92
+ /** The URL path that serves the local game file. */
93
+ export function localGamePath(file) {
94
+ return `${LOCAL_GAME_PREFIX}${encodeURIComponent(basename(file))}`;
95
+ }
96
+
97
+ /** The player URL (path + query) that boots into the local game file. */
98
+ export function playerPath(file) {
99
+ // '/' is legal in a query string, and the file name is already escaped by localGamePath().
100
+ return file ? `${BASE_PATH}?game=${localGamePath(file)}` : BASE_PATH;
101
+ }
102
+
103
+ /**
104
+ * Create (but do not start) the player HTTP server.
105
+ * @param {{ distDir: string, gameFile?: string | null }} opts
106
+ */
107
+ export function createPlayerServer({ distDir, gameFile = null }) {
108
+ const DIST_DIR = resolve(distDir);
109
+ const APP_ENTRY = join(DIST_DIR, 'index.html');
110
+ // Compared after decoding, so it matches however the browser escapes the name.
111
+ const gamePath = gameFile ? `${LOCAL_GAME_PREFIX}${basename(gameFile)}` : null;
112
+
113
+ const sendEntry = (res) => {
114
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
115
+ createReadStream(APP_ENTRY).pipe(res);
116
+ };
117
+
118
+ return createServer((req, res) => {
119
+ const rawPath = (req.url ?? '/').split('?')[0];
120
+ let urlPath;
121
+ try {
122
+ urlPath = decodeURIComponent(rawPath);
123
+ } catch {
124
+ res.writeHead(400);
125
+ res.end('Bad request');
126
+ return;
127
+ }
128
+
129
+ // The one local game file, if any. Always re-read; never cached.
130
+ if (gamePath && urlPath === gamePath) {
131
+ if (!existsSync(gameFile)) {
132
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
133
+ res.end(`Game file no longer exists: ${gameFile}`);
134
+ return;
135
+ }
136
+ res.writeHead(200, {
137
+ 'Content-Type': 'application/octet-stream',
138
+ 'Content-Length': statSync(gameFile).size,
139
+ 'Cache-Control': 'no-store',
140
+ });
141
+ createReadStream(gameFile).pipe(res);
142
+ return;
143
+ }
144
+
145
+ // Anything else under /local/ is a game the player asked for that we don't have.
146
+ // A 404 makes the player report it, instead of trying to boot the HTML fallback.
147
+ if (urlPath.startsWith(LOCAL_GAME_PREFIX)) {
148
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
149
+ res.end('Not found');
150
+ return;
151
+ }
152
+
153
+ // App root: /, /c64-ready, /c64-ready/ → dist/index.html
154
+ if (urlPath === '/' || urlPath === '/c64-ready' || urlPath === BASE_PATH) {
155
+ sendEntry(res);
156
+ return;
157
+ }
158
+
159
+ // Everything else resolves against dist/. Vite bakes base='/c64-ready/' into asset
160
+ // URLs, so strip it: /c64-ready/assets/x.js → dist/assets/x.js.
161
+ const stripped = urlPath.startsWith(BASE_PATH) ? urlPath.slice(BASE_PATH.length) : urlPath;
162
+ const relative = stripped.startsWith('/') ? stripped.slice(1) : stripped;
163
+ const filePath = resolve(DIST_DIR, normalize(relative));
164
+
165
+ if (filePath !== DIST_DIR && !filePath.startsWith(DIST_DIR + sep)) {
166
+ res.writeHead(403);
167
+ res.end('Forbidden');
168
+ return;
169
+ }
170
+
171
+ if (!existsSync(filePath) || !statSync(filePath).isFile()) {
172
+ sendEntry(res); // SPA fallback
173
+ return;
174
+ }
175
+
176
+ const mime = MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream';
177
+ res.writeHead(200, { 'Content-Type': mime });
178
+ createReadStream(filePath).pipe(res);
179
+ });
180
+ }
181
+
182
+ /** Open a URL in the default browser. Best effort: failures are reported, never thrown. */
183
+ export function openInBrowser(url, { platform = process.platform, spawnFn = spawn } = {}) {
184
+ const [cmd, args] =
185
+ platform === 'darwin'
186
+ ? ['open', [url]]
187
+ : platform === 'win32'
188
+ ? ['cmd', ['/c', 'start', '""', url]]
189
+ : ['xdg-open', [url]];
190
+ try {
191
+ const child = spawnFn(cmd, args, { stdio: 'ignore', detached: true });
192
+ child.on?.('error', () => console.error(` (could not open a browser: open ${url} manually)`));
193
+ child.unref?.();
194
+ } catch {
195
+ console.error(` (could not open a browser: open ${url} manually)`);
196
+ }
197
+ }
package/src/main.ts CHANGED
@@ -40,7 +40,11 @@ const cheevosTrackerPanel = new CheevosTrackerPanel();
40
40
  cheevosTrackerPanel.init();
41
41
 
42
42
  // Initialise UI with reference to the player (for audio controls)
43
- new UIController({ assetBaseUrl: base }).init(player);
43
+ new UIController({
44
+ assetBaseUrl: base,
45
+ appVersion: import.meta.env.VITE_APP_VERSION,
46
+ gitHash: import.meta.env.VITE_GIT_HASH,
47
+ }).init(player);
44
48
 
45
49
  player
46
50
  .start()
@@ -4,7 +4,7 @@ import type { C64Emulator } from '../emulator/c64-emulator';
4
4
  const loaderCss = `
5
5
  .c64-loader {
6
6
  position: relative;
7
- width: 768px;
7
+ width: min(768px, calc(100vw - 24px));
8
8
  margin-top: 12px;
9
9
  transition: opacity 0.6s ease, transform 0.6s ease;
10
10
  }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Responsive display layout for the browser player.
3
+ *
4
+ * The user-facing display *mode* (Settings → Display) is combined with the
5
+ * device context (fullscreen, touch device, orientation) to produce a concrete
6
+ * *layout*, which is written to `<html data-c64-layout="…">`. All sizing is
7
+ * done by the CSS below so the canvas follows viewport / rotation changes
8
+ * without any JS resize handling.
9
+ */
10
+
11
+ export type DisplayMode = 'standard' | 'full' | 'stretch';
12
+
13
+ /**
14
+ * - `standard` — desktop default: up to 2x (768×544) with a border, scaled down to fit.
15
+ * - `fill-width` — touch portrait default: the full width of the screen.
16
+ * - `contain` — largest size that fits the viewport, aspect ratio kept
17
+ * (fills the height on landscape phones / tablets).
18
+ * - `stretch` — fill the whole viewport, aspect ratio ignored.
19
+ */
20
+ export type DisplayLayout = 'standard' | 'fill-width' | 'contain' | 'stretch';
21
+
22
+ export interface DisplayContext {
23
+ fullscreen: boolean;
24
+ touch: boolean;
25
+ portrait: boolean;
26
+ }
27
+
28
+ export const DISPLAY_MODES: readonly DisplayMode[] = ['standard', 'full', 'stretch'];
29
+ export const DISPLAY_MODE_STORAGE_KEY = 'c64-display-mode';
30
+
31
+ /** Media query identifying phones / tablets (no hover, coarse pointer). */
32
+ export const TOUCH_DEVICE_QUERY = '(hover: none) and (pointer: coarse)';
33
+ export const PORTRAIT_QUERY = '(orientation: portrait)';
34
+
35
+ export function isDisplayMode(value: unknown): value is DisplayMode {
36
+ return typeof value === 'string' && (DISPLAY_MODES as readonly string[]).includes(value);
37
+ }
38
+
39
+ export function resolveDisplayLayout(mode: DisplayMode, ctx: DisplayContext): DisplayLayout {
40
+ if (mode === 'stretch') return 'stretch';
41
+ if (mode === 'full') return 'contain';
42
+ if (ctx.fullscreen) return 'contain';
43
+ if (ctx.touch) return ctx.portrait ? 'fill-width' : 'contain';
44
+ return 'standard';
45
+ }
46
+
47
+ /** Layouts that take over the whole viewport (no page scrolling, overlays dimmed). */
48
+ export function isFillLayout(layout: DisplayLayout): boolean {
49
+ return layout === 'contain' || layout === 'stretch';
50
+ }
51
+
52
+ // Every dvh rule is preceded by a vh fallback for older browsers.
53
+ export const displayLayoutCss = `
54
+ html[data-c64-layout=fill-width] #c64-screen{border:none;width:100vw;height:auto}
55
+ 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))}
56
+ html[data-c64-layout=stretch] #c64-screen{border:none;aspect-ratio:auto;object-fit:fill;width:100vw;height:100vh;height:100dvh}
57
+ html[data-c64-fill],html[data-c64-fill] body{overflow:hidden;overscroll-behavior:none}
58
+ html[data-c64-fill] body{height:100vh;height:100dvh;min-height:0}
59
+ 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}
60
+ 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}
61
+ html[data-c64-fill] .c64-loader{position:fixed;left:50%;bottom:16px;margin:0;translate:-50% 0;z-index:950}
62
+ .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}
63
+ .c64-fullscreen-btn svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
64
+ `;
65
+
66
+ export const FULLSCREEN_ENTER_ICON =
67
+ '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>';
68
+ export const FULLSCREEN_EXIT_ICON =
69
+ '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>';
70
+
71
+ type FullscreenDocument = Document & {
72
+ webkitFullscreenElement?: Element | null;
73
+ webkitFullscreenEnabled?: boolean;
74
+ webkitExitFullscreen?: () => Promise<void> | void;
75
+ };
76
+ type FullscreenElement = HTMLElement & {
77
+ webkitRequestFullscreen?: () => Promise<void> | void;
78
+ };
79
+
80
+ /** iPhone Safari has no element fullscreen API — the button is hidden there. */
81
+ export function isFullscreenSupported(doc: Document = document): boolean {
82
+ const d = doc as FullscreenDocument;
83
+ const el = d.documentElement as FullscreenElement;
84
+ const canRequest =
85
+ typeof el.requestFullscreen === 'function' || typeof el.webkitRequestFullscreen === 'function';
86
+ const enabled = d.fullscreenEnabled ?? d.webkitFullscreenEnabled ?? canRequest;
87
+ return canRequest && enabled !== false;
88
+ }
89
+
90
+ export function isFullscreenActive(doc: Document = document): boolean {
91
+ const d = doc as FullscreenDocument;
92
+ return !!(d.fullscreenElement ?? d.webkitFullscreenElement);
93
+ }
94
+
95
+ export async function toggleFullscreen(doc: Document = document): Promise<void> {
96
+ const d = doc as FullscreenDocument;
97
+ if (isFullscreenActive(d)) {
98
+ await (d.exitFullscreen ? d.exitFullscreen() : d.webkitExitFullscreen?.());
99
+ return;
100
+ }
101
+ // Fullscreen the whole page (not just the canvas) so the menu, help and
102
+ // unmute overlays keep working while in fullscreen.
103
+ const el = d.documentElement as FullscreenElement;
104
+ if (el.requestFullscreen) {
105
+ await el.requestFullscreen({ navigationUI: 'hide' });
106
+ } else {
107
+ await el.webkitRequestFullscreen?.();
108
+ }
109
+ }