@wasm-gaming/blastem-wasm 0.1.0 → 0.1.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.
@@ -1,145 +1,601 @@
1
- import { manifest } from './blastem.manifest.js';
2
- import { DEFAULT_BLASTEM_OPTIONS } from './blastem.options.js';
3
- export { manifest };
4
- const scriptLoadCache = new Map();
5
- function loadClassicScriptOnce(src) {
6
- const cached = scriptLoadCache.get(src);
7
- if (cached)
8
- return cached;
9
- const p = new Promise((resolve, reject) => {
10
- const script = document.createElement('script');
11
- script.src = src;
12
- script.async = true;
13
- script.onload = () => resolve();
14
- script.onerror = () => reject(new Error(`blastem: failed to load script: ${src}`));
15
- document.head.appendChild(script);
16
- });
17
- scriptLoadCache.set(src, p);
18
- return p;
19
- }
20
1
  /**
21
- * Ensure the canvas used by BlastEm has `id="canvas"`.
22
- * Emscripten SDL2 queries `document.querySelector('#canvas')` to locate its render target.
2
+ * The engine package's entry point: an `EngineSDK` for BlastEm, the Sega Mega Drive /
3
+ * Genesis emulator.
4
+ *
5
+ * ```js
6
+ * import BlastemSDK from '@wasm-gaming/blastem-wasm';
7
+ *
8
+ * const play = await new BlastemSDK()
9
+ * .assets({ rom: () => readRom() }) // bytes, or a thunk
10
+ * .storage({ namespace: 'old-towers' }) // → OPFS blastem/old-towers/
11
+ * .mount(document.querySelector('#stage'))
12
+ * .start();
13
+ *
14
+ * play.pause('menu'); play.resume('menu');
15
+ * await play.restart(); // soft reset
16
+ * await play.destroy(); // saves flushed, loop stopped, audio closed
17
+ * ```
18
+ *
19
+ * Everything a host drives is the contract's (`@wasm-gaming/engine-specs`); what is
20
+ * this engine's own: {@link BlastemConfig} and friends, owner-aware
21
+ * {@link BlastemPlay.pause} / {@link BlastemPlay.resume}, {@link BlastemPlay.storagePath}
22
+ * and the `saves` event.
23
+ *
24
+ * Saves: the wasm build writes every save of the running game to MEMFS `/save`
25
+ * (upstream's `save_path`, patched). The SDK seeds it from OPFS `blastem/<namespace>/`
26
+ * before boot and mirrors it back after asking BlastEm to flush (`web_persist_save`):
27
+ * every 10 s, on pause, when the page is hidden and on destroy. Upstream only flushed
28
+ * at exit, which a web page never reaches.
23
29
  */
