sepal 0.1.0-alpha.1 → 0.2.0-alpha.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.
package/README.md CHANGED
@@ -9,7 +9,7 @@ a Rust HTML/CSS engine; the JavaScript runs in an embedded QuickJS.
9
9
 
10
10
  An alpha, on macOS (Linux builds and passes its tests headless; its window has
11
11
  not been tried yet). Svelte 5 and Tailwind v4 as on the web, pages as files
12
- (Sepal's router or SvelteKit's), shadcn-svelte components through an opt-in
12
+ run by SvelteKit's router, shadcn-svelte components through an opt-in
13
13
  DOM layer, desktop APIs behind permissions, macOS `.app` bundles and
14
14
  self-update, and no frame loop: an idle app does no work.
15
15
 
@@ -24,7 +24,7 @@ runs; [how they were measured](https://github.com/etherCorps/sepal/blob/main/com
24
24
  | Idle memory, 1,000 issues | 107 MB RAM, 43 MB GPU memory |
25
25
  | Memory after wheel-scrolling the whole list, 1,000 issues | 305 MB RAM, 220 MB GPU memory |
26
26
 
27
- This one package is the runtime, the Vite preset and the `sepal` command; the
27
+ This one package is the runtime, the Vite presets and the `sepal` command; the
28
28
  prebuilt host comes with it. Start a project with the starter rather than by
29
29
  installing it directly:
30
30
 
@@ -41,10 +41,8 @@ What is in here:
41
41
  | `sepal/updater` | self-update |
42
42
  | `sepal/dom` | a small DOM for component libraries written for the web (`dom: true`) |
43
43
  | `sepal/renderer`, `sepal/protocol` | what the Vite preset and the host are built against |
44
- | `sepal/vite` | the Vite preset, `sepal()`, and `defineConfig` for `sepal.config.ts` |
45
- | `sepal/sveltekit` | `sepalKit()`, which takes the place of both `sveltekit()` and the adapter |
46
- | `sepal/router`, `sepal/navigation`, `sepal/state` | the file-based router (`src/routes`, `$app/navigation`, `$app/state`) |
47
- | `sepal/ambient` | types for `$app/*`; add it to `types` in tsconfig.json |
44
+ | `sepal/vite` | the Vite preset for apps without routes, `sepal()`, and `defineConfig` for `sepal.config.ts` |
45
+ | `sepal/sveltekit` | `sepalKit()`, for apps with pages in `src/routes`: it takes the place of both `sveltekit()` and the adapter |
48
46
 
49
47
  The preset compiles Svelte for the Blitz renderer, writes the one `app.js` and
50
48
  `app.css` the host loads, reads `sepal.config.ts`, and in `vite build --watch`
package/cli.js CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { spawnSync } from 'node:child_process';
6
6
  import { readFileSync } from 'node:fs';
7
+ import { basename, join, resolve } from 'node:path';
7
8
  import { find_host, platform_package } from '@ethercorps/calyx';
8
9
 
9
10
  const own = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
@@ -26,8 +27,8 @@ function fail(message) {
26
27
  process.exit(1);
27
28
  }
28
29
 
29
- /** Run the host with these arguments and exit with its status. @param {string[]} args @returns {never} */
30
- function host(args) {
30
+ /** This machine's calyx, once its version is known to fit. @returns {string} */
31
+ function calyx() {
31
32
  /** @type {ReturnType<typeof find_host>} */
32
33
  let found;
33
34
  try {
@@ -45,18 +46,53 @@ function host(args) {
45
46
  'again). To run a different calyx on purpose, point SEPAL_HOST at it.'
46
47
  );
47
48
  }
48
- const { status, error } = spawnSync(found.path, args, { stdio: 'inherit' });
49
- if (error) fail(`sepal: cannot start ${found.path}: ${error.message}`);
49
+ return found.path;
50
+ }
51
+
52
+ /** Run a binary with these arguments and exit with its status. @param {string} bin @param {string[]} args @returns {never} */
53
+ function start(bin, args) {
54
+ const { status, error } = spawnSync(bin, args, { stdio: 'inherit' });
55
+ if (error) fail(`sepal: cannot start ${bin}: ${error.message}`);
50
56
  process.exit(status ?? 1);
51
57
  }
52
58
 
59
+ /** Run the host with these arguments and exit with its status. @param {string[]} args @returns {never} */
60
+ function host(args) {
61
+ start(calyx(), args);
62
+ }
63
+
64
+ /**
65
+ * macOS takes the name in the Dock, the app switcher and Activity Monitor
66
+ * from the bundle a process runs from; a bare calyx is called "calyx". So on
67
+ * macOS an app with a name runs out of a throwaway bundle in
68
+ * node_modules/.sepal, as it does in dev, and still loads from `dir`.
69
+ * @param {string} bin @param {string} dir
70
+ */
71
+ function bundled(bin, dir) {
72
+ if (process.platform !== 'darwin') return bin;
73
+ let name;
74
+ try {
75
+ name = JSON.parse(readFileSync(join(dir, 'app.json'), 'utf8')).name;
76
+ } catch {
77
+ return bin;
78
+ }
79
+ if (!name) return bin;
80
+ const made = spawnSync(bin, ['--bundle', dir, resolve('node_modules/.sepal')], { encoding: 'utf8' });
81
+ if (made.status !== 0) {
82
+ console.warn(`sepal: running unbundled: ${made.stderr.trim()}`);
83
+ return bin;
84
+ }
85
+ const bundle = made.stdout.trim();
86
+ return join(bundle, 'Contents/MacOS', basename(bundle, '.app'));
87
+ }
88
+
53
89
  const [command, ...args] = process.argv.slice(2);
54
90
  // `bundle --sign x` with no directory still means `dist`.
55
91
  const dist = args[0] !== undefined && !args[0].startsWith('--') ? args : ['dist', ...args];
56
92
 
57
93
  switch (command) {
58
94
  case 'run':
59
- host(dist);
95
+ start(bundled(calyx(), dist[0]), dist);
60
96
  case 'bundle':
61
97
  host(['--bundle', ...dist]);
62
98
  case 'signer':
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sepal",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.2.0-alpha.0",
4
4
  "description": "Native Svelte apps, drawn by Blitz: a Svelte custom renderer for the Blitz HTML/CSS engine, its Vite preset and the sepal command",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -22,7 +22,6 @@
22
22
  "gui",
23
23
  "vite",
24
24
  "vite-plugin",
25
- "router",
26
25
  "svelte-blitz"
27
26
  ],
28
27
  "type": "module",
@@ -77,32 +76,16 @@
77
76
  "./sveltekit": {
78
77
  "types": "./types/vite/sveltekit.d.ts",
79
78
  "default": "./vite/sveltekit.js"
80
- },
81
- "./router": {
82
- "types": "./types/vite/router.d.ts",
83
- "default": "./vite/router.js"
84
- },
85
- "./navigation": {
86
- "types": "./types/vite/navigation.d.ts",
87
- "default": "./vite/navigation.js"
88
- },
89
- "./state": {
90
- "types": "./types/vite/state.d.ts",
91
- "default": "./vite/state.js"
92
- },
93
- "./ambient": {
94
- "types": "./ambient.d.ts"
95
79
  }
96
80
  },
97
81
  "files": [
98
82
  "src",
99
83
  "vite",
100
84
  "types",
101
- "ambient.d.ts",
102
85
  "cli.js"
103
86
  ],
104
87
  "dependencies": {
105
- "@ethercorps/calyx": "0.1.0-alpha.1"
88
+ "@ethercorps/calyx": "0.2.0-alpha.0"
106
89
  },
107
90
  "peerDependencies": {
108
91
  "svelte": "^5.59.0",
@@ -124,6 +107,6 @@
124
107
  "vite": "^8.3.8"
125
108
  },
126
109
  "scripts": {
127
- "check": "tsc && tsc -p tsconfig.vite.json && tsc -p tsconfig.node.json"
110
+ "check": "tsc && tsc -p tsconfig.node.json"
128
111
  }
129
112
  }
