@wasm-gaming/blastem-wasm 0.1.0 → 0.1.2

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