24
- function prepareCanvas(canvas) {
25
- if (canvas.id !== 'canvas') {
26
- // Clone or alias — prefer aliasing so the caller's reference remains valid.
27
- canvas.id = 'canvas';
30
+ import { EnginePlayBase, EngineSDKBase, EventEmitter, } from './engine-specs.js';
31
+ import { BLASTEM_SPEC, BLASTEM_VIDEO, } from './blastem.options.js';
32
+ export { BLASTEM_SPEC, BLASTEM_VIDEO } from './blastem.options.js';
33
+ const ENGINE_ID = 'blastem';
34
+ const DEFAULT_STORAGE_NAMESPACE = 'default';
35
+ const SAVE_DIR = '/save';
36
+ const ROM_DIR = '/rom';
37
+ const SAVE_INTERVAL_MS = 10_000;
38
+ const REGION_FLAG = { us: 'U', eu: 'E', jp: 'J' };
39
+ /**
40
+ * Where an engine keeps one namespace: `<engineId>/<namespace>`, relative to the OPFS
41
+ * root. Identical to rsdkv4's, written to move verbatim into engine-specs: segments
42
+ * cleaned, `.` and `..` dropped, anything outside `[A-Za-z0-9._-]` → `_`, nothing
43
+ * usable → `default`; a leading `<engineId>/` is stripped once.
44
+ */
45
+ export function storagePath(engineId, namespace) {
46
+ const segments = typeof namespace === 'string'
47
+ ? namespace
48
+ .split('/')
49
+ .map((segment) => segment.trim())
50
+ .filter((segment) => segment && segment !== '.' && segment !== '..')
51
+ .map((segment) => segment.replace(/[^A-Za-z0-9._-]/g, '_'))
52
+ : [];
53
+ const prefixed = segments.length > 1 && segments[0] === engineId;
54
+ if (prefixed)
55
+ segments.shift();
56
+ const cleaned = segments.join('/') || DEFAULT_STORAGE_NAMESPACE;
57
+ return { namespace: cleaned, path: `${engineId}/${cleaned}`, prefixed };
58
+ }
59
+ async function opfsDir(path, create) {
60
+ if (typeof navigator === 'undefined' || !navigator.storage?.getDirectory)
61
+ return null;
62
+ try {
63
+ let dir = await navigator.storage.getDirectory();
64
+ for (const segment of path.split('/').filter(Boolean)) {
65
+ dir = await dir.getDirectoryHandle(segment, { create });
66
+ }
67
+ return dir;
68
+ }
69
+ catch {
70
+ return null;
28
71
  }
29
- // Emscripten SDL2 reads getBoundingClientRect(); ensure it has layout dimensions.
30
- if (!canvas.width)
31
- canvas.width = 640;
32
- if (!canvas.height)
33
- canvas.height = 480;
34
- // SDL2's Emscripten backend shrinks the canvas to 1x1 and measures
35
- // getBoundingClientRect() to detect external CSS sizing. Borders/padding are
36
- // included in that rect, so decoration on the canvas itself makes SDL create
37
- // a tiny (e.g. 5x5) window. Host pages should decorate a wrapper instead.
38
- canvas.style.border = '0';
39
- canvas.style.padding = '0';
40
- return canvas;
41
72
  }
42
- function toUint8(x) {
43
- if (x == null)
73
+ async function resolveAsset(asset) {
74
+ const value = typeof asset === 'function' ? await asset() : asset;
75
+ if (value == null)
44
76
  return null;
45
- if (typeof x === 'string')
46
- return new TextEncoder().encode(x);
47
- if (x instanceof Uint8Array)
48
- return x;
49
- if (x instanceof ArrayBuffer)
50
- return new Uint8Array(x);
51
- if (ArrayBuffer.isView(x))
52
- return new Uint8Array(x.buffer, x.byteOffset, x.byteLength);
53
- throw new TypeError('asset must be Uint8Array | ArrayBuffer | string');
77
+ if (value instanceof Uint8Array)
78
+ return value;
79
+ if (value instanceof ArrayBuffer)
80
+ return new Uint8Array(value);
81
+ throw new TypeError('blastem: an asset must be a Uint8Array, an ArrayBuffer or a thunk returning one');
54
82
  }
55
- export async function load(config) {
56
- const { canvas, assets, onEvent } = config;
57
- if (!canvas)
58
- throw new Error('blastem: config.canvas is required');
59
- const emit = (e) => {
60
- try {
61
- onEvent?.(e);
83
+ function sameBytes(a, b) {
84
+ if (!a || a.length !== b.length)
85
+ return false;
86
+ for (let i = 0; i < a.length; i++)
87
+ if (a[i] !== b[i])
88
+ return false;
89
+ return true;
90
+ }
91
+ /** The ROM's extension, so BlastEm sees the file the way the player named it. */
92
+ function romName(bytes) {
93
+ // SMD-interleaved dumps start with a 512-byte header; BlastEm detects them by content.
94
+ return bytes.length % 0x4000 === 512 ? 'game.smd' : 'game.bin';
95
+ }
96
+ /** The player's save-state slots: 0-3 (BlastEm numbers 0-9). */
97
+ export const STATE_SLOTS = 4;
98
+ /**
99
+ * The *unsaved* suspend point (Classic Mini style): written when the player leaves,
100
+ * offered when they come back, and saved into a numbered slot only when they ask.
101
+ */
102
+ export const AUTO_STATE_SLOT = 9;
103
+ const STATE_EXTS = ['state', 'gst'];
104
+ const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve()));
105
+ const mtimeOf = (value) => value instanceof Date ? value.getTime() : typeof value === 'number' ? value : 0;
106
+ /** The live engine: one booted BlastEm and its session. */
107
+ export class BlastemPlay extends EnginePlayBase {
108
+ #module = null;
109
+ #destroyed = false;
110
+ #pauseOwner = null;
111
+ #canvas = null;
112
+ #ownsCanvas = false;
113
+ #box = null;
114
+ #boxObserver = null;
115
+ #namespace = DEFAULT_STORAGE_NAMESPACE;
116
+ #storagePath = `${ENGINE_ID}/${DEFAULT_STORAGE_NAMESPACE}`;
117
+ #persist = true;
118
+ #saveTimer = null;
119
+ #lastSaved = new Map();
120
+ #flushing = null;
121
+ #onHidden = () => {
122
+ if (document.visibilityState === 'hidden')
123
+ void this.flushSaves();
124
+ };
125
+ constructor(init, events) {
126
+ super(BLASTEM_SPEC, init, events);
127
+ }
128
+ /** The normalised namespace this session uses. */
129
+ get namespace() {
130
+ return this.#namespace;
131
+ }
132
+ /** Where this session's saves live, relative to the OPFS root: `blastem/<namespace>`. */
133
+ get storagePath() {
134
+ return this.#storagePath;
135
+ }
136
+ /**
137
+ * The current frame as a PNG, read inside an animation frame (the picture is only
138
+ * there right after the game drew it): take it *before* pausing. Null when there is
139
+ * nothing to read.
140
+ */
141
+ async snapshot() {
142
+ const canvas = this.#canvas;
143
+ if (!canvas || !this.#module)
144
+ return null;
145
+ await nextFrame();
146
+ const copy = document.createElement('canvas');
147
+ copy.width = BLASTEM_VIDEO.width;
148
+ copy.height = BLASTEM_VIDEO.height;
149
+ copy.getContext('2d')?.drawImage(canvas, 0, 0, copy.width, copy.height);
150
+ return new Promise((resolve) => copy.toBlob((blob) => resolve(blob), 'image/png'));
151
+ }
152
+ /** Save states — see {@link BlastemStates}. */
153
+ get states() {
154
+ const Module = this.#requireModule();
155
+ const { FS } = Module;
156
+ const file = (name) => `${SAVE_DIR}/${name}`;
157
+ const exists = (name) => {
158
+ try {
159
+ FS.stat(file(name));
160
+ return true;
161
+ }
162
+ catch {
163
+ return false;
164
+ }
165
+ };
166
+ const stateFile = (slot) => {
167
+ for (const ext of STATE_EXTS) {
168
+ const name = `slot_${slot}.${ext}`;
169
+ try {
170
+ return { name, mtime: mtimeOf(FS.stat(file(name)).mtime) };
171
+ }
172
+ catch {
173
+ /* not this one */
174
+ }
175
+ }
176
+ return null;
177
+ };
178
+ const checkSlot = (slot) => {
179
+ if (slot === AUTO_STATE_SLOT || (Number.isInteger(slot) && slot >= 0 && slot < STATE_SLOTS))
180
+ return slot;
181
+ throw new RangeError(`blastem: a state slot is 0-${STATE_SLOTS - 1} or ${AUTO_STATE_SLOT}, not ${slot}`);
182
+ };
183
+ const isLocked = (slot) => exists(`slot_${slot}.lock`);
184
+ const refuseLocked = (slot) => {
185
+ if (isLocked(slot))
186
+ throw new Error(`blastem: state slot ${slot} is locked`);
187
+ };
188
+ const unlink = (name) => {
189
+ try {
190
+ FS.unlink(file(name));
191
+ }
192
+ catch {
193
+ /* not there */
194
+ }
195
+ };
196
+ // Removed files have to leave OPFS too: the mirror only ever writes.
197
+ const forget = async (names) => {
198
+ for (const name of names) {
199
+ unlink(name);
200
+ this.#lastSaved.delete(name);
201
+ }
202
+ const dir = this.#persist ? await opfsDir(this.#storagePath, false) : null;
203
+ for (const name of names)
204
+ await dir?.removeEntry(name).catch(() => { });
205
+ };
206
+ const get = (slot) => {
207
+ checkSlot(slot);
208
+ const state = stateFile(slot);
209
+ let thumbnail = null;
210
+ if (state && exists(`slot_${slot}.png`)) {
211
+ thumbnail = new Blob([new Uint8Array(FS.readFile(file(`slot_${slot}.png`)))], { type: 'image/png' });
212
+ }
213
+ return { slot, savedAt: state ? new Date(state.mtime) : null, thumbnail, locked: isLocked(slot) };
214
+ };
215
+ return {
216
+ list: () => Array.from({ length: STATE_SLOTS }, (_, slot) => get(slot)),
217
+ get,
218
+ save: async (slot, options = {}) => {
219
+ checkSlot(slot);
220
+ refuseLocked(slot);
221
+ const before = stateFile(slot);
222
+ if (!Module._web_save_state(slot))
223
+ throw new Error('blastem: no game running to save');
224
+ // A paused game has to run for the request to reach a sync point — and BlastEm
225
+ // paces itself on the audio callback, so the sound has to run too: routed
226
+ // through a silent gain for those few frames.
227
+ const owner = this.#pauseOwner;
228
+ const muted = owner ? await this.#runMuted() : null;
229
+ try {
230
+ const deadline = performance.now() + 3000;
231
+ let after = stateFile(slot);
232
+ while (!(after && (!before || after.mtime !== before.mtime)) && performance.now() < deadline) {
233
+ await nextFrame();
234
+ after = stateFile(slot);
235
+ }
236
+ if (!after)
237
+ throw new Error('blastem: the state was not written');
238
+ }
239
+ finally {
240
+ await muted?.();
241
+ }
242
+ if (options.thumbnail) {
243
+ FS.writeFile(file(`slot_${slot}.png`), new Uint8Array(await options.thumbnail.arrayBuffer()));
244
+ }
245
+ else
246
+ await forget([`slot_${slot}.png`]);
247
+ await this.flushSaves();
248
+ },
249
+ load: (slot) => {
250
+ checkSlot(slot);
251
+ if (!stateFile(slot))
252
+ return false;
253
+ return Module._web_load_state(slot) !== 0;
254
+ },
255
+ copy: async (from, to) => {
256
+ checkSlot(from);
257
+ checkSlot(to);
258
+ refuseLocked(to);
259
+ const state = stateFile(from);
260
+ if (!state)
261
+ throw new Error(`blastem: state slot ${from} is empty`);
262
+ const ext = state.name.slice(state.name.lastIndexOf('.') + 1);
263
+ await forget(STATE_EXTS.map((e) => `slot_${to}.${e}`).concat(`slot_${to}.png`));
264
+ FS.writeFile(file(`slot_${to}.${ext}`), new Uint8Array(FS.readFile(file(state.name))));
265
+ if (exists(`slot_${from}.png`)) {
266
+ FS.writeFile(file(`slot_${to}.png`), new Uint8Array(FS.readFile(file(`slot_${from}.png`))));
267
+ }
268
+ await this.flushSaves();
269
+ },
270
+ lock: async (slot, locked) => {
271
+ checkSlot(slot);
272
+ if (locked) {
273
+ if (!stateFile(slot))
274
+ throw new Error(`blastem: state slot ${slot} is empty`);
275
+ FS.writeFile(file(`slot_${slot}.lock`), new Uint8Array([1]));
276
+ await this.flushSaves();
277
+ }
278
+ else {
279
+ await forget([`slot_${slot}.lock`]);
280
+ this.emit('saves', { files: [`slot_${slot}.lock`] });
281
+ }
282
+ },
283
+ remove: async (slot) => {
284
+ checkSlot(slot);
285
+ refuseLocked(slot);
286
+ const names = [...STATE_EXTS.map((ext) => `slot_${slot}.${ext}`), `slot_${slot}.png`];
287
+ await forget(names);
288
+ this.emit('saves', { files: names });
289
+ },
290
+ };
291
+ }
292
+ /** Run the paused loop with the sound going nowhere; returns the undo. */
293
+ async #runMuted() {
294
+ const Module = this.#requireModule();
295
+ const context = Module.SDL2?.audioContext;
296
+ const node = Module.SDL2?.audio?.scriptProcessorNode;
297
+ let gain = null;
298
+ if (context && node) {
299
+ gain = context.createGain();
300
+ gain.gain.value = 0;
301
+ gain.connect(context.destination);
302
+ node.disconnect();
303
+ node.connect(gain);
304
+ await context.resume().catch(() => { });
62
305
  }
63
- catch {
64
- // host callback must not break the engine runtime
306
+ Module._emscripten_resume_main_loop();
307
+ return async () => {
308
+ // Still paused by the same owner (nobody resumed meanwhile): freeze again.
309
+ if (this.#pauseOwner) {
310
+ Module._emscripten_pause_main_loop();
311
+ await context?.suspend().catch(() => { });
312
+ }
313
+ if (context && node && gain) {
314
+ node.disconnect();
315
+ node.connect(context.destination);
316
+ gain.disconnect();
317
+ }
318
+ };
319
+ }
320
+ #requireModule() {
321
+ if (!this.#module)
322
+ throw new Error('blastem: the engine is not running — start() it first');
323
+ return this.#module;
324
+ }
325
+ /** Who holds the pause, or null while running. */
326
+ get pausedBy() {
327
+ return this.#pauseOwner;
328
+ }
329
+ /**
330
+ * Freeze emulation and sound. The first caller owns the pause, and only that
331
+ * owner's {@link resume} lifts it, so an overlay cannot resume a game the host had
332
+ * already frozen. Saves are flushed, since a paused game is often a closed one.
333
+ */
334
+ pause(owner = 'host') {
335
+ const Module = this.#module;
336
+ if (!Module || this.#pauseOwner)
337
+ return;
338
+ this.#pauseOwner = owner;
339
+ Module._emscripten_pause_main_loop();
340
+ void Module.SDL2?.audioContext?.suspend();
341
+ void this.flushSaves();
342
+ this.emit('pause', { owner });
343
+ }
344
+ resume(owner = 'host') {
345
+ const Module = this.#module;
346
+ if (!Module || this.#pauseOwner !== owner)
347
+ return;
348
+ this.#pauseOwner = null;
349
+ void Module.SDL2?.audioContext?.resume();
350
+ Module._emscripten_resume_main_loop();
351
+ this.emit('resume', { owner });
352
+ }
353
+ /**
354
+ * Ask BlastEm to write its saves, then copy whatever changed in `/save` to OPFS
355
+ * `blastem/<namespace>/`. Emits `saves` with the files that moved. Safe to call any
356
+ * time; overlapping calls share one flush.
357
+ */
358
+ flushSaves() {
359
+ this.#flushing ??= this.#flush().finally(() => {
360
+ this.#flushing = null;
361
+ });
362
+ return this.#flushing;
363
+ }
364
+ // ---- Contract hooks ----
365
+ mounted(target) {
366
+ if (target instanceof HTMLCanvasElement) {
367
+ this.#canvas = target;
368
+ this.#ownsCanvas = false;
369
+ this.#box = target.parentElement;
65
370
  }
66
- };
67
- const opts = {
68
- ...DEFAULT_BLASTEM_OPTIONS,
69
- ...config.options,
70
- };
71
- const romBytes = toUint8(assets?.rom ?? assets?.data);
72
- if (!romBytes) {
73
- throw new Error('blastem: no ROM bytes provided — pass assets.rom');
74
- }
75
- prepareCanvas(canvas);
76
- const jsUrl = config.jsUrl ?? new URL('./blastem.js', import.meta.url).href;
77
- const wasmUrl = new URL('./blastem.wasm', jsUrl).href;
78
- let modRef = null;
79
- let readyResolve = null;
80
- const readyPromise = new Promise((resolve) => {
81
- readyResolve = resolve;
82
- });
83
- const moduleOverrides = {
84
- canvas,
85
- noInitialRun: true,
86
- locateFile(path) {
87
- if (path.endsWith('.wasm'))
88
- return wasmUrl;
89
- return new URL(path, jsUrl).href;
90
- },
91
- onRuntimeInitialized() {
92
- const mod = modRef ?? (globalThis.Module ?? null);
93
- if (!mod)
94
- return;
95
- // Write ROM into MEMFS before callMain so BlastEm can open it.
371
+ else {
372
+ this.#canvas = document.createElement('canvas');
373
+ this.#ownsCanvas = true;
374
+ this.#box = target;
375
+ target.appendChild(this.#canvas);
376
+ }
377
+ const canvas = this.#canvas;
378
+ // Emscripten's SDL2 finds its window by id, and measures the element: no border or
379
+ // padding on the canvas itself, or SDL creates a tiny window.
380
+ canvas.id = 'canvas';
381
+ canvas.width = BLASTEM_VIDEO.width;
382
+ canvas.height = BLASTEM_VIDEO.height;
383
+ canvas.tabIndex = 0;
384
+ canvas.style.border = '0';
385
+ canvas.style.padding = '0';
386
+ canvas.style.display = 'block';
387
+ canvas.addEventListener('contextmenu', (event) => event.preventDefault());
388
+ void this.#applyFilter();
389
+ if (this.#box && this.#ownsCanvas) {
390
+ this.#boxObserver?.disconnect();
391
+ this.#boxObserver = new ResizeObserver(() => this.#fit());
392
+ this.#boxObserver.observe(this.#box);
393
+ this.#fit();
394
+ }
395
+ }
396
+ async open(_options) {
397
+ if (this.#destroyed) {
398
+ throw new Error('blastem: this engine has been destroyed and cannot be started again in this page — build a new BlastemSDK in a new page');
399
+ }
400
+ if (this.#module) {
401
+ // Already running: a restart is BlastEm's soft reset.
402
+ if (this.#pauseOwner)
403
+ this.resume(this.#pauseOwner);
404
+ this.#module._web_soft_reset();
405
+ return;
406
+ }
407
+ await this.#boot();
408
+ }
409
+ patched(kind, patch) {
410
+ if (kind === 'config' && 'renderFilter' in patch)
411
+ void this.#applyFilter();
412
+ }
413
+ async close() {
414
+ if (this.#saveTimer)
415
+ clearInterval(this.#saveTimer);
416
+ this.#saveTimer = null;
417
+ document.removeEventListener('visibilitychange', this.#onHidden);
418
+ window.removeEventListener('pagehide', this.#onHidden);
419
+ const Module = this.#module;
420
+ if (Module) {
421
+ await this.flushSaves();
96
422
  try {
97
- mod.FS_createPath('/', 'rom', true, true);
423
+ Module._emscripten_pause_main_loop();
98
424
  }
99
425
  catch {
100
- // /rom may already exist
426
+ /* already gone */
101
427
  }
102
- mod.FS_createDataFile('/rom', opts.romFileName, romBytes, true, true, true);
103
- readyResolve?.();
104
- },
105
- };
106
- // Some BlastEm builds are classic scripts (global Module), others expose a global factory.
107
- globalThis.Module = moduleOverrides;
108
- await loadClassicScriptOnce(jsUrl);
109
- const g = globalThis;
110
- if (typeof g.createBlastemModule === 'function') {
111
- modRef = await g.createBlastemModule(moduleOverrides);
112
- }
113
- else if (g.Module) {
114
- modRef = g.Module;
115
- }
116
- else {
117
- throw new Error('blastem: unable to initialize runtime module from blastem.js');
118
- }
119
- await readyPromise;
120
- // Boot the emulator pointing at the ROM path.
121
- modRef.callMain([`/rom/${opts.romFileName}`]);
122
- emit({ type: 'ready' });
123
- return {
124
- start() {
125
- // BlastEm starts automatically after callMain().
126
- },
127
- pause() {
128
- // No pause API exposed by the Emscripten build.
129
- },
130
- resume() {
131
- // No pause API exposed by the Emscripten build.
132
- },
133
- reset() {
134
- // BlastEm does not expose a reset hook via the WASM API.
135
- },
136
- setInput(_map) {
137
- // Input is handled by Emscripten SDL2 event loop; no external override needed.
138
- },
139
- destroy() {
140
- // No shutdown hook in the Emscripten module.
141
- },
142
- };
428
+ try {
429
+ await Module.SDL2?.audioContext?.close();
430
+ }
431
+ catch {
432
+ /* already closed */
433
+ }
434
+ }
435
+ this.#boxObserver?.disconnect();
436
+ this.#boxObserver = null;
437
+ if (this.#ownsCanvas)
438
+ this.#canvas?.remove();
439
+ this.#canvas = null;
440
+ this.#module = null;
441
+ this.#pauseOwner = null;
442
+ this.#destroyed = true;
443
+ }
444
+ // ---- Boot ----
445
+ async #boot() {
446
+ const config = await this.#values('config');
447
+ const assets = await this.#values('assets');
448
+ const storage = await this.#values('storage');
449
+ if (!this.#canvas) {
450
+ throw new Error('blastem: mount() an element (or a canvas) before start()');
451
+ }
452
+ const rom = await resolveAsset(assets.rom);
453
+ if (!rom)
454
+ throw new Error('blastem: no ROM — hand one over as assets.rom (bytes or a thunk)');
455
+ const resolved = storagePath(ENGINE_ID, storage.namespace);
456
+ this.#namespace = resolved.namespace;
457
+ this.#storagePath = resolved.path;
458
+ this.#persist = storage.persist !== null;
459
+ const jsUrl = config.jsUrl ?? new URL('./blastem.js', import.meta.url).href;
460
+ const wasmUrl = config.wasmUrl ?? new URL('./blastem.wasm', import.meta.url).href;
461
+ const { default: createBlastem } = (await import(/* @vite-ignore */ jsUrl));
462
+ let failed = null;
463
+ const Module = await createBlastem({
464
+ canvas: this.#canvas,
465
+ noInitialRun: true,
466
+ locateFile: (path) => (path.endsWith('.wasm') ? wasmUrl : new URL(path, jsUrl).href),
467
+ print: (text) => console.log('[blastem]', text),
468
+ printErr: (text) => console.warn('[blastem]', text),
469
+ onAbort: (what) => failed?.(new Error(`blastem: aborted — ${String(what)}`)),
470
+ });
471
+ this.#module = Module;
472
+ failed = (error) => this.emit('error', error);
473
+ const { FS } = Module;
474
+ for (const dir of [ROM_DIR, SAVE_DIR]) {
475
+ try {
476
+ FS.mkdir(dir);
477
+ }
478
+ catch {
479
+ /* exists */
480
+ }
481
+ }
482
+ const name = romName(rom);
483
+ FS.writeFile(`${ROM_DIR}/${name}`, rom);
484
+ if (this.#persist)
485
+ await this.#restoreSaves();
486
+ const args = [];
487
+ if (config.region && config.region !== 'auto')
488
+ args.push('-r', REGION_FLAG[config.region]);
489
+ args.push(`${ROM_DIR}/${name}`, String(BLASTEM_VIDEO.width), String(BLASTEM_VIDEO.height));
490
+ Module.callMain(args);
491
+ if (this.#persist) {
492
+ this.#saveTimer = setInterval(() => void this.flushSaves(), SAVE_INTERVAL_MS);
493
+ document.addEventListener('visibilitychange', this.#onHidden);
494
+ window.addEventListener('pagehide', this.#onHidden);
495
+ }
496
+ this.#fit();
497
+ }
498
+ /** The plain values behind one payload's descriptors. */
499
+ async #values(kind) {
500
+ const described = (await this[kind]());
501
+ const out = {};
502
+ for (const [key, property] of Object.entries(described))
503
+ out[key] = property.value;
504
+ return out;
505
+ }
506
+ // ---- Saves ----
507
+ async #restoreSaves() {
508
+ const dir = await opfsDir(this.#storagePath, false);
509
+ if (!dir || !this.#module)
510
+ return;
511
+ const iterable = dir;
512
+ for await (const [name, handle] of iterable.entries()) {
513
+ if (handle.kind !== 'file')
514
+ continue;
515
+ const bytes = new Uint8Array(await (await handle.getFile()).arrayBuffer());
516
+ this.#module.FS.writeFile(`${SAVE_DIR}/${name}`, bytes);
517
+ this.#lastSaved.set(name, bytes);
518
+ }
519
+ }
520
+ async #flush() {
521
+ const Module = this.#module;
522
+ if (!Module || !this.#persist)
523
+ return;
524
+ try {
525
+ Module._web_persist_save();
526
+ }
527
+ catch (e) {
528
+ console.warn('[blastem] persist_save failed', e);
529
+ return;
530
+ }
531
+ const changed = [];
532
+ for (const name of Module.FS.readdir(SAVE_DIR)) {
533
+ if (name === '.' || name === '..')
534
+ continue;
535
+ const path = `${SAVE_DIR}/${name}`;
536
+ if (!Module.FS.isFile(Module.FS.stat(path).mode))
537
+ continue;
538
+ const bytes = new Uint8Array(Module.FS.readFile(path));
539
+ if (!sameBytes(this.#lastSaved.get(name), bytes))
540
+ changed.push([name, bytes]);
541
+ }
542
+ if (changed.length === 0)
543
+ return;
544
+ const dir = await opfsDir(this.#storagePath, true);
545
+ if (!dir)
546
+ return;
547
+ const written = [];
548
+ for (const [name, bytes] of changed) {
549
+ try {
550
+ const writable = await (await dir.getFileHandle(name, { create: true })).createWritable();
551
+ await writable.write(bytes);
552
+ await writable.close();
553
+ this.#lastSaved.set(name, bytes);
554
+ written.push(name);
555
+ }
556
+ catch (e) {
557
+ console.warn(`[blastem] could not persist ${name}`, e);
558
+ }
559
+ }
560
+ if (written.length)
561
+ this.emit('saves', { files: written });
562
+ }
563
+ // ---- Picture ----
564
+ #fit() {
565
+ const canvas = this.#canvas;
566
+ const box = this.#box;
567
+ if (!canvas || !box || !this.#ownsCanvas)
568
+ return;
569
+ const { width, height } = box.getBoundingClientRect();
570
+ if (!width || !height)
571
+ return;
572
+ const scale = Math.min(width / BLASTEM_VIDEO.width, height / BLASTEM_VIDEO.height);
573
+ canvas.style.width = `${Math.floor(BLASTEM_VIDEO.width * scale)}px`;
574
+ canvas.style.height = `${Math.floor(BLASTEM_VIDEO.height * scale)}px`;
575
+ }
576
+ async #applyFilter() {
577
+ const canvas = this.#canvas;
578
+ if (!canvas)
579
+ return;
580
+ const { renderFilter } = await this.#values('config');
581
+ canvas.style.imageRendering = renderFilter === 'smooth' ? 'auto' : 'pixelated';
582
+ }
583
+ }
584
+ /**
585
+ * The factory a host constructs: static identity, the configuration chain, and a
586
+ * `start()` that boots BlastEm and opens a session.
587
+ */
588
+ export class BlastemSDK extends EngineSDKBase {
589
+ static id = ENGINE_ID;
590
+ /** Kept in step with package.json by `node scripts/sync-version.mjs`. */
591
+ static version = '0.1.1';
592
+ static name = 'BlastEm';
593
+ static description = 'BlastEm, the Sega Mega Drive / Genesis emulator by Michael Pavone, compiled to WebAssembly. Ships no games: the player provides the ROM, and it never leaves their browser.';
594
+ createPlay(init, events) {
595
+ return new BlastemPlay(init, events);
596
+ }
143
597
  }
144
- export default { manifest, load };
598
+ /** CI's conformance line: if this class stops satisfying the contract, `make test` fails. */
599
+ export const BLASTEM_ENGINE = BlastemSDK;
600
+ export default BlastemSDK;
145
601
  //# sourceMappingURL=blastem.sdk.js.map