package/src/fetch.js CHANGED
@@ -1,57 +1,143 @@
1
- // `fetch`, installed as a global when the engine has none.
1
+ // `fetch`, and the Fetch API classes around it (`Request`, `Headers`,
2
+ // `Response`), installed as globals when the engine has none.
2
3
  //
3
4
  // The host makes the request, and only to URLs the app's `permissions.http`
4
5
  // allows. This is the everyday part of the Fetch API: method, headers, a
5
6
  // string or byte body, and `text()`, `json()`, `arrayBuffer()`, `bytes()` on
6
- // the response. There is no streaming, no `AbortSignal`, and no `Request`,
7
- // `Headers` or `FormData` classes.
7
+ // the response. There is no streaming, no `AbortSignal` and no `FormData`.
8
+ // The classes are there because libraries test for them and build them:
9
+ // SvelteKit's client asks `input instanceof Request` on every fetch.
8
10
 
9
11
  import { host_call } from './host-call.js';
10
12
  import { decode, encode, to_bytes } from './base64.js';
11
13
 
12
- /** Response headers: names are case-insensitive, as in the Fetch API. */
13
- class ResponseHeaders {
14
- /** @param {[string, string][]} pairs */
15
- constructor(pairs) {
16
- /** @type {Map<string, string>} */
17
- this.values = new Map();
18
- for (const [name, value] of pairs) {
19
- const key = name.toLowerCase();
20
- const earlier = this.values.get(key);
21
- this.values.set(key, earlier === undefined ? value : `${earlier}, ${value}`);
22
- }
14
+ /** Headers: names are case-insensitive and kept in lower case, as in the Fetch API. */
15
+ export class Headers {
16
+ /** @type {Map<string, string>} */
17
+ #map = new Map();
18
+
19
+ /** @param {unknown} [init] a plain object, a list of pairs, or another `Headers` */
20
+ constructor(init) {
21
+ for (const [name, value] of header_pairs(init)) this.append(name, value);
22
+ }
23
+ /** @param {string} name @param {string} value */
24
+ append(name, value) {
25
+ const key = name.toLowerCase();
26
+ const earlier = this.#map.get(key);
27
+ this.#map.set(key, earlier === undefined ? String(value) : `${earlier}, ${value}`);
28
+ }
29
+ /** @param {string} name @param {string} value */
30
+ set(name, value) {
31
+ this.#map.set(name.toLowerCase(), String(value));
23
32
  }
24
33
  /** @param {string} name */
25
34
  get(name) {
26
- return this.values.get(name.toLowerCase()) ?? null;
35
+ return this.#map.get(name.toLowerCase()) ?? null;
27
36
  }
28
37
  /** @param {string} name */
29
38
  has(name) {
30
- return this.values.has(name.toLowerCase());
39
+ return this.#map.has(name.toLowerCase());
40
+ }
41
+ /** @param {string} name */
42
+ delete(name) {
43
+ this.#map.delete(name.toLowerCase());
31
44
  }
32
- /** @param {(value: string, name: string) => void} callback */
45
+ /** @param {(value: string, name: string, headers: Headers) => void} callback */
33
46
  forEach(callback) {
34
- this.values.forEach(callback);
47
+ this.#map.forEach((value, name) => callback(value, name, this));
35
48
  }
36
49
  entries() {
37
- return this.values.entries();
50
+ return this.#map.entries();
51
+ }
52
+ keys() {
53
+ return this.#map.keys();
54
+ }
55
+ values() {
56
+ return this.#map.values();
38
57
  }
39
58
  [Symbol.iterator]() {
40
- return this.values.entries();
59
+ return this.#map.entries();
60
+ }
61
+ }
62
+
63
+ const METHODS = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'PATCH'];
64
+
65
+ /** A request to make: what `fetch` takes, as a string, a URL or one of these. */
66
+ export class Request {
67
+ /**
68
+ * @param {string | Request | { url?: string, href?: string }} input
69
+ * @param {{ method?: string, headers?: unknown, body?: string | ArrayBuffer | ArrayBufferView | null }} [init]
70
+ */
71
+ constructor(input, init = {}) {
72
+ /** @type {Request | null} */
73
+ const from = input instanceof Request ? input : null;
74
+ const target = /** @type {any} */ (input);
75
+ /** @type {string} */
76
+ this.url = from ? from.url : typeof input === 'string' ? input : String(target?.url ?? target?.href ?? input);
77
+ /** @type {string} */
78
+ const method = init.method ?? from?.method ?? 'GET';
79
+ // As the Fetch API does: the standard methods in upper case, any other as written.
80
+ /** @type {string} */
81
+ this.method = METHODS.includes(method.toUpperCase()) ? method.toUpperCase() : method;
82
+ /** @type {Headers} */
83
+ this.headers = new Headers(init.headers ?? from?.headers);
84
+ /** @type {string | ArrayBuffer | ArrayBufferView | null} */
85
+ this.body = init.body ?? from?.body ?? null;
41
86
  }
42
87
  }
43
88
 
44
- class FetchResponse {
89
+ /** A response with its body in hand: what `new Response(body, init)` makes. `fetch` answers with a subclass. */
90
+ export class Response {
91
+ /**
92
+ * @param {string | ArrayBuffer | ArrayBufferView | null} [body]
93
+ * @param {{ status?: number, statusText?: string, headers?: unknown }} [init]
94
+ */
95
+ constructor(body = null, init = {}) {
96
+ this.status = init.status ?? 200;
97
+ this.statusText = init.statusText ?? '';
98
+ this.ok = this.status >= 200 && this.status < 300;
99
+ this.headers = new Headers(init.headers);
100
+ this.url = '';
101
+ this.redirected = false;
102
+ this.bodyUsed = false;
103
+ /** @type {string | Uint8Array | null} */
104
+ this.held = body == null || typeof body === 'string' ? body : to_bytes(body);
105
+ }
106
+
107
+ /** @returns {string | Uint8Array} */
108
+ take() {
109
+ if (this.bodyUsed) throw new TypeError('the response body was already read');
110
+ this.bodyUsed = true;
111
+ return this.held ?? '';
112
+ }
113
+
114
+ /** @returns {Promise<string>} */
115
+ async text() {
116
+ const body = this.take();
117
+ if (typeof body !== 'string') throw new TypeError('text() of a byte body is not supported; use bytes()');
118
+ return body;
119
+ }
120
+ async json() {
121
+ return JSON.parse(await this.text());
122
+ }
123
+ /** @returns {Promise<Uint8Array>} */
124
+ async bytes() {
125
+ const body = this.take();
126
+ if (typeof body === 'string') throw new TypeError('bytes() of a string body is not supported; use text()');
127
+ return body;
128
+ }
129
+ async arrayBuffer() {
130
+ return /** @type {ArrayBuffer} */ ((await this.bytes()).buffer);
131
+ }
132
+ }
133
+
134
+ /** What `fetch` answers with: the body stays with the host until it is asked for. */
135
+ class FetchResponse extends Response {
45
136
  /** @param {{ id: number, status: number, status_text: string, url: string, redirected: boolean, headers: [string, string][] }} head */
46
137
  constructor(head) {
47
- this.status = head.status;
48
- this.statusText = head.status_text;
49
- this.ok = head.status >= 200 && head.status < 300;
138
+ super(null, { status: head.status, statusText: head.status_text, headers: head.headers });
50
139
  this.url = head.url;
51
140
  this.redirected = head.redirected;
52
- this.headers = new ResponseHeaders(head.headers);
53
- this.bodyUsed = false;
54
- /** The body stays with the host until it is asked for. */
55
141
  this.body_id = head.id;
56
142
  }
57
143
 
@@ -65,15 +151,9 @@ class FetchResponse {
65
151
  text() {
66
152
  return this.read('text');
67
153
  }
68
- async json() {
69
- return JSON.parse(await this.read('text'));
70
- }
71
154
  async bytes() {
72
155
  return decode(await this.read('base64'));
73
156
  }
74
- async arrayBuffer() {
75
- return (await this.bytes()).buffer;
76
- }
77
157
  }
78
158
 
79
159
  /**
@@ -95,17 +175,15 @@ function header_pairs(headers) {
95
175
  }
96
176
 
97
177
  /**
98
- * @param {string | { url: string } | { href: string }} input
178
+ * @param {string | Request | { url?: string, href?: string }} input
99
179
  * @param {{ method?: string, headers?: unknown, body?: string | ArrayBuffer | ArrayBufferView | null }} [init]
100
- * @returns {Promise<FetchResponse>}
180
+ * @returns {Promise<Response>}
101
181
  */
102
182
  export async function fetch(input, init = {}) {
103
- const target = /** @type {any} */ (input);
104
- const url = typeof input === 'string' ? input : String(target.url ?? target.href ?? input);
183
+ const { url, method, headers, body } = new Request(input, init);
105
184
  /** @type {Record<string, unknown>} */
106
- const request = { url, method: init.method ?? 'GET', headers: header_pairs(init.headers) };
185
+ const request = { url, method, headers: [...headers] };
107
186
 
108
- const body = init.body;
109
187
  if (typeof body === 'string') request.body = body;
110
188
  else if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) request.body_base64 = encode(to_bytes(body));
111
189
  else if (body != null) throw new TypeError('fetch: the body must be a string, an ArrayBuffer or a typed array');
package/src/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // Shims must be evaluated before Svelte's runtime.
2
- import { run_timers, next_timer, track_rejection, report_rejections, rejection_count } from './shims.js';
2
+ import { run_timers, next_timer, run_frame, frame_pending, track_rejection, report_rejections, rejection_count } from './shims.js';
3
3
  import { mount as svelte_mount, unmount } from 'svelte';
4
4
  import renderer, { root, dispatch, take_batch, stats, keep_alive, host_hooks } from './renderer.js';
5
5
  import { settle_call } from './host-call.js';
6
- import { fetch } from './fetch.js';
6
+ import { fetch, Headers, Request, Response } from './fetch.js';
7
7
 
8
8
  /**
9
9
  * Mount a component into the window.
@@ -22,8 +22,11 @@ export function mount(component, options = {}) {
22
22
 
23
23
  export { unmount, renderer, root };
24
24
 
25
- // The engine has no `fetch`. This one asks the host, which checks the app's permissions.
26
- if (typeof (/** @type {any} */ (globalThis).fetch) !== 'function') /** @type {any} */ (globalThis).fetch = fetch;
25
+ // The engine has no `fetch`. This one asks the host, which checks the app's
26
+ // permissions. The classes around it come along: libraries test for them.
27
+ for (const [name, value] of Object.entries({ fetch, Headers, Request, Response })) {
28
+ if (typeof (/** @type {any} */ (globalThis)[name]) !== 'function') /** @type {any} */ (globalThis)[name] = value;
29
+ }
27
30
 
28
31
  // The host's entry points into JS. It calls these and nothing else.
29
32
  /** @type {any} */ (globalThis).__sb = {
@@ -35,6 +38,10 @@ if (typeof (/** @type {any} */ (globalThis).fetch) !== 'function') /** @type {an
35
38
  timers: run_timers,
36
39
  /** The next timer deadline on the host clock, or -1. Read at the end of a turn. */
37
40
  next_timer,
41
+ /** Run one `requestAnimationFrame` callback; `false` when this frame has none left. Called until it says so. */
42
+ frame: run_frame,
43
+ /** Whether a `requestAnimationFrame` callback waits for a frame. Read at the end of a turn. */
44
+ frame_pending,
38
45
  /** Answer a call the app made to the host (see host-call.js). */
39
46
  resolve: settle_call,
40
47
  /**
package/src/shims.js CHANGED
@@ -89,8 +89,13 @@ if (typeof g.queueMicrotask !== 'function') {
89
89
  };
90
90
  }
91
91
 
92
- if (typeof g.performance === 'undefined') {
93
- g.performance = { now: clock };
92
+ // One clock for scripts, timers and frame timestamps: the host's, which
93
+ // stands still headless until a test moves it. QuickJS-ng has a `performance`
94
+ // of its own, on real time, whose `now` cannot be replaced; animation code
95
+ // compares a frame's timestamp with `performance.now()`, so the whole object
96
+ // is. Its `timeOrigin` stays.
97
+ if (typeof g.performance === 'undefined' || host.now) {
98
+ g.performance = { ...g.performance, now: clock };
94
99
  }
95
100
 
96
101
  // ---------------------------------------------------------------------------
@@ -101,11 +106,24 @@ if (typeof g.performance === 'undefined') {
101
106
  // timer is pending.
102
107
  // ---------------------------------------------------------------------------
103
108
 
104
- /** @typedef {{ fn: Function, args: any[], at: number, every: number }} Timer */
109
+ /** @typedef {{ fn: Function, args: any[], at: number, every: number, level: number }} Timer */
105
110
 
106
111
  /** @type {Map<number, Timer>} */
107
112
  const timers = new Map();
108
113
  let next_timer_id = 1;
114
+ /**
115
+ * HTML's timer nesting level: that of the timer whose callback, or whose
116
+ * microtasks, run now; 0 outside a timer.
117
+ */
118
+ let timer_level = 0;
119
+
120
+ /**
121
+ * As in HTML: from the sixth nested timer on, a timer waits at least 4 ms.
122
+ * A chain of `setTimeout(fn, 0)` then wakes the host about 250 times a
123
+ * second, not once per turn as fast as it can go.
124
+ * @param {number} delay
125
+ */
126
+ const clamped = (delay) => (timer_level > 5 ? Math.max(4, delay) : delay);
109
127
 
110
128
  /**
111
129
  * @param {unknown} fn
@@ -116,8 +134,8 @@ let next_timer_id = 1;
116
134
  function add_timer(fn, delay, every, args) {
117
135
  if (typeof fn !== 'function') return 0;
118
136
  const id = next_timer_id++;
119
- const at = clock() + Math.max(0, Number(delay) || 0);
120
- timers.set(id, { fn, args, at, every });
137
+ const at = clock() + clamped(Math.max(0, Number(delay) || 0));
138
+ timers.set(id, { fn, args, at, every, level: timer_level + 1 });
121
139
  return id;
122
140
  }
123
141
 
@@ -172,6 +190,7 @@ let round = null;
172
190
  * @returns {boolean}
173
191
  */
174
192
  export function run_timers() {
193
+ timer_level = 0;
175
194
  if (round === null) {
176
195
  if (timers.size === 0) return false;
177
196
  const now = clock();
@@ -190,8 +209,13 @@ export function run_timers() {
190
209
  }
191
210
  const [id, timer] = next;
192
211
  if (!timers.has(id)) continue; // cleared by an earlier callback
193
- if (timer.every > 0) timer.at = clock() + timer.every;
194
- else timers.delete(id);
212
+ // Until the next call: the microtasks the host runs in between belong to this timer.
213
+ timer_level = timer.level;
214
+ if (timer.every > 0) {
215
+ // Each run of an interval is nested in the one before.
216
+ timer.at = clock() + clamped(timer.every);
217
+ timer.level++;
218
+ } else timers.delete(id);
195
219
  try {
196
220
  timer.fn(...timer.args);
197
221
  } catch (error) {
@@ -222,8 +246,62 @@ if (typeof g.setTimeout !== 'function') {
222
246
  g.clearInterval = g.clearTimeout;
223
247
  }
224
248
 
249
+ // ---------------------------------------------------------------------------
250
+ // Animation frames
251
+ //
252
+ // A `requestAnimationFrame` callback runs when the host draws its next frame,
253
+ // before it lays the page out and paints. The host asks `frame_pending()` at
254
+ // the end of every turn and draws a frame only when the answer is yes, so
255
+ // with no callback queued nothing is drawn and nothing wakes it.
256
+ // ---------------------------------------------------------------------------
257
+
258
+ /** Queued callbacks, in the order they were queued. @type {Map<number, (time: number) => void>} */
259
+ const frame_callbacks = new Map();
260
+ let next_frame_id = 1;
261
+ /** The callbacks that were queued when the host started this frame. @type {number[] | null} */
262
+ let frame = null;
263
+
264
+ /**
265
+ * Run one callback of this frame, and say whether there was one. As with
266
+ * timers, the host calls this until the answer is no, and runs microtasks
267
+ * after every call. Every callback of a frame gets the same `time`; one
268
+ * queued during the frame runs in the next.
269
+ *
270
+ * @param {number} time the frame's timestamp, on the host clock
271
+ * @returns {boolean}
272
+ */
273
+ export function run_frame(time) {
274
+ if (frame === null) {
275
+ if (frame_callbacks.size === 0) return false;
276
+ frame = [...frame_callbacks.keys()];
277
+ }
278
+ for (;;) {
279
+ const id = frame.shift();
280
+ if (id === undefined) {
281
+ frame = null;
282
+ return false;
283
+ }
284
+ const fn = frame_callbacks.get(id);
285
+ if (fn === undefined) continue; // cancelled by an earlier callback
286
+ frame_callbacks.delete(id);
287
+ try {
288
+ fn(time);
289
+ } catch (error) {
290
+ g.console.error('Error in requestAnimationFrame callback:', error);
291
+ }
292
+ return true;
293
+ }
294
+ }
295
+
296
+ /** Whether the app waits for a frame. The host asks at the end of every turn. */
297
+ export const frame_pending = () => frame_callbacks.size > 0;
298
+
225
299
  if (typeof g.requestAnimationFrame !== 'function') {
226
- // TODO: tie this to the host's redraw instead of a 16ms timer.
227
- g.requestAnimationFrame = (/** @type {(time: number) => void} */ fn) => g.setTimeout(() => fn(clock()), 16);
228
- g.cancelAnimationFrame = g.clearTimeout;
300
+ g.requestAnimationFrame = (/** @type {unknown} */ fn) => {
301
+ if (typeof fn !== 'function') throw new TypeError('requestAnimationFrame: the callback is not a function');
302
+ const id = next_frame_id++;
303
+ frame_callbacks.set(id, /** @type {(time: number) => void} */ (fn));
304
+ return id;
305
+ };
306
+ g.cancelAnimationFrame = (/** @type {number} */ id) => void frame_callbacks.delete(id);
229
307
  }