@amritk/nish-x86_64-linux 0.38.0 → 0.40.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 (86) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +455 -65
  4. package/package.json +1 -1
  5. package/runtime/core/host.d.ts +11 -0
  6. package/runtime/core/host.mjs +35 -0
  7. package/runtime/nish.d.ts +320 -33
  8. package/runtime/nish.h +84 -10
  9. package/runtime/nish.mjs +69 -6
  10. package/runtime/node.mjs +117 -0
  11. package/runtime/page-frame.d.ts +123 -0
  12. package/runtime/page-frame.mjs +736 -0
  13. package/runtime/page-game.d.ts +132 -0
  14. package/runtime/page-game.mjs +738 -0
  15. package/runtime/runtime-aes.c +97 -12
  16. package/runtime/runtime-async.c +43 -10
  17. package/runtime/runtime-bytes.c +88 -4
  18. package/runtime/runtime-checksum.c +207 -15
  19. package/runtime/runtime-net.c +64 -3
  20. package/runtime/runtime-os.c +174 -27
  21. package/runtime/runtime-region.c +94 -10
  22. package/runtime/runtime-sandbox.c +404 -17
  23. package/runtime/runtime-sha256.c +11 -4
  24. package/runtime/runtime-wasm.c +437 -0
  25. package/runtime/runtime.c +5 -0
  26. package/runtime/vite.mjs +1 -1
  27. package/scripts/build.sh +42 -8
  28. package/std/README.md +78 -91
  29. package/std/array.ts +36 -3
  30. package/std/collections.ts +51 -0
  31. package/std/compress/checksum.ts +13 -0
  32. package/std/compress/deflate.ts +0 -2
  33. package/std/crypto/hmac.ts +37 -10
  34. package/std/crypto/p256.ts +1629 -2732
  35. package/std/crypto/p384.ts +3 -1
  36. package/std/crypto/pki.ts +151 -13
  37. package/std/crypto/sha256.ts +34 -6
  38. package/std/crypto/x25519.ts +153 -64
  39. package/std/crypto/x509.ts +120 -10
  40. package/std/host/game.ts +273 -0
  41. package/std/input.ts +56 -0
  42. package/std/json-tokenizer.ts +344 -111
  43. package/std/json-typed.ts +256 -12
  44. package/std/json-value.ts +144 -3
  45. package/std/json.ts +63 -8
  46. package/std/net/fetch.ts +22 -4
  47. package/std/net/handler.ts +130 -16
  48. package/std/net/http-server.ts +3382 -0
  49. package/std/net/http1-client-codec.ts +6 -2
  50. package/std/net/http1-codec.ts +636 -162
  51. package/std/net/http1-server.ts +569 -42
  52. package/std/net/http2-cleartext.ts +526 -0
  53. package/std/net/http2-tls.ts +48 -0
  54. package/std/net/http2.ts +131 -14
  55. package/std/net/http3-server.ts +29 -3
  56. package/std/net/http3.ts +180 -7
  57. package/std/net/postgres-async.ts +1304 -86
  58. package/std/net/postgres-carrier.ts +343 -10
  59. package/std/net/postgres.ts +122 -7
  60. package/std/net/prefork.ts +195 -11
  61. package/std/net/quic-datagram.ts +30 -0
  62. package/std/net/quic-listener.ts +38 -12
  63. package/std/net/quic-packet.ts +19 -6
  64. package/std/net/quic-recovery.ts +373 -27
  65. package/std/net/quic-stream.ts +195 -37
  66. package/std/net/quic.ts +516 -22
  67. package/std/net/router.ts +407 -38
  68. package/std/net/serve.ts +1022 -110
  69. package/std/net/tls/codec.ts +110 -32
  70. package/std/net/tls/record-server.ts +37 -7
  71. package/std/net/tls/verify.ts +19 -1
  72. package/std/net/tls-tcp.ts +56 -1
  73. package/std/net/tls.ts +196 -50
  74. package/std/net/url.ts +83 -35
  75. package/std/net/websocket.ts +129 -19
  76. package/std/net/webtransport.ts +185 -1
  77. package/std/raster.ts +837 -0
  78. package/std/regex.ts +69 -47
  79. package/std/region.ts +62 -11
  80. package/std/release.ts +593 -0
  81. package/std/secret.ts +26 -59
  82. package/std/synth.ts +143 -0
  83. package/std/text.ts +233 -0
  84. package/std/threads.ts +298 -0
  85. package/std/yaml-json.ts +368 -28
  86. package/std/yaml.ts +122 -27
