@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/src/index.ts ADDED
@@ -0,0 +1,140 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import {
4
+ TestRenderer,
5
+ Window,
6
+ compareRgbaImages,
7
+ createApp,
8
+ readPngRgba,
9
+ type AppHandle,
10
+ type AppOptions,
11
+ type PixelComparison,
12
+ type PixelComparisonOptions,
13
+ type RgbaImage,
14
+ type ThemeDefinition,
15
+ type VNode,
16
+ } from "@tarve/core";
17
+ import { jsx } from "@tarve/core/jsx-runtime";
18
+ import { HeadlessBridge, type HeadlessBridgeOptions } from "./bridge";
19
+ import { encodePng } from "./png";
20
+ import { loadHeadlessRuntime, type HeadlessRuntimeOptions } from "./runtime";
21
+
22
+ export { HeadlessBridge, type HeadlessBridgeOptions } from "./bridge";
23
+ export { encodePng } from "./png";
24
+ export {
25
+ loadHeadlessRuntime,
26
+ registerHeadlessFont,
27
+ type HeadlessFont,
28
+ type HeadlessRuntimeOptions,
29
+ } from "./runtime";
30
+
31
+ export type HeadlessAppOptions = Omit<AppOptions, "bridge" | "debug" | "headless"> & HeadlessBridgeOptions & HeadlessRuntimeOptions;
32
+
33
+ export interface HeadlessApp extends AppHandle {
34
+ readonly bridge: HeadlessBridge;
35
+ /** Waits until the app stops re-rendering in response to layout and input. */
36
+ settle(): Promise<void>;
37
+ /** The current frame as RGBA pixels. */
38
+ pixels(): RgbaImage;
39
+ /** The current frame as PNG bytes. */
40
+ png(): Uint8Array;
41
+ }
42
+
43
+ /**
44
+ * Runs a Tarve app on the WebAssembly runtime: no window, GPU or native library, so it works in
45
+ * any CI. Input, `inspect`, `advanceMotion` and `capture` behave as in a debug window.
46
+ */
47
+ export async function createHeadlessApp(view: () => VNode, options: HeadlessAppOptions = {}): Promise<HeadlessApp> {
48
+ const { width, height, scale, clock, assetRoot, fonts, ...appOptions } = options;
49
+ await loadHeadlessRuntime({ fonts });
50
+ const bridge = new HeadlessBridge({ width, height, scale, clock, assetRoot });
51
+ const app = createApp(view, { ...appOptions, debug: true, bridge });
52
+ await app.ready;
53
+ await bridge.settle();
54
+ return Object.assign(app, {
55
+ bridge,
56
+ settle: () => bridge.settle(),
57
+ pixels: () => bridge.pixels(),
58
+ png: () => bridge.png(),
59
+ });
60
+ }
61
+
62
+ /** `createTestRenderer` on the WebAssembly runtime: locators, clicks, typing and captures without a window. */
63
+ export async function createHeadlessTestRenderer(view: () => VNode, options: HeadlessAppOptions = {}): Promise<TestRenderer> {
64
+ return new TestRenderer(await createHeadlessApp(view, options));
65
+ }
66
+
67
+ export interface RenderOptions extends HeadlessBridgeOptions, HeadlessRuntimeOptions {
68
+ /** Theme of the Window wrapped around a view that is not a Window already. */
69
+ theme?: ThemeDefinition;
70
+ }
71
+
72
+ function windowed(view: VNode | (() => VNode), options: RenderOptions): () => VNode {
73
+ const render = typeof view === "function" ? view : () => view;
74
+ return () => {
75
+ const root = render();
76
+ if (root.type === Window) return root;
77
+ return jsx(Window, {
78
+ width: options.width ?? 640,
79
+ height: options.height ?? 480,
80
+ ...(options.theme ? { theme: options.theme } : {}),
81
+ children: root,
82
+ });
83
+ };
84
+ }
85
+
86
+ /** Renders a view (or a component tree that is not a Window, inside a default one) to RGBA pixels. */
87
+ export async function renderToRgba(view: VNode | (() => VNode), options: RenderOptions = {}): Promise<RgbaImage> {
88
+ const { theme: _theme, ...appOptions } = options;
89
+ const app = await createHeadlessApp(windowed(view, options), appOptions);
90
+ try {
91
+ return app.pixels();
92
+ } finally {
93
+ app.close();
94
+ }
95
+ }
96
+
97
+ /** Renders a view to PNG bytes. Same input, same bytes, on every platform. */
98
+ export async function renderToPng(view: VNode | (() => VNode), options: RenderOptions = {}): Promise<Uint8Array> {
99
+ const image = await renderToRgba(view, options);
100
+ return encodePng(image.rgba, image.width, image.height);
101
+ }
102
+
103
+ export interface ImageSnapshotOptions extends PixelComparisonOptions {
104
+ /** Share of pixels allowed to differ. Default 0: captures are deterministic. */
105
+ maxDifferenceRatio?: number;
106
+ /** Overwrite the stored image. Default: `TARVE_UPDATE_SNAPSHOTS=1`. */
107
+ update?: boolean;
108
+ }
109
+
110
+ /**
111
+ * Compares an image with the PNG stored at `file`. A missing file is written (except on CI,
112
+ * where it fails); a mismatch writes `<file>.actual.png` next to it and throws.
113
+ */
114
+ export async function matchImageSnapshot(image: RgbaImage, file: string, options: ImageSnapshotOptions = {}): Promise<PixelComparison | undefined> {
115
+ const update = options.update ?? process.env.TARVE_UPDATE_SNAPSHOTS === "1";
116
+ const write = (path: string) => {
117
+ mkdirSync(dirname(path), { recursive: true });
118
+ writeFileSync(path, encodePng(image.rgba, image.width, image.height));
119
+ };
120
+ if (update || !existsSync(file)) {
121
+ if (!update && process.env.CI) throw new Error(`Missing image snapshot ${file}. Run the tests locally to create it and commit it.`);
122
+ write(file);
123
+ return undefined;
124
+ }
125
+ const expected = await readPngRgba(file);
126
+ const actualPath = file.replace(/\.png$/i, "") + ".actual.png";
127
+ if (expected.width !== image.width || expected.height !== image.height) {
128
+ write(actualPath);
129
+ throw new Error(`Image snapshot ${file} is ${expected.width}x${expected.height}, got ${image.width}x${image.height}; wrote ${actualPath}`);
130
+ }
131
+ const comparison = compareRgbaImages(image, expected, options);
132
+ if (comparison.differenceRatio > (options.maxDifferenceRatio ?? 0)) {
133
+ write(actualPath);
134
+ throw new Error(
135
+ `Image snapshot ${file} differs in ${comparison.differentPixels} of ${comparison.totalPixels} pixels ` +
136
+ `(max channel delta ${comparison.maxChannelDelta}); wrote ${actualPath}`,
137
+ );
138
+ }
139
+ return comparison;
140
+ }
package/src/png.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { deflateSync } from "node:zlib";
2
+
3
+ const CRC_TABLE = new Uint32Array(256).map((_, n) => {
4
+ let c = n;
5
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
6
+ return c >>> 0;
7
+ });
8
+
9
+ function crc32(bytes: Uint8Array): number {
10
+ let crc = 0xffffffff;
11
+ for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
12
+ return (crc ^ 0xffffffff) >>> 0;
13
+ }
14
+
15
+ function chunk(type: string, data: Uint8Array): Buffer {
16
+ const out = Buffer.alloc(12 + data.length);
17
+ out.writeUInt32BE(data.length, 0);
18
+ out.write(type, 4, "ascii");
19
+ out.set(data, 8);
20
+ out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length);
21
+ return out;
22
+ }
23
+
24
+ /** Encodes RGBA8 pixels as an 8-bit truecolour-with-alpha PNG. */
25
+ export function encodePng(rgba: Uint8Array, width: number, height: number): Uint8Array {
26
+ const stride = width * 4;
27
+ const raw = Buffer.alloc((stride + 1) * height);
28
+ for (let y = 0; y < height; y++) {
29
+ raw[y * (stride + 1)] = 0;
30
+ raw.set(rgba.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
31
+ }
32
+ const header = Buffer.alloc(13);
33
+ header.writeUInt32BE(width, 0);
34
+ header.writeUInt32BE(height, 4);
35
+ header[8] = 8;
36
+ header[9] = 6;
37
+ return Buffer.concat([
38
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
39
+ chunk("IHDR", header),
40
+ chunk("IDAT", deflateSync(raw, { level: 9 })),
41
+ chunk("IEND", new Uint8Array()),
42
+ ]);
43
+ }
44
+
45
+ /** Copies a rectangle out of an RGBA8 image. */
46
+ export function cropRgba(rgba: Uint8Array, width: number, x: number, y: number, w: number, h: number): Uint8Array {
47
+ const out = new Uint8Array(w * h * 4);
48
+ for (let row = 0; row < h; row++) {
49
+ const from = ((y + row) * width + x) * 4;
50
+ out.set(rgba.subarray(from, from + w * 4), row * w * 4);
51
+ }
52
+ return out;
53
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,90 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ /** The part of the wasm-bindgen output this package uses (see native/src/web.rs). */
5
+ export interface WebTreeHandle {
6
+ command(command: string): void;
7
+ resize(width: number, height: number, scale: number): void;
8
+ frame(nowMs: number): boolean;
9
+ pixelsPtr(): number;
10
+ pixelsLen(): number;
11
+ deviceWidth(): number;
12
+ deviceHeight(): number;
13
+ nextTickMs(): number;
14
+ takeEvents(): string;
15
+ takeRemoteImageRequests(): string;
16
+ finishRemoteImage(url: string, bytes: Uint8Array, error?: string): void;
17
+ free(): void;
18
+ }
19
+
20
+ interface WasmModule {
21
+ initSync(options: { module: BufferSource }): { memory: WebAssembly.Memory };
22
+ registerFont(bytes: Uint8Array, generics: string): void;
23
+ WebTree: new (document: string) => WebTreeHandle;
24
+ }
25
+
26
+ /** A font to register before rendering, e.g. a CJK or emoji font. */
27
+ export interface HeadlessFont {
28
+ data: Uint8Array;
29
+ /** CSS generic families it serves: `sans-serif`, `monospace`, `emoji`… */
30
+ families: readonly string[];
31
+ }
32
+
33
+ export interface HeadlessRuntimeOptions {
34
+ /** Extra fonts, registered after the bundled Inter and JetBrains Mono. */
35
+ fonts?: readonly HeadlessFont[];
36
+ }
37
+
38
+ export interface HeadlessRuntime {
39
+ memory: WebAssembly.Memory;
40
+ WebTree: WasmModule["WebTree"];
41
+ }
42
+
43
+ const SANS = ["system-ui", "ui-sans-serif", "sans-serif", "serif", "ui-serif", "cursive", "fantasy", "emoji"];
44
+ const MONO = ["monospace", "ui-monospace"];
45
+
46
+ let runtime: Promise<HeadlessRuntime> | undefined;
47
+ let loaded: HeadlessRuntime | undefined;
48
+ let wasmModule: WasmModule | undefined;
49
+
50
+ function asset(path: string): string {
51
+ return fileURLToPath(new URL(path, import.meta.url));
52
+ }
53
+
54
+ /**
55
+ * Loads the WebAssembly build of Tarve's native tree and the bundled fonts, once per process.
56
+ * There are no system fonts here: text renders with the same Inter and JetBrains Mono on every
57
+ * machine, which is what makes captures comparable across platforms.
58
+ */
59
+ export function loadHeadlessRuntime(options: HeadlessRuntimeOptions = {}): Promise<HeadlessRuntime> {
60
+ runtime ??= (async () => {
61
+ const glue = asset("../wasm/tarve_web.js");
62
+ const binary = asset("../wasm/tarve_web_bg.wasm");
63
+ if (!existsSync(glue) || !existsSync(binary)) {
64
+ throw new Error("@tarve/headless: the WebAssembly runtime is missing. Run `bun run build:wasm` in the Tarve repository.");
65
+ }
66
+ const module = (await import(glue)) as WasmModule;
67
+ const { memory } = module.initSync({ module: readFileSync(binary) });
68
+ module.registerFont(readFileSync(asset("../fonts/InterVariable.ttf")), SANS.join(","));
69
+ module.registerFont(readFileSync(asset("../fonts/JetBrainsMono.ttf")), MONO.join(","));
70
+ wasmModule = module;
71
+ loaded = { memory, WebTree: module.WebTree };
72
+ return loaded;
73
+ })();
74
+ return runtime.then((ready) => {
75
+ for (const font of options.fonts ?? []) registerHeadlessFont(font);
76
+ return ready;
77
+ });
78
+ }
79
+
80
+ /** Registers a font for every tree created afterwards. Call after `loadHeadlessRuntime`. */
81
+ export function registerHeadlessFont(font: HeadlessFont): void {
82
+ if (!wasmModule) throw new Error("@tarve/headless: call loadHeadlessRuntime() before registering fonts");
83
+ wasmModule.registerFont(font.data, font.families.join(","));
84
+ }
85
+
86
+ /** The loaded runtime, for code that cannot await (bridges start synchronously). */
87
+ export function headlessRuntime(): HeadlessRuntime {
88
+ if (!loaded) throw new Error("@tarve/headless: call and await loadHeadlessRuntime() first");
89
+ return loaded;
90
+ }
@@ -0,0 +1,142 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ export class WebTree {
5
+ free(): void;
6
+ [Symbol.dispose](): void;
7
+ /**
8
+ * Moves the native clock to `now_ms` without stepping motion. Call before `command` so
9
+ * transitions started by a patch begin now, not at the last painted frame.
10
+ */
11
+ advanceClock(now_ms: number): void;
12
+ blur(): void;
13
+ /**
14
+ * Applies a JSON `NativeCommand`, including the diagnostic `inspect`, `input` and
15
+ * `motionAdvance` commands. Commands that need a desktop window are ignored.
16
+ */
17
+ command(command: string): void;
18
+ /**
19
+ * CSS cursor for the hovered node: `text`, `col-resize`/`row-resize`, `pointer` or `default`.
20
+ */
21
+ cursor(): string;
22
+ deviceHeight(): number;
23
+ deviceWidth(): number;
24
+ /**
25
+ * Decodes a fetched remote image, or records why it failed when `error` is set.
26
+ */
27
+ finishRemoteImage(url: string, bytes: Uint8Array, error?: string | null): void;
28
+ /**
29
+ * Advances motion to `now_ms`, lays out and paints when something changed.
30
+ * Returns true when `pixels()` holds a new frame.
31
+ */
32
+ frame(now_ms: number): boolean;
33
+ /**
34
+ * Sends a named key (`Enter`, `ShiftArrowLeft`, `Escape`…), as the desktop runtime does.
35
+ * Returns true when the tree handled it.
36
+ */
37
+ key(name: string): boolean;
38
+ /**
39
+ * Creates a tree from a `SceneDocument` JSON string.
40
+ */
41
+ constructor(document: string);
42
+ /**
43
+ * Milliseconds until motion, caret blink or another clock needs a frame, or -1 when idle.
44
+ */
45
+ nextTickMs(): number;
46
+ pixelsLen(): number;
47
+ /**
48
+ * Address of the last frame's opaque RGBA8 pixels in wasm memory, so the page can
49
+ * hand them to the canvas without copying.
50
+ */
51
+ pixelsPtr(): number;
52
+ pointerContext(): void;
53
+ pointerDown(): void;
54
+ pointerLeave(): void;
55
+ pointerMove(x: number, y: number): void;
56
+ pointerUp(): void;
57
+ /**
58
+ * Sets the logical size and device pixel ratio of the canvas.
59
+ */
60
+ resize(width: number, height: number, scale: number): void;
61
+ selectedText(): string | undefined;
62
+ /**
63
+ * Drains pending native events as a JSON array.
64
+ */
65
+ takeEvents(): string;
66
+ /**
67
+ * Remote (`http(s)://`) image URLs painted since the last call, as a JSON array.
68
+ * The host fetches them and hands the bytes to `finishRemoteImage`.
69
+ */
70
+ takeRemoteImageRequests(): string;
71
+ typeText(text: string): void;
72
+ wheel(delta_x: number, delta_y: number): void;
73
+ /**
74
+ * The `windowAction` (`minimize`, `toggleMaximize`, `close`) of a node, if it has one.
75
+ */
76
+ windowAction(id: string): string | undefined;
77
+ }
78
+
79
+ /**
80
+ * Registers a TrueType/OpenType font for every tree created afterwards.
81
+ * `generics` is a comma-separated list of CSS generic families (`system-ui,sans-serif`).
82
+ */
83
+ export function registerFont(bytes: Uint8Array, generics: string): void;
84
+
85
+ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
86
+
87
+ export interface InitOutput {
88
+ readonly memory: WebAssembly.Memory;
89
+ readonly __wbg_webtree_free: (a: number, b: number) => void;
90
+ readonly registerFont: (a: number, b: number, c: number, d: number) => void;
91
+ readonly webtree_advanceClock: (a: number, b: number) => void;
92
+ readonly webtree_blur: (a: number) => void;
93
+ readonly webtree_command: (a: number, b: number, c: number, d: number) => void;
94
+ readonly webtree_cursor: (a: number, b: number) => void;
95
+ readonly webtree_deviceHeight: (a: number) => number;
96
+ readonly webtree_deviceWidth: (a: number) => number;
97
+ readonly webtree_finishRemoteImage: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => void;
98
+ readonly webtree_frame: (a: number, b: number, c: number) => void;
99
+ readonly webtree_key: (a: number, b: number, c: number) => number;
100
+ readonly webtree_new: (a: number, b: number, c: number) => void;
101
+ readonly webtree_nextTickMs: (a: number) => number;
102
+ readonly webtree_pixelsLen: (a: number) => number;
103
+ readonly webtree_pixelsPtr: (a: number) => number;
104
+ readonly webtree_pointerContext: (a: number) => void;
105
+ readonly webtree_pointerDown: (a: number) => void;
106
+ readonly webtree_pointerLeave: (a: number) => void;
107
+ readonly webtree_pointerMove: (a: number, b: number, c: number) => void;
108
+ readonly webtree_pointerUp: (a: number) => void;
109
+ readonly webtree_resize: (a: number, b: number, c: number, d: number) => void;
110
+ readonly webtree_selectedText: (a: number, b: number) => void;
111
+ readonly webtree_takeEvents: (a: number, b: number) => void;
112
+ readonly webtree_takeRemoteImageRequests: (a: number, b: number) => void;
113
+ readonly webtree_typeText: (a: number, b: number, c: number) => void;
114
+ readonly webtree_wheel: (a: number, b: number, c: number) => void;
115
+ readonly webtree_windowAction: (a: number, b: number, c: number, d: number) => void;
116
+ readonly __wbindgen_export: (a: number, b: number) => number;
117
+ readonly __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
118
+ readonly __wbindgen_add_to_stack_pointer: (a: number) => number;
119
+ readonly __wbindgen_export3: (a: number, b: number, c: number) => void;
120
+ }
121
+
122
+ export type SyncInitInput = BufferSource | WebAssembly.Module;
123
+
124
+ /**
125
+ * Instantiates the given `module`, which can either be bytes or
126
+ * a precompiled `WebAssembly.Module`.
127
+ *
128
+ * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
129
+ *
130
+ * @returns {InitOutput}
131
+ */
132
+ export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
133
+
134
+ /**
135
+ * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
136
+ * for everything else, calls `WebAssembly.instantiate` directly.
137
+ *
138
+ * @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
139
+ *
140
+ * @returns {Promise<InitOutput>}
141
+ */
142
+ export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;