@tarve/headless 0.0.0-stage → 0.6.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
@@ -1,3 +1,92 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @tarve/headless
2
+
3
+ Render Tarve apps to pixels with no window, no GPU and no native library. It runs the
4
+ WebAssembly build of Tarve's native tree — the same Taffy layout, Parley text, input handling
5
+ and Vello CPU painter a window uses — inside Bun, so UI tests and visual snapshots run on any
6
+ CI machine (Linux, macOS, Windows, x64 or ARM).
7
+
8
+ Text always renders with the bundled Inter and JetBrains Mono, never with system fonts, and the
9
+ clock only moves when you advance it. The same view gives the same bytes on every machine.
10
+
11
+ ```sh
12
+ bun add -d @tarve/headless
13
+ ```
14
+
15
+ ## Render to an image
16
+
17
+ ```tsx
18
+ import { Button } from "@tarve/core";
19
+ import { renderToPng } from "@tarve/headless";
20
+
21
+ await Bun.write("button.png", await renderToPng(<Button>Save</Button>, { width: 200, height: 80, scale: 2 }));
22
+ ```
23
+
24
+ A view that is not a `Window` is wrapped in one (`width`/`height` default to 640×480, `theme`
25
+ sets its theme). `renderToRgba` returns the raw pixels instead.
26
+
27
+ ## Test like a user
28
+
29
+ `createHeadlessTestRenderer` is `createTestRenderer` from `@tarve/core` on the WebAssembly
30
+ runtime: locators, clicks, typing, scrolling, `inspect` and `capture` work unchanged.
31
+
32
+ ```tsx
33
+ import { expect, test } from "bun:test";
34
+ import { createHeadlessTestRenderer } from "@tarve/headless";
35
+
36
+ test("saves", async () => {
37
+ const renderer = await createHeadlessTestRenderer(App);
38
+ await renderer.getByRole("button", { name: "Save" }).click();
39
+ await renderer.getByText("Saved").waitFor();
40
+ renderer.close();
41
+ });
42
+ ```
43
+
44
+ `createHeadlessApp(view, options)` returns the `AppHandle` itself, plus `pixels()`, `png()` and
45
+ `settle()` (wait until layout feedback and re-renders stop).
46
+
47
+ ## Visual snapshots
48
+
49
+ ```tsx
50
+ import { matchImageSnapshot, renderToRgba } from "@tarve/headless";
51
+
52
+ await matchImageSnapshot(await renderToRgba(App, { scale: 2 }), "__snapshots__/app.png");
53
+ ```
54
+
55
+ A missing snapshot is written (on CI, where `CI` is set, it fails instead). A mismatch writes
56
+ `app.actual.png` next to the stored image and throws. `TARVE_UPDATE_SNAPSHOTS=1` rewrites them.
57
+ Captures are deterministic, so the default tolerance is zero; `threshold` and
58
+ `maxDifferenceRatio` loosen it.
59
+
60
+ ## Time
61
+
62
+ The default `clock: "manual"` freezes time: transitions, `spin` and the caret only move with
63
+ `app.advanceMotion(ms)`, so a capture taken mid-animation is reproducible. `clock: "realtime"`
64
+ follows `performance.now()` like a window.
65
+
66
+ ## Options
67
+
68
+ | Option | Default | |
69
+ |---|---|---|
70
+ | `width`, `height` | the Window's size | Logical size of the render target |
71
+ | `scale` | `1` | Device pixel ratio of the pixels |
72
+ | `clock` | `"manual"` | `"manual"` or `"realtime"` |
73
+ | `assetRoot` | `process.cwd()` | Where relative `Image` paths are read from |
74
+ | `fonts` | — | Extra fonts (`{ data, families }`), e.g. CJK or emoji |
75
+
76
+ ## Limits
77
+
78
+ - No window: title bar buttons, file dialogs, the clipboard and accessibility are desktop-only.
79
+ - Images load from files and `data:` URIs; remote URLs are not fetched. Relative paths resolve from
80
+ the main script, as in a window; web-style `/assets/a.png` paths resolve from `assetRoot`.
81
+ - Only the bundled fonts exist unless you register more: Arabic, CJK and emoji text needs a font.
82
+
83
+ ## Building from the repository
84
+
85
+ The WebAssembly runtime is built, not committed:
86
+
87
+ ```sh
88
+ rustup target add wasm32-unknown-unknown
89
+ cargo install wasm-bindgen-cli --version 0.2.129
90
+ bun run build:wasm
91
+ bun run test:headless
92
+ ```
Binary file
Binary file
@@ -0,0 +1,92 @@
1
+ Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+ -----------------------------------------------------------
8
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
9
+ -----------------------------------------------------------
10
+
11
+ PREAMBLE
12
+ The goals of the Open Font License (OFL) are to stimulate worldwide
13
+ development of collaborative font projects, to support the font creation
14
+ efforts of academic and linguistic communities, and to provide a free and
15
+ open framework in which fonts may be shared and improved in partnership
16
+ with others.
17
+
18
+ The OFL allows the licensed fonts to be used, studied, modified and
19
+ redistributed freely as long as they are not sold by themselves. The
20
+ fonts, including any derivative works, can be bundled, embedded,
21
+ redistributed and/or sold with any software provided that any reserved
22
+ names are not used by derivative works. The fonts and derivatives,
23
+ however, cannot be released under any other type of license. The
24
+ requirement for fonts to remain under this license does not apply
25
+ to any document created using the fonts or their derivatives.
26
+
27
+ DEFINITIONS
28
+ "Font Software" refers to the set of files released by the Copyright
29
+ Holder(s) under this license and clearly marked as such. This may
30
+ include source files, build scripts and documentation.
31
+
32
+ "Reserved Font Name" refers to any names specified as such after the
33
+ copyright statement(s).
34
+
35
+ "Original Version" refers to the collection of Font Software components as
36
+ distributed by the Copyright Holder(s).
37
+
38
+ "Modified Version" refers to any derivative made by adding to, deleting,
39
+ or substituting -- in part or in whole -- any of the components of the
40
+ Original Version, by changing formats or by porting the Font Software to a
41
+ new environment.
42
+
43
+ "Author" refers to any designer, engineer, programmer, technical
44
+ writer or other person who contributed to the Font Software.
45
+
46
+ PERMISSION AND CONDITIONS
47
+ Permission is hereby granted, free of charge, to any person obtaining
48
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
49
+ redistribute, and sell modified and unmodified copies of the Font
50
+ Software, subject to the following conditions:
51
+
52
+ 1) Neither the Font Software nor any of its individual components,
53
+ in Original or Modified Versions, may be sold by itself.
54
+
55
+ 2) Original or Modified Versions of the Font Software may be bundled,
56
+ redistributed and/or sold with any software, provided that each copy
57
+ contains the above copyright notice and this license. These can be
58
+ included either as stand-alone text files, human-readable headers or
59
+ in the appropriate machine-readable metadata fields within text or
60
+ binary files as long as those fields can be easily viewed by the user.
61
+
62
+ 3) No Modified Version of the Font Software may use the Reserved Font
63
+ Name(s) unless explicit written permission is granted by the corresponding
64
+ Copyright Holder. This restriction only applies to the primary font name as
65
+ presented to the users.
66
+
67
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
68
+ Software shall not be used to promote, endorse or advertise any
69
+ Modified Version, except to acknowledge the contribution(s) of the
70
+ Copyright Holder(s) and the Author(s) or with their explicit written
71
+ permission.
72
+
73
+ 5) The Font Software, modified or unmodified, in part or in whole,
74
+ must be distributed entirely under this license, and must not be
75
+ distributed under any other license. The requirement for fonts to
76
+ remain under this license does not apply to any document created
77
+ using the Font Software.
78
+
79
+ TERMINATION
80
+ This license becomes null and void if any of the above conditions are
81
+ not met.
82
+
83
+ DISCLAIMER
84
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
85
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
86
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
87
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
88
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
89
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
90
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
91
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
92
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ https://openfontlicense.org
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@tarve/headless",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.0",
4
+ "description": "Render Tarve UIs to pixels without a window or GPU: tests, visual snapshots and image generation on any platform",
5
+ "license": "Apache-2.0",
6
+ "keywords": [
7
+ "tarve",
8
+ "headless",
9
+ "testing",
10
+ "visual-regression",
11
+ "snapshot",
12
+ "wasm"
13
+ ],
14
+ "homepage": "https://github.com/omarcosr/tarve/tree/main/packages/headless#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/omarcosr/tarve.git",
18
+ "directory": "packages/headless"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/omarcosr/tarve/issues"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "provenance": true
26
+ },
27
+ "type": "module",
28
+ "exports": {
29
+ ".": "./src/index.ts"
30
+ },
31
+ "files": [
32
+ "src",
33
+ "!src/**/*.test.tsx",
34
+ "wasm",
35
+ "fonts",
36
+ "README.md"
37
+ ],
38
+ "scripts": {
39
+ "build": "bun scripts/build-wasm.ts",
40
+ "verify:pack": "bun scripts/verify-pack.ts"
41
+ },
42
+ "peerDependencies": {
43
+ "@tarve/core": ">=0.4.0"
44
+ },
45
+ "engines": {
46
+ "bun": ">=1.4.0"
47
+ }
48
+ }
package/src/bridge.ts ADDED
@@ -0,0 +1,243 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, extname, isAbsolute, resolve } from "node:path";
3
+ import type { NativeBridge, RgbaImage } from "@tarve/core";
4
+ import { encodePng } from "./png";
5
+ import { headlessRuntime, type WebTreeHandle } from "./runtime";
6
+
7
+ type SceneDocument = Parameters<NativeBridge["start"]>[0];
8
+ type NativeEvent = Parameters<Parameters<NativeBridge["start"]>[1]>[0];
9
+ type NativeCommand = Parameters<NativeBridge["send"]>[0];
10
+
11
+ export interface HeadlessBridgeOptions {
12
+ /** Logical size of the render target. Defaults to the Window's width and height. */
13
+ width?: number;
14
+ height?: number;
15
+ /** Device pixel ratio of captures. Default 1. */
16
+ scale?: number;
17
+ /**
18
+ * `manual` (default): time stands still and only `advanceMotion` moves it, so transitions,
19
+ * spinners and the caret are frozen and every capture is reproducible.
20
+ * `realtime`: the clock follows `performance.now()`, as in a window.
21
+ */
22
+ clock?: "manual" | "realtime";
23
+ /** Directory relative `Image` paths (and web-style `/…` paths) are read from. Default `process.cwd()`. */
24
+ assetRoot?: string;
25
+ }
26
+
27
+ const MEDIA: Record<string, string> = {
28
+ ".png": "image/png",
29
+ ".jpg": "image/jpeg",
30
+ ".jpeg": "image/jpeg",
31
+ ".webp": "image/webp",
32
+ ".gif": "image/gif",
33
+ ".svg": "image/svg+xml",
34
+ };
35
+
36
+ /**
37
+ * A `NativeBridge` over the WebAssembly build of Tarve's native tree: the same layout, text,
38
+ * input and CPU painter as a window, with no window, GPU or native library. Pass it to
39
+ * `createApp({ bridge })`; `inspect`, `debug` input, `advanceMotion` and `capture` all work.
40
+ */
41
+ export class HeadlessBridge implements NativeBridge {
42
+ private tree?: WebTreeHandle;
43
+ private onEvent?: (event: NativeEvent) => void;
44
+ private flushQueued = false;
45
+ private tickTimer?: ReturnType<typeof setTimeout>;
46
+ private readonly epoch = performance.now();
47
+ private closed = false;
48
+ /** Bumped by every command and every delivered event, so `settle` can tell when work stops. */
49
+ private activity = 0;
50
+ /** Remote images being fetched; `settle` waits for them. */
51
+ private fetching = 0;
52
+
53
+ constructor(private readonly options: HeadlessBridgeOptions = {}) {}
54
+
55
+ start(document: SceneDocument, onEvent: (event: NativeEvent) => void): void {
56
+ this.onEvent = onEvent;
57
+ this.inlineImages(document);
58
+ const { WebTree } = headlessRuntime();
59
+ this.tree = new WebTree(JSON.stringify(document));
60
+ this.tree.resize(
61
+ this.options.width ?? document.window.width,
62
+ this.options.height ?? document.window.height,
63
+ this.options.scale ?? 1,
64
+ );
65
+ queueMicrotask(() => {
66
+ this.flush();
67
+ this.onEvent?.({ type: "ready" });
68
+ });
69
+ }
70
+
71
+ send(command: NativeCommand): void {
72
+ if (this.closed || !this.tree) return;
73
+ this.activity++;
74
+ switch (command.type) {
75
+ case "close":
76
+ this.dispose();
77
+ queueMicrotask(() => this.onEvent?.({ type: "closed" }));
78
+ return;
79
+ case "cancelCloseRequest":
80
+ return;
81
+ case "capture":
82
+ this.captureTo(command.path, command.requestId);
83
+ return;
84
+ case "fileDialog":
85
+ this.emitSoon({ type: "fileDialog", requestId: command.requestId, paths: [], error: "File dialogs are not available headless" });
86
+ return;
87
+ }
88
+ this.inlineImages(command);
89
+ try {
90
+ this.tree.command(JSON.stringify(command));
91
+ } catch (error) {
92
+ this.emitSoon({ type: "error", message: error instanceof Error ? error.message : String(error) });
93
+ }
94
+ this.queueFlush();
95
+ }
96
+
97
+ join(): void {}
98
+
99
+ /** Lays out, paints if needed and returns the current frame. */
100
+ pixels(): RgbaImage {
101
+ const tree = this.requireTree();
102
+ this.flush();
103
+ const { memory } = headlessRuntime();
104
+ return {
105
+ width: tree.deviceWidth(),
106
+ height: tree.deviceHeight(),
107
+ rgba: new Uint8Array(memory.buffer, tree.pixelsPtr(), tree.pixelsLen()).slice(),
108
+ };
109
+ }
110
+
111
+ /** The current frame as PNG bytes. */
112
+ png(): Uint8Array {
113
+ const image = this.pixels();
114
+ return encodePng(image.rgba, image.width, image.height);
115
+ }
116
+
117
+ /**
118
+ * Resolves once the app stops reacting: no commands and no events for a few turns of the event
119
+ * loop. Layout feedback (virtual lists, scroll positions) and the re-renders it triggers are
120
+ * done by then.
121
+ */
122
+ async settle(maxTurns = 100): Promise<void> {
123
+ let quiet = 0;
124
+ for (let turn = 0; turn < maxTurns && quiet < 3; turn++) {
125
+ const before = this.activity;
126
+ await new Promise((resolve) => setTimeout(resolve, 0));
127
+ this.flush();
128
+ quiet = this.activity === before && this.fetching === 0 ? quiet + 1 : 0;
129
+ }
130
+ }
131
+
132
+ private now(): number {
133
+ return this.options.clock === "realtime" ? performance.now() - this.epoch : 0;
134
+ }
135
+
136
+ private requireTree(): WebTreeHandle {
137
+ if (!this.tree) throw new Error(this.closed ? "The headless app is closed" : "The headless app has not started");
138
+ return this.tree;
139
+ }
140
+
141
+ private queueFlush(): void {
142
+ if (this.flushQueued) return;
143
+ this.flushQueued = true;
144
+ queueMicrotask(() => this.flush());
145
+ }
146
+
147
+ /** Steps the clock, lays out, paints, and delivers whatever the tree emitted. */
148
+ private flush(): void {
149
+ this.flushQueued = false;
150
+ const tree = this.tree;
151
+ if (!tree || this.closed) return;
152
+ try {
153
+ tree.frame(this.now());
154
+ } catch (error) {
155
+ this.onEvent?.({ type: "error", message: error instanceof Error ? error.message : String(error) });
156
+ }
157
+ for (const url of JSON.parse(tree.takeRemoteImageRequests()) as string[]) this.fetchImage(url);
158
+ const events = JSON.parse(tree.takeEvents()) as NativeEvent[];
159
+ if (events.length > 0) this.activity++;
160
+ for (const event of events) {
161
+ if (this.closed) break;
162
+ this.onEvent?.(event);
163
+ }
164
+ if (this.options.clock === "realtime") this.scheduleTick();
165
+ }
166
+
167
+ private scheduleTick(): void {
168
+ clearTimeout(this.tickTimer);
169
+ const next = this.tree?.nextTickMs() ?? -1;
170
+ if (next < 0) return;
171
+ this.tickTimer = setTimeout(() => this.flush(), Math.max(0, next - this.now()));
172
+ (this.tickTimer as { unref?: () => void }).unref?.();
173
+ }
174
+
175
+ /** A painted `http(s)://` image: fetched here, decoded by the tree like in a window. */
176
+ private fetchImage(url: string): void {
177
+ this.fetching++;
178
+ const finish = (bytes: Uint8Array, error?: string) => {
179
+ this.fetching--;
180
+ this.activity++;
181
+ if (this.closed || !this.tree) return;
182
+ this.tree.finishRemoteImage(url, bytes, error);
183
+ this.queueFlush();
184
+ };
185
+ // Settle the fetch first, then hand it over once: a throw inside finish must not finish twice.
186
+ fetch(url)
187
+ .then(async (response) => {
188
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
189
+ return { bytes: new Uint8Array(await response.arrayBuffer()) };
190
+ })
191
+ .catch((error: unknown) => ({ bytes: new Uint8Array(), error: error instanceof Error ? error.message : String(error) }))
192
+ .then(({ bytes, error }: { bytes: Uint8Array; error?: string }) => finish(bytes, error));
193
+ }
194
+
195
+ private emitSoon(event: NativeEvent): void {
196
+ queueMicrotask(() => {
197
+ if (!this.closed) this.onEvent?.(event);
198
+ });
199
+ }
200
+
201
+ private captureTo(path: string, requestId: string): void {
202
+ try {
203
+ const png = this.png();
204
+ mkdirSync(dirname(resolve(path)), { recursive: true });
205
+ writeFileSync(path, png);
206
+ this.emitSoon({ type: "captured", requestId, path });
207
+ } catch (error) {
208
+ this.emitSoon({ type: "captured", requestId, path, error: error instanceof Error ? error.message : String(error) });
209
+ }
210
+ }
211
+
212
+ private dispose(): void {
213
+ this.closed = true;
214
+ clearTimeout(this.tickTimer);
215
+ this.tree?.free();
216
+ this.tree = undefined;
217
+ }
218
+
219
+ /** The wasm tree cannot open files: `Image` sources that are paths are read here and inlined. */
220
+ private inlineImages(value: unknown): void {
221
+ if (Array.isArray(value)) {
222
+ for (const item of value) this.inlineImages(item);
223
+ return;
224
+ }
225
+ if (!value || typeof value !== "object") return;
226
+ const node = value as Record<string, unknown> & { src?: unknown; image?: unknown };
227
+ if (typeof node.kind === "string" && typeof node.id === "string" && typeof node.src === "string" && !node.image) {
228
+ const src = node.src;
229
+ // A single letter before ":" is a Windows drive, not a URL scheme.
230
+ if (!/^[a-z][a-z0-9+.-]+:/i.test(src) || src.startsWith("file:")) {
231
+ const path = src.startsWith("file:") ? new URL(src).pathname : src;
232
+ const root = this.options.assetRoot ?? process.cwd();
233
+ // "/assets/a.png" is a real absolute path, or, as on the web, rooted at assetRoot.
234
+ const file = [isAbsolute(path) ? path : resolve(root, path), resolve(root, path.replace(/^[\\/]+/, ""))].find((candidate) => existsSync(candidate));
235
+ if (file) {
236
+ node.image = { kind: "encoded", key: src, data: readFileSync(file).toString("base64"), mediaType: MEDIA[extname(file).toLowerCase()] };
237
+ delete node.src;
238
+ }
239
+ }
240
+ }
241
+ for (const key in node) if (key !== "style") this.inlineImages(node[key]);
242
+ }
243
+ }