@@ -0,0 +1,738 @@
1
+ // nish/page/game: runs a game built over `nish/host/game` on a canvas with one
2
+ // call. It loads the module from its URL, draws GAME_FRAME through
3
+ // nish/page/frame's presenter at the display's rate, feeds key, pointer and
4
+ // touch input into GAME_INPUT, and plays the ids the game queues on
5
+ // GAME_SOUNDS through WebAudio. Plain ECMAScript importing only its two
6
+ // siblings, so a page serves the three files as they are.
7
+ //
8
+ // Every browser object (`fetch`, `WebAssembly`, `AudioContext`,
9
+ // `ResizeObserver`, `matchMedia`, `devicePixelRatio`, `addEventListener`) is read from
10
+ // `globalThis` when it is used, never when the module loads, so
11
+ // tests/game-page drives it under Node against fakes.
12
+
13
+ import { createPresenter, runFixedStep } from "./page-frame.mjs";
14
+ import { ringOver } from "./page.mjs";
15
+
16
+ // nish/term's constants (std/term.ts), which a game's StepInput reads.
17
+ const EVENT_KEY = 1;
18
+ const EVENT_MOUSE = 2;
19
+ const EVENT_FOCUS = 4;
20
+ const ACTION_PRESS = 1;
21
+ const ACTION_REPEAT = 2;
22
+ const ACTION_RELEASE = 3;
23
+ const ACTION_MOVE = 4;
24
+ const KEY_CHAR = 1;
25
+ const MOD_SHIFT = 1;
26
+ const MOD_ALT = 2;
27
+ const MOD_CTRL = 4;
28
+ const MOD_SUPER = 8;
29
+ const MOUSE_NONE = 0;
30
+ const MOUSE_BUTTONS = [1, 2, 3];
31
+
32
+ /** `KeyboardEvent.key` names with a `KEY_` kind of their own; any other one-character key is `KEY_CHAR`. */
33
+ const KEY_KINDS = {
34
+ ArrowUp: 2,
35
+ ArrowDown: 3,
36
+ ArrowRight: 4,
37
+ ArrowLeft: 5,
38
+ Enter: 6,
39
+ " ": 7,
40
+ Escape: 8,
41
+ Tab: 10,
42
+ Backspace: 11,
43
+ Home: 26,
44
+ End: 27,
45
+ PageUp: 28,
46
+ PageDown: 29,
47
+ Insert: 30,
48
+ Delete: 31,
49
+ };
50
+ for (let f = 1; f <= 12; f++) {
51
+ KEY_KINDS[`F${f}`] = 13 + f;
52
+ }
53
+
54
+ /** The words of one GAME_INPUT record (`GAME_EVENT_WORDS`). */
55
+ const EVENT_WORDS = 7;
56
+ /** The storage `nish/host/game` declares, which the module's `layout` must name. */
57
+ const STORAGE = ["GAME_FRAME", "GAME_INFO", "GAME_INPUT", "GAME_SOUNDS", "GAME_SAMPLES"];
58
+ /** The most sound ids `startGame` asks the game for. */
59
+ const SOUND_IDS = 64;
60
+ /** A touch held no longer than this, and moved no further, is a tap. */
61
+ const TAP_MS = 250;
62
+ const TAP_CSS_PX = 12;
63
+
64
+ /** The keys a game reads unless `keys` says otherwise. */
65
+ export const DEFAULT_KEYS = Object.freeze(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", " ", "Enter", "Escape"]);
66
+
67
+ /** Touch zones unless `touch` says otherwise: each half of the canvas steers, and a tap confirms. */
68
+ export const DEFAULT_TOUCH = Object.freeze({
69
+ zones: Object.freeze([
70
+ Object.freeze({ x: 0, y: 0, width: 0.5, height: 1, key: "ArrowLeft" }),
71
+ Object.freeze({ x: 0.5, y: 0, width: 0.5, height: 1, key: "ArrowRight" }),
72
+ ]),
73
+ tap: "Enter",
74
+ });
75
+
76
+ /** A one-character key compares without case, so Shift+A releases the A pressed. */
77
+ const keyName = (key) => (typeof key === "string" && key.length === 1 ? key.toLowerCase() : key);
78
+
79
+ /** `[kind, code point]` for a `KeyboardEvent.key`, or null for one the game cannot read. */
80
+ const keyWords = (key) => {
81
+ const kind = KEY_KINDS[key];
82
+ if (kind !== undefined) {
83
+ return [kind, 0];
84
+ }
85
+ const cp = typeof key === "string" ? key.codePointAt(0) : undefined;
86
+ return cp !== undefined && String.fromCodePoint(cp) === key ? [KEY_CHAR, cp] : null;
87
+ };
88
+
89
+ const modifiers = (e) =>
90
+ (e.shiftKey ? MOD_SHIFT : 0) | (e.altKey ? MOD_ALT : 0) | (e.ctrlKey ? MOD_CTRL : 0) | (e.metaKey ? MOD_SUPER : 0);
91
+
92
+ /** The error an aborted start rejects with: the signal's reason, or an AbortError. */
93
+ const aborted = (signal) =>
94
+ signal.reason ??
95
+ (typeof globalThis.DOMException === "function"
96
+ ? new globalThis.DOMException("nish/page/game: the start was aborted", "AbortError")
97
+ : new Error("nish/page/game: the start was aborted"));
98
+
99
+ /** Throws a TypeError naming `what` unless `ok`. */
100
+ const expect = (ok, what) => {
101
+ if (!ok) {
102
+ throw new TypeError(`nish/page/game: ${what}`);
103
+ }
104
+ };
105
+
106
+ /** Checks every option before `startGame` does anything, so a bad one costs nothing to undo. */
107
+ const validate = (url, options) => {
108
+ expect(options !== null && typeof options === "object", "options is an object");
109
+ const { keys, touch, stepsPerSecond, maxStepsPerFrame } = options;
110
+ expect(keys === undefined || (Array.isArray(keys) && keys.every((k) => typeof k === "string")), "keys is an array of KeyboardEvent.key names");
111
+ if (touch !== undefined && touch !== false) {
112
+ expect(touch !== null && typeof touch === "object" && Array.isArray(touch.zones), "touch is false or { zones, tap }");
113
+ for (const z of touch.zones) {
114
+ expect(
115
+ [z?.x, z?.y, z?.width, z?.height].every(Number.isFinite) && typeof z.key === "string",
116
+ "each touch zone is { x, y, width, height, key }"
117
+ );
118
+ }
119
+ expect(touch.tap === undefined || touch.tap === null || typeof touch.tap === "string", "touch.tap is a key name");
120
+ }
121
+ expect(
122
+ stepsPerSecond === undefined || (Number.isFinite(stepsPerSecond) && stepsPerSecond > 0),
123
+ `stepsPerSecond is a positive number, not ${stepsPerSecond}`
124
+ );
125
+ expect(
126
+ maxStepsPerFrame === undefined || (Number.isInteger(maxStepsPerFrame) && maxStepsPerFrame >= 1),
127
+ `maxStepsPerFrame is a whole number of at least 1, not ${maxStepsPerFrame}`
128
+ );
129
+ for (const name of ["onError", "onFallback"]) {
130
+ expect(options[name] === undefined || typeof options[name] === "function", `${name} is a function`);
131
+ }
132
+ expect(
133
+ options.seed === undefined || (Number.isInteger(options.seed) && Math.abs(options.seed) <= 0x7fffffff),
134
+ `seed is a whole number that fits in an i32, not ${options.seed}`
135
+ );
136
+ expect(
137
+ options.sound === undefined ||
138
+ options.sound === false ||
139
+ (options.sound !== null &&
140
+ typeof options.sound === "object" &&
141
+ (options.sound.muted === undefined || typeof options.sound.muted === "boolean")),
142
+ "sound is false or { muted }"
143
+ );
144
+ expect(
145
+ options.prefer === undefined || ["webgpu", "webgl2", "canvas2d"].includes(options.prefer),
146
+ `prefer is "webgpu", "webgl2" or "canvas2d", not ${JSON.stringify(options.prefer)}`
147
+ );
148
+ expect(
149
+ options.signal === undefined || typeof options.signal?.addEventListener === "function",
150
+ "signal is an AbortSignal"
151
+ );
152
+ expect(
153
+ options.loader !== undefined || options.loaderUrl !== undefined || /\.wasm$/.test(url.pathname),
154
+ `${url.href} does not end in .wasm, so its loader cannot be found beside it; pass options.loader or options.loaderUrl`
155
+ );
156
+ };
157
+
158
+ /** A rejection naming the module's missing part. */
159
+ const missing = (what) => new TypeError(`nish/page/game: the module has no ${what}, which a game over nish/host/game exports`);
160
+
161
+ /**
162
+ * Compiles the module at `url` in the background: `compileStreaming` as the
163
+ * bytes arrive, or, when the server's MIME type is not `application/wasm`,
164
+ * `compile` over the whole body.
165
+ */
166
+ const compileFrom = async (url, signal) => {
167
+ let response;
168
+ try {
169
+ response = await globalThis.fetch(url, signal === undefined ? undefined : { signal });
170
+ } catch (e) {
171
+ if (signal?.aborted) {
172
+ throw aborted(signal);
173
+ }
174
+ throw new Error(`nish/page/game: could not fetch ${url}: ${e instanceof Error ? e.message : String(e)}`);
175
+ }
176
+ if (!response.ok) {
177
+ throw new Error(`nish/page/game: fetching ${url} answered ${response.status} ${response.statusText || ""}`.trim());
178
+ }
179
+ if (typeof WebAssembly.compileStreaming === "function") {
180
+ try {
181
+ return await WebAssembly.compileStreaming(response.clone());
182
+ } catch (e) {
183
+ // A TypeError is the response refused (the MIME type); a CompileError is the bytes.
184
+ if (!(e instanceof TypeError)) {
185
+ throw e;
186
+ }
187
+ }
188
+ }
189
+ return WebAssembly.compile(await response.arrayBuffer());
190
+ };
191
+
192
+ /** The URL `wasmUrl` names, read against the page. */
193
+ const resolve = (wasmUrl) => {
194
+ const base = globalThis.document?.baseURI ?? globalThis.location?.href;
195
+ return base === undefined ? new URL(String(wasmUrl)) : new URL(String(wasmUrl), base);
196
+ };
197
+
198
+ /**
199
+ * Loads a game built over `nish/host/game` and runs it on `canvas`.
200
+ *
201
+ * The module at `wasmUrl` is compiled with `WebAssembly.compileStreaming` and
202
+ * instantiated by its generated loader: `options.loader`, the module at
203
+ * `options.loaderUrl`, or the `.mjs` beside the `.wasm` (`game.wasm` →
204
+ * `game.mjs`). It must export
205
+ * `init(seed)`, `step(nowMs)` and `draw(alpha, frameMs)` and keep
206
+ * `nish/host/game`'s storage; `sound(id)` and `resize(width, height)` are
207
+ * optional. `init` runs once; `sound` runs for ids 0, 1, ... until it answers
208
+ * 0, and each answer's samples become an `AudioBuffer`; then `step` runs
209
+ * `stepsPerSecond` times a second and `draw` once per display frame, after
210
+ * which `GAME_FRAME` is presented in place at `GAME_INFO`'s width and height.
211
+ * A throw from the module (a panic) or from presenting its frame stops the
212
+ * game, as `stop()` does, and reaches `options.onError`.
213
+ *
214
+ * @param canvas - the canvas to draw on; a fallback may replace it, see `presenter.canvas`
215
+ * @param wasmUrl - the module's URL, read against the page's base URL
216
+ * @param options - the seed, the keys and touch zones the game reads, the sound, the tier, the loader
217
+ * @returns the running game, once the module is loaded and its first frame is scheduled
218
+ */
219
+ export const startGame = async (canvas, wasmUrl, options = {}) => {
220
+ const url = resolve(wasmUrl);
221
+ validate(url, options);
222
+ const keys = new Set((options.keys ?? DEFAULT_KEYS).map(keyName));
223
+ const touch = options.touch === false ? null : (options.touch ?? DEFAULT_TOUCH);
224
+ const stepsPerSecond = options.stepsPerSecond ?? 60;
225
+ const soundOn = options.sound !== false;
226
+ const signal = options.signal;
227
+ let muted = options.sound?.muted === true;
228
+ const checkAbort = () => {
229
+ if (signal?.aborted) {
230
+ throw aborted(signal);
231
+ }
232
+ };
233
+ checkAbort();
234
+
235
+ const loaderHref =
236
+ options.loaderUrl === undefined ? url.href.replace(/\.wasm(?=$|[?#])/, ".mjs") : resolve(options.loaderUrl).href;
237
+ const [loader, compiled] = await Promise.all([
238
+ options.loader ?? import(loaderHref),
239
+ compileFrom(url.href, signal),
240
+ ]);
241
+ checkAbort();
242
+ if (typeof loader?.load !== "function") {
243
+ throw new TypeError("nish/page/game: the loader has no load(source) export; pass the module's generated .mjs as options.loader");
244
+ }
245
+ const game = await loader.load(compiled, options.imports);
246
+ checkAbort();
247
+ for (const name of ["init", "step", "draw"]) {
248
+ if (typeof game[name] !== "function") {
249
+ throw missing(`export \`${name}\``);
250
+ }
251
+ }
252
+ for (const name of STORAGE) {
253
+ if (game.layout?.[name] === undefined) {
254
+ throw missing(`storage \`${name}\``);
255
+ }
256
+ }
257
+ const input = ringOver(game.memory, game.layout.GAME_INPUT);
258
+ const queue = ringOver(game.memory, game.layout.GAME_SOUNDS);
259
+ const storage = () => game.views().storage;
260
+
261
+ game.init(options.seed ?? (Date.now() & 0x7fffffff));
262
+
263
+ // The samples are copied out once, at start: GAME_SAMPLES holds one sound at a time.
264
+ const sounds = [];
265
+ if (soundOn && typeof game.sound === "function") {
266
+ for (let id = 0; id < SOUND_IDS; id++) {
267
+ const n = game.sound(id);
268
+ if (!(n > 0)) {
269
+ break;
270
+ }
271
+ const s = storage();
272
+ sounds.push({ rate: s.GAME_INFO[3], samples: s.GAME_SAMPLES.slice(0, n) });
273
+ }
274
+ }
275
+
276
+ // ---- input --------------------------------------------------------------
277
+
278
+ let running = false;
279
+ // The keys the game has seen pressed, and the releases a full ring refused,
280
+ // retried before each step: the game sees every press it is told of released.
281
+ const held = new Map();
282
+ const unreleased = new Map();
283
+ const touches = new Map();
284
+ const buttons = new Map();
285
+ let pendingMove = null;
286
+
287
+ const push = (type, what, code, mods, action, x, y) => {
288
+ if (input.free() < EVENT_WORDS) {
289
+ return false;
290
+ }
291
+ for (const word of [type, what, code, mods, action, x, y]) {
292
+ input.push(word);
293
+ }
294
+ return true;
295
+ };
296
+ const pressKey = (id, name, mods, repeat) => {
297
+ const words = keyWords(name);
298
+ if (words === null) {
299
+ return;
300
+ }
301
+ // A key whose release is still queued is down as far as the game knows.
302
+ const again = held.has(id) || unreleased.delete(id);
303
+ if (push(EVENT_KEY, words[0], words[1], mods, again || repeat ? ACTION_REPEAT : ACTION_PRESS, 0, 0) || again) {
304
+ held.set(id, words);
305
+ }
306
+ };
307
+ const releaseKey = (id, mods) => {
308
+ const words = held.get(id);
309
+ if (words !== undefined) {
310
+ held.delete(id);
311
+ if (!push(EVENT_KEY, words[0], words[1], mods, ACTION_RELEASE, 0, 0)) {
312
+ unreleased.set(id, words);
313
+ }
314
+ }
315
+ };
316
+ const flushReleases = () => {
317
+ for (const [id, words] of unreleased) {
318
+ if (!push(EVENT_KEY, words[0], words[1], 0, ACTION_RELEASE, 0, 0)) {
319
+ return;
320
+ }
321
+ unreleased.delete(id);
322
+ }
323
+ };
324
+ const pressButton = (e) => {
325
+ const [x, y] = framePoint(e);
326
+ pendingMove = null;
327
+ const button = MOUSE_BUTTONS[e.button] ?? MOUSE_NONE;
328
+ if (push(EVENT_MOUSE, button, 0, modifiers(e), ACTION_PRESS, x, y)) {
329
+ buttons.set(e.button, [x, y]);
330
+ }
331
+ };
332
+ const releaseButton = (index, mods, x, y) => {
333
+ if (buttons.delete(index)) {
334
+ push(EVENT_MOUSE, MOUSE_BUTTONS[index] ?? MOUSE_NONE, 0, mods, ACTION_RELEASE, x, y);
335
+ }
336
+ };
337
+ const releaseButtons = () => {
338
+ for (const [index, [x, y]] of [...buttons]) {
339
+ releaseButton(index, 0, x, y);
340
+ }
341
+ };
342
+ const releaseAll = () => {
343
+ for (const id of [...held.keys()]) {
344
+ releaseKey(id, 0);
345
+ }
346
+ releaseButtons();
347
+ touches.clear();
348
+ };
349
+
350
+ /** The frame pixel under a pointer, through the presenter's letterbox. */
351
+ const framePoint = (e) => {
352
+ const box = presenter.canvas.getBoundingClientRect();
353
+ const info = storage().GAME_INFO;
354
+ const w = info[0];
355
+ const h = info[1];
356
+ if (!(w > 0 && h > 0 && box.width > 0 && box.height > 0)) {
357
+ return [0, 0];
358
+ }
359
+ const scale = Math.min(box.width / w, box.height / h);
360
+ const fx = Math.floor((e.clientX - box.left - (box.width - w * scale) / 2) / scale);
361
+ const fy = Math.floor((e.clientY - box.top - (box.height - h * scale) / 2) / scale);
362
+ return [Math.min(Math.max(fx, 0), w - 1), Math.min(Math.max(fy, 0), h - 1)];
363
+ };
364
+ const zoneAt = (e) => {
365
+ const box = presenter.canvas.getBoundingClientRect();
366
+ const u = (e.clientX - box.left) / box.width;
367
+ const v = (e.clientY - box.top) / box.height;
368
+ return touch.zones.find((z) => u >= z.x && u < z.x + z.width && v >= z.y && v < z.y + z.height);
369
+ };
370
+
371
+ // ---- sound --------------------------------------------------------------
372
+
373
+ // The context is made on the first gesture and resumed on every later one
374
+ // until it runs: a browser starts it suspended unless the gesture activates
375
+ // the page (a click, a key, a touch's end), and a pointerdown on a phone does not.
376
+ let audio = null;
377
+ let buffers = [];
378
+ const unlock = () => {
379
+ if (!running || !soundOn || sounds.length === 0) {
380
+ return;
381
+ }
382
+ if (audio === null) {
383
+ const Context = globalThis.AudioContext ?? globalThis.webkitAudioContext;
384
+ if (typeof Context !== "function") {
385
+ return;
386
+ }
387
+ let context = null;
388
+ try {
389
+ context = new Context();
390
+ // A sound the browser refuses (a rate it cannot play) is skipped, not the rest.
391
+ buffers = sounds.map(({ rate, samples }) => {
392
+ try {
393
+ const buffer = context.createBuffer(1, samples.length, rate);
394
+ buffer.copyToChannel(samples, 0);
395
+ return buffer;
396
+ } catch {
397
+ return undefined;
398
+ }
399
+ });
400
+ } catch {
401
+ // No context this time; the next gesture tries again.
402
+ buffers = [];
403
+ Promise.resolve(context?.close?.()).catch(() => {});
404
+ return;
405
+ }
406
+ audio = context;
407
+ }
408
+ if (audio.state !== "running") {
409
+ try {
410
+ Promise.resolve(audio.resume?.()).catch(() => {});
411
+ } catch {
412
+ // A resume refused now is tried again on the next gesture.
413
+ }
414
+ }
415
+ };
416
+ const play = (id) => {
417
+ const buffer = buffers[id];
418
+ if (audio === null || muted || buffer === undefined || audio.state === "closed") {
419
+ return;
420
+ }
421
+ const source = audio.createBufferSource();
422
+ source.buffer = buffer;
423
+ source.connect(audio.destination);
424
+ source.start();
425
+ };
426
+
427
+ // ---- listeners ----------------------------------------------------------
428
+
429
+ /** Ctrl, Alt and Meta make a key the browser's (Ctrl+Enter, Alt+Arrow, Cmd+Arrow), not the game's. */
430
+ const shortcut = (e) => e.ctrlKey === true || e.altKey === true || e.metaKey === true;
431
+ const onKeyDown = (e) => {
432
+ const name = keyName(e.key);
433
+ if (!running) {
434
+ return;
435
+ }
436
+ if (name !== "Escape") {
437
+ unlock();
438
+ }
439
+ if (!keys.has(name) || shortcut(e)) {
440
+ return;
441
+ }
442
+ e.preventDefault();
443
+ pressKey(e.code || name, name, modifiers(e), e.repeat === true);
444
+ };
445
+ const onKeyUp = (e) => {
446
+ const name = keyName(e.key);
447
+ const id = e.code || name;
448
+ if (!running || !held.has(id)) {
449
+ return;
450
+ }
451
+ e.preventDefault();
452
+ releaseKey(id, modifiers(e));
453
+ };
454
+ const onGesture = () => unlock();
455
+ const onPointerDown = (e) => {
456
+ if (!running) {
457
+ return;
458
+ }
459
+ unlock();
460
+ presenter.canvas.focus?.({ preventScroll: true });
461
+ if (e.pointerType === "touch") {
462
+ if (touch === null) {
463
+ return;
464
+ }
465
+ e.preventDefault();
466
+ const zone = zoneAt(e);
467
+ const id = `touch:${e.pointerId}`;
468
+ touches.set(e.pointerId, { at: e.timeStamp, x: e.clientX, y: e.clientY, id });
469
+ if (zone !== undefined) {
470
+ pressKey(id, zone.key, 0, false);
471
+ }
472
+ return;
473
+ }
474
+ // Captured, so a release off the canvas still reaches it.
475
+ try {
476
+ presenter.canvas.setPointerCapture?.(e.pointerId);
477
+ } catch {
478
+ // A pointer the browser no longer tracks; its release comes as a cancel.
479
+ }
480
+ pressButton(e);
481
+ };
482
+ const onPointerUp = (e) => {
483
+ if (!running) {
484
+ return;
485
+ }
486
+ if (e.type === "pointerup") {
487
+ unlock();
488
+ }
489
+ if (e.pointerType === "touch") {
490
+ const t = touches.get(e.pointerId);
491
+ if (t === undefined) {
492
+ return;
493
+ }
494
+ touches.delete(e.pointerId);
495
+ releaseKey(t.id, 0);
496
+ const still = Math.hypot(e.clientX - t.x, e.clientY - t.y) <= TAP_CSS_PX;
497
+ if (e.type === "pointerup" && touch.tap && still && e.timeStamp - t.at <= TAP_MS) {
498
+ pressKey("tap", touch.tap, 0, false);
499
+ releaseKey("tap", 0);
500
+ }
501
+ return;
502
+ }
503
+ const [x, y] = framePoint(e);
504
+ releaseButton(e.button, modifiers(e), x, y);
505
+ };
506
+ // A cancel's or a context menu's button is 0 or -1, not the one held, and no
507
+ // release follows either: every held button is let go where it was pressed.
508
+ const onPointerCancel = (e) => {
509
+ if (e.pointerType === "touch") {
510
+ onPointerUp(e);
511
+ } else if (running) {
512
+ releaseButtons();
513
+ }
514
+ };
515
+ const onContextMenu = () => {
516
+ if (running) {
517
+ releaseButtons();
518
+ }
519
+ };
520
+ const onPointerMove = (e) => {
521
+ if (running && e.pointerType !== "touch") {
522
+ // Moves are coalesced: the step reads where the pointer is, not every place it passed.
523
+ pendingMove = [...framePoint(e), modifiers(e)];
524
+ }
525
+ };
526
+ const onBlur = () => {
527
+ if (running) {
528
+ releaseAll();
529
+ push(EVENT_FOCUS, 0, 0, 0, 0, 0, 0);
530
+ }
531
+ };
532
+ const onFocus = () => {
533
+ if (running) {
534
+ push(EVENT_FOCUS, 1, 0, 0, 0, 0, 0);
535
+ }
536
+ };
537
+ const onVisibility = () => {
538
+ // Hidden is a blur; shown again, the game hears its focus back if the canvas kept it.
539
+ if (globalThis.document?.visibilityState === "hidden") {
540
+ onBlur();
541
+ } else if (globalThis.document?.activeElement === presenter.canvas) {
542
+ onFocus();
543
+ }
544
+ };
545
+ const onWindowResize = () => fit();
546
+
547
+ // A devicePixelRatio change with no CSS resize (a zoom, a move to another
548
+ // display) is heard through a media query for the ratio it was.
549
+ let ratioQuery = null;
550
+ const onRatio = () => {
551
+ watchRatio();
552
+ fit();
553
+ };
554
+ const watchRatio = () => {
555
+ ratioQuery?.removeEventListener?.("change", onRatio);
556
+ ratioQuery = null;
557
+ if (running && typeof globalThis.matchMedia === "function") {
558
+ ratioQuery = globalThis.matchMedia(`(resolution: ${globalThis.devicePixelRatio || 1}dppx)`);
559
+ ratioQuery?.addEventListener?.("change", onRatio);
560
+ }
561
+ };
562
+
563
+ const canvasListeners = [
564
+ ["keydown", onKeyDown],
565
+ ["keyup", onKeyUp],
566
+ ["pointerdown", onPointerDown],
567
+ ["pointerup", onPointerUp],
568
+ ["pointercancel", onPointerCancel],
569
+ ["contextmenu", onContextMenu],
570
+ ["pointermove", onPointerMove],
571
+ ["click", onGesture],
572
+ ["touchend", onGesture],
573
+ ["blur", onBlur],
574
+ ["focus", onFocus],
575
+ ];
576
+ let bound = null;
577
+ let observer = null;
578
+ const bind = (target) => {
579
+ if (bound !== null) {
580
+ for (const [type, listener] of canvasListeners) {
581
+ bound.removeEventListener(type, listener);
582
+ }
583
+ observer?.disconnect();
584
+ }
585
+ bound = target;
586
+ if (target === null) {
587
+ return;
588
+ }
589
+ for (const [type, listener] of canvasListeners) {
590
+ target.addEventListener(type, listener);
591
+ }
592
+ if (!target.hasAttribute?.("tabindex")) {
593
+ target.setAttribute?.("tabindex", "0");
594
+ }
595
+ if (target.style !== undefined && touch !== null) {
596
+ target.style.touchAction = "none";
597
+ }
598
+ if (typeof globalThis.ResizeObserver === "function") {
599
+ observer = new globalThis.ResizeObserver(() => fit());
600
+ observer.observe(target);
601
+ }
602
+ };
603
+
604
+ // ---- presenter and loop -------------------------------------------------
605
+
606
+ let presenter = null;
607
+ let loop = null;
608
+ let stopped = false;
609
+ const teardown = () => {
610
+ if (stopped) {
611
+ return;
612
+ }
613
+ stopped = true;
614
+ running = false;
615
+ loop?.stop();
616
+ bind(null);
617
+ observer?.disconnect();
618
+ ratioQuery?.removeEventListener?.("change", onRatio);
619
+ ratioQuery = null;
620
+ globalThis.document?.removeEventListener?.("visibilitychange", onVisibility);
621
+ globalThis.removeEventListener?.("resize", onWindowResize);
622
+ signal?.removeEventListener?.("abort", teardown);
623
+ held.clear();
624
+ unreleased.clear();
625
+ touches.clear();
626
+ buttons.clear();
627
+ if (audio !== null) {
628
+ Promise.resolve(audio.close?.()).catch(() => {});
629
+ audio = null;
630
+ }
631
+ presenter?.destroy();
632
+ };
633
+ /** Stops the game on a throw from the module or the presenter, and reports it. */
634
+ const fail = (error) => {
635
+ teardown();
636
+ if (options.onError === undefined) {
637
+ throw error;
638
+ }
639
+ options.onError(error);
640
+ };
641
+
642
+ presenter = await createPresenter(canvas, {
643
+ prefer: options.prefer,
644
+ onFallback: (from, to, reason, fresh) => {
645
+ // A fallback hands over a fresh canvas: the listeners move to it.
646
+ if (bound !== null && fresh !== bound) {
647
+ bind(fresh);
648
+ fit();
649
+ fresh.focus?.({ preventScroll: true });
650
+ }
651
+ options.onFallback?.(from, to, reason, fresh);
652
+ },
653
+ });
654
+ if (signal?.aborted) {
655
+ presenter.destroy();
656
+ throw aborted(signal);
657
+ }
658
+
659
+ const fit = () => {
660
+ const box = presenter.canvas.getBoundingClientRect();
661
+ presenter.resize(box.width, box.height, globalThis.devicePixelRatio || 1);
662
+ if (typeof game.resize === "function") {
663
+ game.resize(Math.round(box.width), Math.round(box.height));
664
+ }
665
+ };
666
+
667
+ let steps = 0;
668
+ try {
669
+ running = true;
670
+ bind(presenter.canvas);
671
+ globalThis.document?.addEventListener?.("visibilitychange", onVisibility);
672
+ globalThis.addEventListener?.("resize", onWindowResize);
673
+ signal?.addEventListener?.("abort", teardown);
674
+ watchRatio();
675
+ fit();
676
+ presenter.canvas.focus?.({ preventScroll: true });
677
+
678
+ loop = runFixedStep({
679
+ stepsPerSecond,
680
+ maxStepsPerFrame: options.maxStepsPerFrame,
681
+ step: () => {
682
+ try {
683
+ flushReleases();
684
+ if (pendingMove !== null) {
685
+ const [x, y, mods] = pendingMove;
686
+ pendingMove = null;
687
+ push(EVENT_MOUSE, MOUSE_NONE, 0, mods, ACTION_MOVE, x, y);
688
+ }
689
+ game.step((steps * 1000) / stepsPerSecond);
690
+ steps++;
691
+ while (queue.size() > 0) {
692
+ play(queue.shift());
693
+ }
694
+ } catch (e) {
695
+ fail(e);
696
+ }
697
+ },
698
+ render: (alpha, frameMs) => {
699
+ try {
700
+ game.draw(alpha, frameMs);
701
+ // views() after the call: a memory that grew has a new buffer.
702
+ const s = storage();
703
+ const w = s.GAME_INFO[0];
704
+ const h = s.GAME_INFO[1];
705
+ if (w > 0 && h > 0) {
706
+ presenter.present(s.GAME_FRAME, w, h);
707
+ }
708
+ } catch (e) {
709
+ fail(e);
710
+ }
711
+ },
712
+ });
713
+ } catch (e) {
714
+ teardown();
715
+ throw e;
716
+ }
717
+
718
+ return {
719
+ presenter,
720
+ module: game,
721
+ get fps() {
722
+ return loop.fps;
723
+ },
724
+ get refreshHz() {
725
+ return loop.refreshHz;
726
+ },
727
+ get muted() {
728
+ return muted;
729
+ },
730
+ set muted(value) {
731
+ muted = value === true;
732
+ },
733
+ get running() {
734
+ return running;
735
+ },
736
+ stop: teardown,
737
+ };
738
+ };