termigan 0.0.0-stage → 0.0.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.
package/docs/api.md ADDED
@@ -0,0 +1,295 @@
1
+ # Termigan API reference
2
+
3
+ The browser API is exported from `"termigan"` ([web/termigan.js](../web/termigan.js)), with TypeScript declarations in [types/index.d.ts](../types/index.d.ts). That module exports `createTermiganViewer`, `attachPtySocket`, and `TermiganViewerElement`, and registers the `<termigan-viewer>` custom element when `customElements` is available. The package also exports `"termigan/wasm"` pointing to `dist/termigan.wasm`.
4
+
5
+ ## createTermiganViewer(container, options)
6
+
7
+ ```js
8
+ const viewer = await createTermiganViewer(container, options);
9
+ ```
10
+
11
+ Creates one terminal viewer instance inside `container`, instantiates one WebAssembly terminal engine, and returns a `Promise` that resolves to a viewer object.
12
+
13
+ ### Parameters
14
+
15
+ | Parameter | Type | Required | Description |
16
+ |---|---|---|---|
17
+ | `container` | `HTMLElement` | Yes | DOM element into which Termigan appends `div.termigan-root`. |
18
+ | `options` | `object` | No | Optional configuration object. Defaults to `{}`. |
19
+
20
+ ### Options
21
+
22
+ | Option | Type | Default | Behavior |
23
+ |---|---|---|---|
24
+ | `wasmUrl` | `string`, `URL`, `WebAssembly.Module`, `Uint8Array`, or `ArrayBuffer` | `new URL("../dist/termigan.wasm", import.meta.url)` | WebAssembly binary source passed to `WasmTerminalEngine.create`. Resolves relative to `web/termigan.js` when omitted. URL strings and `URL` objects are fetched, compiled once, and cached in memory. |
25
+ | `cols` | `number` | `80` | Initial remote column count. Falsy values resolve to `80`. Truncated to integer and clamped to at least `1`. |
26
+ | `rows` | `number` | `24` | Initial remote row count. Falsy values resolve to `24`. Truncated to integer and clamped to at least `2`. |
27
+ | `scrollbackCap` | `number` | `10000` | Maximum lines retained in normal-screen scrollback. Uses nullish coalescing so `0` disables scrollback retention. |
28
+ | `fontSize` | `number` | `13` | Base font size in CSS pixels. Falsy values resolve to `13`. |
29
+ | `minFontSize` | `number` | `6` | Minimum font size in CSS pixels when scaled down in `"mirror"` mode. Falsy values resolve to `6`. |
30
+ | `fontFamily` | `string` | `"'JetBrains Mono', 'Fira Code', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"` | CSS font family string used to measure cells and paint text. |
31
+ | `theme` | `object` | `DEFAULT_THEME` | Partial or full color override object merged onto `DEFAULT_THEME`. |
32
+ | `isMac` | `boolean` | Auto-detected | Controls macOS copy and paste shortcut routes. When omitted, checks `navigator.userAgentData.platform` or `navigator.platform` against `/mac\|iphone\|ipad\|ipod/i`. |
33
+ | `shouldHandleKey` | `function` | `undefined` | Initial key interceptor callback taking a `KeyboardEvent`. Installed when `typeof options.shouldHandleKey === "function"`. |
34
+
35
+ ### options.theme
36
+
37
+ `DEFAULT_THEME` in [web/canvas-renderer.js](../web/canvas-renderer.js) defines these properties. Any omitted property falls back to its default.
38
+
39
+ | Property | Type | Default |
40
+ |---|---|---|
41
+ | `background` | `string` | `"#0f1117"` |
42
+ | `foreground` | `string` | `"#e6edf3"` |
43
+ | `cursor` | `string` | `"#58a6ff"` |
44
+ | `cursorAccent` | `string` | `"#0f1117"` |
45
+ | `selection` | `string` | `"rgba(88, 166, 255, 0.32)"` |
46
+ | `scrollbarTrack` | `string` | `"rgba(255, 255, 255, 0.06)"` |
47
+ | `scrollbarThumb` | `string` | `"rgba(255, 255, 255, 0.28)"` |
48
+ | `palette` | `string[]` | 16 ANSI colors from index `0` to `15`: `["#1f242c", "#f85149", "#3fb950", "#d29922", "#58a6ff", "#bc8cff", "#39c5cf", "#b1bac4", "#6e7681", "#ff7b72", "#56d364", "#e3b341", "#79c0ff", "#d2a8ff", "#56d4dd", "#f0f6fc"]` |
49
+
50
+ ## Viewer properties
51
+
52
+ | Property | Type | Description |
53
+ |---|---|---|
54
+ | `element` | `HTMLDivElement` | Root `div.termigan-root` element created inside `container`. Contains the `<canvas>` and hidden `<textarea class="termigan-input">`. |
55
+
56
+ ## Control methods
57
+
58
+ ### write(bytes)
59
+
60
+ Writes VT output into the WebAssembly engine and drains any replies queued by device queries. When replies exist, it emits `"input"` synchronously before it schedules a frame render on the next animation frame.
61
+
62
+ - **Parameters.** `bytes` accepts a UTF-8 `string`, `Uint8Array`, `ArrayBuffer`, or array-like byte sequence accepted by `new Uint8Array(bytes)`.
63
+ - **Returns.** `undefined`. No-op after `dispose()`.
64
+
65
+ ### reset()
66
+
67
+ Resets the WebAssembly terminal engine and keeps current `cols`, `rows`, and `scrollbackCap`. Clears any active selection, sets `scrollbackLen` and `scrollOffset` to `0`, and schedules a full frame render.
68
+
69
+ - **Returns.** `undefined`. No-op after `dispose()`.
70
+
71
+ ### dispose()
72
+
73
+ Destroys the viewer instance. Cancels any queued `requestAnimationFrame`, disconnects `ResizeObserver`, removes DOM and `window` listeners, frees the WebAssembly terminal handle, and removes `element` from the DOM. Repeated calls have no effect.
74
+
75
+ - **Returns.** `undefined`.
76
+
77
+ ### setRemoteSize(cols, rows)
78
+
79
+ Updates the remote session size used in `"mirror"` mode. `cols` is truncated to an integer and clamped to at least `1`. `rows` is truncated to an integer and clamped to at least `2`.
80
+
81
+ If the remote dimensions changed, Termigan recomputes layout, resizes the engine grid if needed, and schedules a render. `setRemoteSize` never emits `"resize"`.
82
+
83
+ - **Returns.** `undefined`. No-op after `dispose()`.
84
+
85
+ ### setSizeMode(mode)
86
+
87
+ Switches between `"mirror"` and `"fit"` size modes.
88
+
89
+ - In `"mirror"` mode, the terminal grid stays at the dimensions set by `cols`, `rows`, and `setRemoteSize`. Font size scales down toward `minFontSize` and canvas CSS dimensions scale down so the viewer fits the container with zero outer scrollbars. `"resize"` is never emitted.
90
+ - In `"fit"` mode, Termigan computes the columns and rows that fit inside the container at `fontSize` and sets canvas CSS scale to `1`. It resizes the terminal grid and emits `"resize"` when those grid dimensions change.
91
+
92
+ Throws an `Error` with message `Invalid size mode: <mode>` if `mode` is neither `"mirror"` nor `"fit"`.
93
+
94
+ - **Returns.** `undefined`. No-op after `dispose()`.
95
+
96
+ ### proposeFitSize()
97
+
98
+ Measures the viewer container box. When `expanded` is `true`, it measures `window.innerWidth` and `window.innerHeight` instead. It returns the grid size that fits at `fontSize` without changing viewer state.
99
+
100
+ - **Returns.** `{ cols: number, rows: number }`. Falls back to `{ cols, rows }` of the current grid if the measured box has zero width or zero height.
101
+
102
+ ### setExpanded(expanded)
103
+
104
+ Promotes the viewer into a full-window overlay or restores it inline. When `expanded` is `true`, Termigan sets `popover="manual"`, calls `showPopover()` when supported, and sets fixed `100vw` by `100vh` styles with `z-index: 2147483647`. When `expanded` is `false`, Termigan calls `hidePopover()`, removes the `popover` attribute, and restores `100%` relative sizing.
105
+
106
+ Focus on the hidden `<textarea>` stays intact across the transition. Layout and frame flush run synchronously before `"expanded"` listeners run. Expand and restore operations never reset the engine, drop bytes, or reconnect transports.
107
+
108
+ - **Parameters.** `expanded` is coerced with `Boolean(expanded)`. If the value equals the current expanded state, the call returns without invoking `onExpandedChange`.
109
+ - **Returns.** `undefined`. No-op after `dispose()`.
110
+
111
+ ### scrollToBottom()
112
+
113
+ Sets `scrollOffset` to `0` and schedules a full render if `scrollOffset` changed.
114
+
115
+ - **Returns.** `undefined`. No-op after `dispose()`.
116
+
117
+ ### focus()
118
+
119
+ Focuses the hidden `<textarea>` with `{ preventScroll: true }`.
120
+
121
+ - **Returns.** `undefined`. No-op after `dispose()`.
122
+
123
+ ### blur()
124
+
125
+ Blurs the hidden `<textarea>`.
126
+
127
+ - **Returns.** `undefined`. No-op after `dispose()`.
128
+
129
+ ### setKeyInterceptor(fn)
130
+
131
+ Replaces or clears the host key interceptor callback installed by `options.shouldHandleKey`.
132
+
133
+ - **Parameters.** Pass a callback that takes a `KeyboardEvent` and returns a string to intercept keys. Pass `null` or any non-function to clear the interceptor.
134
+ - **Returns.** `undefined`.
135
+
136
+ When the viewer has focus and is not inside an IME composition sequence, Termigan calls the interceptor on each `keydown` event. That call runs before modifier filters, copy or paste shortcuts, and VT key encoding. If the interceptor returns `"host"`, Termigan leaves `event.preventDefault()` uncalled, suppresses the next `input` event on the hidden `<textarea>`, and emits no `"input"` bytes. Any other return value lets Termigan process the key.
137
+
138
+ ### sendKey(keySpec)
139
+
140
+ Encodes `keySpec` with the terminal's current modes and emits `"input"` with the resulting `Uint8Array` if at least one byte was produced. `sendKey` works whether or not the viewer has focus.
141
+
142
+ - **Parameters.** `keySpec` is an object with these properties:
143
+
144
+ | Property | Type | Required | Default | Description |
145
+ |---|---|---|---|---|
146
+ | `key` | `string` | Yes | `""` | Named VT key or single UTF-8 character. |
147
+ | `ctrl` | `boolean` | No | `false` | Sets the `ctrl` modifier bit, `4`. |
148
+ | `alt` | `boolean` | No | `false` | Sets the `alt` modifier bit, `2`. |
149
+ | `shift` | `boolean` | No | `false` | Sets the `shift` modifier bit, `1`. |
150
+ | `meta` | `boolean` | No | `false` | Sets the `meta` modifier bit, `8`. |
151
+
152
+ `core/KeyEncoder.roc` accepts these `key` values:
153
+
154
+ - **Named VT keys.** `"Enter"`, `"Tab"`, `"Escape"`, `"Backspace"`, `"ArrowUp"`, `"ArrowDown"`, `"ArrowLeft"`, `"ArrowRight"`, `"Home"`, `"End"`, `"Insert"`, `"Delete"`, `"PageUp"`, `"PageDown"`, and `"F1"` through `"F12"`.
155
+ - **Single ASCII byte.** Any 1-byte UTF-8 character including `" "`. When `ctrl` is `true`, it maps ASCII letters `a` through `z`, `A` through `Z`, and control characters `" "`, `"@"`, `"2"`, ``"`"``, `"["`, `"3"`, `"\\"`, `"4"`, `"]"`, `"5"`, `"^"`, `"6"`, `"_"`, `"/"`, `"7"`, and `"8"`.
156
+ - **Single multibyte UTF-8 character.** Any single 2-byte, 3-byte, or 4-byte UTF-8 character when `ctrl` is `false`.
157
+
158
+ Other strings, such as empty strings and unrecognized key names, encode to `Uint8Array(0)` and do not emit `"input"`.
159
+
160
+ - **Returns.** `undefined`. No-op after `dispose()`.
161
+
162
+ ### getSelectedText()
163
+
164
+ Extracts the active mouse selection from the WebAssembly engine. It joins soft-wrapped rows without newlines and trims spaces at the ends of unwrapped rows.
165
+
166
+ - **Returns.** `string`. Returns `""` when no selection is active.
167
+
168
+ ### getLastCopiedText()
169
+
170
+ Returns the text most recently copied by `Ctrl+Shift+C`, `Cmd+C`, `Ctrl+C` over an active selection, or a browser `copy` event on the viewer.
171
+
172
+ - **Returns.** `string`. Returns `""` before any copy occurs.
173
+
174
+ ### getState()
175
+
176
+ Returns a snapshot object with the viewer's current dimensions, mode, scroll state, font size, screen buffer, and focus state.
177
+
178
+ | Field | Type | Description |
179
+ |---|---|---|
180
+ | `cols` | `number` | Current terminal grid width in columns. |
181
+ | `rows` | `number` | Current terminal grid height in rows. |
182
+ | `sizeMode` | `"mirror"` or `"fit"` | Active viewport size mode. |
183
+ | `expanded` | `boolean` | Whether the full-window popover overlay is active. |
184
+ | `scrollOffset` | `number` | Lines scrolled up from the live bottom. Zero when at the bottom. |
185
+ | `scrollbackLen` | `number` | Current number of lines stored in the normal scrollback buffer. |
186
+ | `fontSize` | `number` | Active rendered font size in CSS pixels. |
187
+ | `altScreen` | `boolean` | Whether the alternate screen buffer is active. |
188
+ | `focused` | `boolean` | Whether the viewer's hidden `<textarea>` has focus, which includes active IME composition. |
189
+
190
+ ## Event subscriptions
191
+
192
+ Every event method adds `fn` to an internal `Set`. Each method returns an unsubscribe function that removes `fn` from that set and returns a `boolean`.
193
+
194
+ ### onInput(fn)
195
+
196
+ Registers `fn(bytes)` to receive `Uint8Array` payloads intended for the remote terminal backend. Termigan emits `"input"` from these sources:
197
+
198
+ - Encoded keys and typed characters from the focused `<textarea>`.
199
+ - Committed IME composition text from `compositionend`.
200
+ - Pasted text normalized to `\r` line endings and wrapped in `\x1b[200~` and `\x1b[201~` when bracketed paste mode is active.
201
+ - Mouse button and motion sequences when DEC mouse mode is active and `Shift` is not held.
202
+ - Wheel scroll sequences when mouse mode or alternate-screen arrow fallback is active.
203
+ - Calls to `sendKey(keySpec)`.
204
+ - Device replies drained synchronously when `write(bytes)` runs. Possible sequences are `CSI ? 62 ; 22 c`, `CSI > 0 ; 10 ; 1 c`, `CSI 0 n`, and `CSI row ; col R`.
205
+
206
+ - **Returns.** Unsubscribe function.
207
+
208
+ ### onFocus(fn)
209
+
210
+ Registers `fn()` to run when the hidden `<textarea>` gains focus from the unfocused state.
211
+
212
+ - **Returns.** Unsubscribe function.
213
+
214
+ ### onBlur(fn)
215
+
216
+ Registers `fn()` to run when the hidden `<textarea>` loses focus while focused or in IME composition.
217
+
218
+ - **Returns.** Unsubscribe function.
219
+
220
+ ### onResize(fn)
221
+
222
+ Registers `fn(cols, rows)` to run when `"fit"` mode computes new grid dimensions. Never fires while `sizeMode` is `"mirror"`.
223
+
224
+ - **Returns.** Unsubscribe function.
225
+
226
+ ### onExpandedChange(fn)
227
+
228
+ Registers `fn(expanded)` to run when `setExpanded(expanded)` changes the expanded state. Receives the new `boolean` value.
229
+
230
+ - **Returns.** Unsubscribe function.
231
+
232
+ ### onTitleChange(fn)
233
+
234
+ Registers `fn(title)` to run at frame flush when an OSC `0` or OSC `2` sequence changes the terminal title sequence counter. Receives the UTF-8 title `string`.
235
+
236
+ - **Returns.** Unsubscribe function.
237
+
238
+ ## attachPtySocket(viewer, socket, options)
239
+
240
+ ```js
241
+ const detach = attachPtySocket(viewer, socket, options);
242
+ ```
243
+
244
+ Optional transport adapter in [web/pty-socket.js](../web/pty-socket.js) (re-exported from `"termigan"`). Connects a host-owned `WebSocket` (or compatible socket object) to the viewer's public API (`write`, `setRemoteSize`, `onInput`, `onResize`) without touching `createTermiganViewer` or taking ownership of socket lifecycle events.
245
+
246
+ ### Behavior
247
+
248
+ - Sets `socket.binaryType = "arraybuffer"` when writable.
249
+ - Registers its listener via `socket.addEventListener("message", ...)` and never overwrites `socket.onmessage`, leaving host listeners on `open`, `message`, `close`, and `error` intact.
250
+ - By default, binary frames (`ArrayBuffer`, `ArrayBufferView`, or `Blob`) forward to `viewer.write(...)`. String frames that parse as JSON `{ type: "size", cols, rows }` with positive finite numbers forward to `viewer.setRemoteSize(cols, rows)`. Other string frames forward to `viewer.write(data)`.
251
+ - Forwards `viewer.onInput(bytes)` to `socket.send(bytes)` and `viewer.onResize(cols, rows)` to `socket.send(encodeResize(cols, rows))` only while attached and `socket.readyState === OPEN`.
252
+ - Returns an idempotent `detach()` function that removes the `message`, `onInput`, and `onResize` listeners. `detach()` never calls `socket.close()`, and drops any in-flight `Blob` reads that resolve after detachment.
253
+
254
+ ### Options
255
+
256
+ | Option | Type | Default | Behavior |
257
+ |---|---|---|---|
258
+ | `bidirectional` | `boolean` | `true` | When `false`, skips `onInput` and `onResize` subscriptions so the viewer is read-only and never calls `socket.send`. |
259
+ | `decodeMessage` | `(data: unknown) => { type: "output", bytes } \| { type: "size", cols, rows } \| null \| undefined` | Default PTY decoder | Overrides inbound message decoding for custom protocols such as `ttyd` or Kubernetes exec. |
260
+ | `encodeResize` | `((cols: number, rows: number) => frame) \| null` | `(cols, rows) => JSON.stringify({ type: "resize", cols, rows })` | Encodes outbound `onResize` frames. Pass `null` to disable outbound resize messages. |
261
+
262
+ ## Custom element `<termigan-viewer>`
263
+
264
+ `TermiganViewerElement` extends `HTMLElement` and is registered as `<termigan-viewer>`.
265
+
266
+ ### Attributes
267
+
268
+ `connectedCallback()` reads these attributes once on element connection. Attribute mutations after connection are not observed.
269
+
270
+ | Attribute | Option mapped | Default | Parsing |
271
+ |---|---|---|---|
272
+ | `wasm-url` | `wasmUrl` | `new URL("../dist/termigan.wasm", import.meta.url)` | Raw attribute value, or default resolved relative to `web/termigan.js` when absent or empty. |
273
+ | `cols` | `cols` | `80` | `Number(attr) \|\| 80` |
274
+ | `rows` | `rows` | `24` | `Number(attr) \|\| 24` |
275
+ | `font-size` | `fontSize` | `13` | `Number(attr) \|\| 13` |
276
+
277
+ When connected, the element sets `style.display` to `"block"` if unset and sets `style.overflow` to `"hidden"`.
278
+
279
+ ### ready()
280
+
281
+ Returns the `Promise` started by `connectedCallback()`. The promise resolves to the `TermiganViewer` object returned by `createTermiganViewer`, or `null` if the element disconnects before initialization completes. Returns `null` if called before `connectedCallback()` or after `disconnectedCallback()`.
282
+
283
+ ### Example
284
+
285
+ ```html
286
+ <termigan-viewer id="pane" cols="80" rows="24" font-size="13"></termigan-viewer>
287
+ <script type="module">
288
+ import "termigan";
289
+
290
+ const el = document.getElementById("pane");
291
+ const viewer = await el.ready();
292
+ viewer.onInput((bytes) => console.log(bytes));
293
+ viewer.write("Ready\r\n");
294
+ </script>
295
+ ```
@@ -0,0 +1,102 @@
1
+ # Termigan architecture
2
+
3
+ Termigan separates terminal emulation from browser presentation and host policy. Pure Roc `0.1.0` code runs VT parsing, grid state, scrollback, line reflow, and byte encoding inside `dist/termigan.wasm`. That WebAssembly binary is 117,266 bytes and declares zero imports. A thin browser shell paints dirty rows onto a `<canvas>` and routes DOM events, while the host page controls transports, layout, and keybindings.
4
+
5
+ ## Four-layer boundary
6
+
7
+ Each layer communicates across an explicit boundary so terminal state never leaks into DOM code and browser policies never enter the VT engine.
8
+
9
+ ```text
10
+ Host Page (host/index.html, host/pty-server.py, or your application)
11
+ | layout, WebSockets, tabs, split panes, keybinding policy
12
+ v
13
+ Browser Shell (web/)
14
+ |-- web/termigan.js public API, DOM tree, ResizeObserver, Popover overlay
15
+ |-- web/viewport-controller.js mirror vs fit math, scrollback offset pinning
16
+ |-- web/input-controller.js focus state, IME gating, shouldHandleKey routing
17
+ |-- web/canvas-renderer.js 2D canvas painting, row cache, DPR and CSS scaling
18
+ |-- web/wasm-bridge.js WebAssembly module cache, byte staging, frame decoding
19
+ |
20
+ | 17 exported term_* functions over WASM linear memory
21
+ v
22
+ C99 Allocator Host and Roc Platform (platform/host.c, platform/main.roc)
23
+ |-- coalescing free-list allocator (roc_alloc, roc_realloc, roc_dealloc)
24
+ |-- 64-slot Box(Terminal) handle table and List(U8) staging buffers
25
+ |
26
+ | Box(Terminal) ownership transfer into pure functions
27
+ v
28
+ Pure Roc VT Engine (app/main.roc, core/)
29
+ |-- core/Parser.roc bounded UTF-8, CSI, ESC, and OSC parser
30
+ |-- core/Terminal.roc normal and alternate screens, scrollback, text extraction
31
+ |-- core/Reflow.roc logical line unwrap and rewrap across resize
32
+ |-- core/Modes.roc DEC private modes, cursor, mouse, bracketed paste
33
+ |-- core/KeyEncoder.roc mode-aware key, paste, mouse, and wheel encoders
34
+ |-- core/FrameCodec.roc binary dirty-row frame projection
35
+ ```
36
+
37
+ ### Host page
38
+
39
+ The host page owns every policy outside a single terminal stream. In the reference host, [host/index.html](../host/index.html) manages tabs, drag-resizable split panes, leader-key sequences, and one WebSocket connection per pane against [host/pty-server.py](../host/pty-server.py). Termigan enforces one viewer per stream, so closing a tab or splitting a pane never touches shared engine state.
40
+
41
+ ### Browser shell in `web/`
42
+
43
+ The modules in `web/` translate between browser DOM events and binary engine buffers.
44
+
45
+ - **[web/termigan.js](../web/termigan.js)** mounts `<div class="termigan-root">`, a `<canvas>`, and a hidden `<textarea class="termigan-input">`. It attaches `ResizeObserver`, batches frame flushes with `requestAnimationFrame`, handles word and line selection, and toggles full-window expansion with `popover="manual"` and `showPopover()`.
46
+ - **[web/viewport-controller.js](../web/viewport-controller.js)** implements `mirror` and `fit` size policies. In `mirror` mode, it keeps the remote columns and rows fixed and lowers the font size down to `minFontSize`. It then applies a CSS scale factor at or below `1` so outer scrollbars never appear, and it never emits `onResize`. It also adjusts `scrollOffset` as new normal-screen scrollback lines arrive so a scrolled-up reader stays pinned to the same lines.
47
+ - **[web/input-controller.js](../web/input-controller.js)** tracks three focus states, `unfocused`, `focused`, and `composing`. It enforces IME composition boundaries, suppresses stray `<textarea>` `input` events after host-claimed `keydown` events, and routes platform copy and paste shortcuts before VT encoding.
48
+ - **[web/canvas-renderer.js](../web/canvas-renderer.js)** caches decoded row arrays and repaints only dirty rows, cursor rows, and selection changes. CSS `transform: scale(...)` keeps the canvas's unscaled layout box and triggers parent scrollbars. Instead, `CanvasRenderer` sets `canvas.style.width` and `canvas.style.height` directly and keeps full device-pixel-ratio resolution on the canvas bitmap.
49
+ - **[web/wasm-bridge.js](../web/wasm-bridge.js)** compiles and caches `WebAssembly.Module` objects by URL and stages input bytes into linear memory through `term_alloc_in`. After a WebAssembly call returns, it copies `Uint8Array` bytes out from `term_out_ptr()` and releases them with `term_out_free()`.
50
+
51
+ ### C99 allocator host and Roc platform
52
+
53
+ The WebAssembly binary declares zero host imports and links [platform/host.c](../platform/host.c) with the Roc `0.1.0` object generated from [platform/main.roc](../platform/main.roc) and [app/main.roc](../app/main.roc).
54
+
55
+ [platform/host.c](../platform/host.c) compiles with `clang --target=wasm32 -Os -fno-builtin`. It implements a coalescing free-list heap from `__heap_base` onward with 16-byte minimum alignment and 3-argument `roc_realloc(ptr, new_size, alignment)`. The heap grows linear memory in blocks of at least four 64-KiB pages and tracks live allocated bytes for `term_live_bytes()`. A fixed 64-slot handle table stores active terminals and returns handles `1` through `64`.
56
+
57
+ ### Pure Roc VT engine
58
+
59
+ All modules in `core/` are pure Roc functions that compile both to WebAssembly through `app/main.roc` and natively under `roc test core/Layer2Tests.roc`:
60
+
61
+ - **[core/Parser.roc](../core/Parser.roc)** parses UTF-8 bytes, C0 controls, ESC sequences, CSI parameters capped at 16 parameters, and OSC strings capped at 4,096 bytes.
62
+ - **[core/Terminal.roc](../core/Terminal.roc)** applies parsed actions across the normal grid, scrollback buffer, and alternate screen. It also tracks DEC private modes, queues device-attribute and cursor-position replies, and extracts unwrapped text for selection copy.
63
+ - **[core/Reflow.roc](../core/Reflow.roc)** joins scrollback and grid rows on a normal-screen resize. It merges soft-wrapped rows into logical lines, rewraps them to the new column count, and maps the cursor into the new grid.
64
+ - **[core/KeyEncoder.roc](../core/KeyEncoder.roc)** encodes VT keys, bracketed paste payloads, SGR or legacy mouse events, and wheel events from active terminal `Modes`.
65
+ - **[core/FrameCodec.roc](../core/FrameCodec.roc)** encodes dirty rows and terminal flags into the binary render frame.
66
+
67
+ ## Why Box(Terminal) ownership transfer and binary frames
68
+
69
+ Two design choices keep the C host small and prevent WebAssembly boundary churn.
70
+
71
+ ### Ownership transfer instead of refcount headers in C
72
+
73
+ On creation, [platform/main.roc](../platform/main.roc) wraps the pure `Terminal` value with `Box.box`. On each call, `platform/host.c` passes that opaque `Box(Terminal)` pointer back into Roc. Roc calls `st.unbox()`, updates the value, and returns a new boxed pointer. Commands that return bytes return `StateAndBytes`, which matches Roc's `{ out : List(U8), state : Box(Terminal) }`.
74
+
75
+ Input and output `List(U8)` staging buffers are also allocated and freed inside Roc through `roc_alloc_bytes` and `roc_free_bytes`. C code never reads or writes Roc's internal reference-count headers. Because every `Box(Terminal)` and `List(U8)` keeps a reference count of `1`, Roc reuses allocations in place where possible, and `term_live_bytes()` returns to `0` after `dispose()`.
76
+
77
+ ### Binary dirty-row projection instead of draw callbacks or JSON
78
+
79
+ As recorded in [.agents/brain/decisions/0001-roc-wasm-architecture.md](../.agents/brain/decisions/0001-roc-wasm-architecture.md), Termigan rejected two common WebAssembly renderer designs:
80
+
81
+ 1. **Hosted canvas draw callbacks.** Importing JS fill and glyph callbacks into Roc would cross the WebAssembly boundary thousands of times when PTY output bursts. It would also tie stream parsing to browser paint timing and break pure `roc test` runs.
82
+ 2. **JSON state serialization.** Encoding the active screen and up to 10,000 scrollback rows as JSON would allocate and copy megabytes of state on each chunk.
83
+
84
+ Instead, `FrameCodec.encode_frame` writes one compact little-endian byte array per `requestAnimationFrame` flush, and `decodeFrame` in [web/wasm-bridge.js](../web/wasm-bridge.js) reads it with `DataView`:
85
+
86
+ - **36-byte header.** The header stores `cols`, `rows`, `cursorRow`, `cursorCol`, `scrollbackLen`, `scrollOffset`, `dirtyRowCount`, a mode flag byte, `cursorStyle`, two reserved bytes, and `titleSeq`. The mode flag byte packs `cursorVisible`, `altScreen`, `appCursorKeys`, `bracketedPaste`, `mouseActive`, and `sgrMouse`.
87
+ - **Dirty rows.** Only dirty rows follow the header unless the viewport is scrolled back or forced full. Each row uses `5 + cols * 16` bytes for a `U32` `rowIndex`, a `U8` wrap flag, and `cols` 16-byte cell records. Each cell record packs `cp`, a 4-byte foreground color, a 4-byte background color, `U16` attributes, `U8` width, and one padding byte.
88
+
89
+ ## Formally verified gateway models
90
+
91
+ Termigan models every component boundary as a state chart and verifies it in TLA+ with `everystate` before implementation crosses the boundary. All six formal models, their `.cfg` configurations, and their state charts live in [.agents/brain/models/](../.agents/brain/models/state-charts.md) and [PtySocketBridge.md](../.agents/brain/models/PtySocketBridge.md). The verification summaries from `everystate 0.4.6` live in [models-2026-12-02.md](../.agents/brain/verification/models-2026-12-02.md) and [pty-socket-bridge-2026-12-02.md](../.agents/brain/verification/pty-socket-bridge-2026-12-02.md).
92
+
93
+ | Gateway | TLA+ model | Generated states | Distinct states | Max depth | Checked invariants |
94
+ |---|---|---:|---:|---:|---|
95
+ | Gateway 1, VT parser | [.agents/brain/models/VtParser.tla](../.agents/brain/models/VtParser.tla) | 701 | 160 | 12 | `TypeOK`, `Utf8Consistency`, `GroundClearsBuffers`, `NoUnboundedAccumulation` |
96
+ | Gateway 2, Terminal screen | [.agents/brain/models/TerminalScreen.tla](../.agents/brain/models/TerminalScreen.tla) | 469,281 | 30,240 | 19 | `TypeOK`, `DimensionsPositive`, `CursorInBounds`, `ScrollRegionValid`, `ScrollbackBounded`, `AltPreservesNormal` |
97
+ | Gateway 3, WASM memory bridge | [.agents/brain/models/WasmMemoryBridge.tla](../.agents/brain/models/WasmMemoryBridge.tla) | 577 | 144 | 9 | `TypeOK`, `LiveBoxCountMatchesLifecycle`, `NoLeakedOutputAfterDispose` |
98
+ | Gateway 4, Viewport display | [.agents/brain/models/ViewportDisplay.tla](../.agents/brain/models/ViewportDisplay.tla) | 13,159 | 1,548 | 14 | `TypeOK`, `ScrollOffsetInRange`, `ExpandedNeverReconnects`, `MirrorNeverEmitsResize`, `AltScreenBlocksNormalScroll` |
99
+ | Gateway 5, Input routing | [.agents/brain/models/InputRouting.tla](../.agents/brain/models/InputRouting.tla) | 5,052 | 401 | 8 | `TypeOK`, `UnfocusedNeverCaptures`, `HostInterceptorWins`, `ComposingBlocksKeydown`, `SendKeyMatchesMode`, `PasteMatchesBracketedMode` |
100
+ | Gateway 6, PTY socket bridge | [.agents/brain/models/PtySocketBridge.tla](../.agents/brain/models/PtySocketBridge.tla) | 500 | 99 | 5 | `TypeOK`, `BridgeNeverClosesSocket`, `ListenersMatchState`, `NoEffectWhenDetached`, `SendRequiresOpenAndAttached`, `ReadOnlyNeverSends`, `ResizeDisabledNeverSendsResize` |
101
+
102
+ Run all six model checks locally with `make models`, which executes [scripts/verify-models.sh](../scripts/verify-models.sh).
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
- "name": "termigan",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "termigan",
3
+ "version": "0.0.1",
4
+ "description": "Standalone browser terminal viewer with a pure Roc WebAssembly VT core",
5
+ "license": "MIT",
6
+ "author": "Daniel Neighman",
7
+ "type": "module",
8
+ "main": "./web/termigan.js",
9
+ "module": "./web/termigan.js",
10
+ "types": "./types/index.d.ts",
11
+ "sideEffects": [
12
+ "./web/termigan.js"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "types": "./types/index.d.ts",
17
+ "import": "./web/termigan.js"
18
+ },
19
+ "./wasm": "./dist/termigan.wasm"
20
+ },
21
+ "files": [
22
+ "dist/termigan.wasm",
23
+ "web/termigan.js",
24
+ "web/wasm-bridge.js",
25
+ "web/canvas-renderer.js",
26
+ "web/viewport-controller.js",
27
+ "web/input-controller.js",
28
+ "web/pty-socket.js",
29
+ "types/index.d.ts",
30
+ "assets/logo.svg",
31
+ "README.md",
32
+ "LICENSE",
33
+ "docs/api.md",
34
+ "docs/architecture.md"
35
+ ],
36
+ "keywords": [
37
+ "terminal",
38
+ "vt100",
39
+ "ansi",
40
+ "wasm",
41
+ "webassembly",
42
+ "roc",
43
+ "canvas",
44
+ "pty"
45
+ ],
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/hassox/termigan.git"
49
+ },
50
+ "homepage": "https://github.com/hassox/termigan#readme",
51
+ "bugs": {
52
+ "url": "https://github.com/hassox/termigan/issues"
53
+ },
54
+ "engines": {
55
+ "node": ">=22"
56
+ },
57
+ "scripts": {
58
+ "build": "./scripts/build-wasm.sh",
59
+ "prepack": "./scripts/build-wasm.sh >&2",
60
+ "pack:check": "npm pack --dry-run",
61
+ "test": "make test"
62
+ }
63
+ }
@@ -0,0 +1,123 @@
1
+ export type TermiganWasmSource = string | URL | WebAssembly.Module | Uint8Array | ArrayBuffer;
2
+
3
+ export type TermiganSizeMode = "mirror" | "fit";
4
+
5
+ export type TermiganKeyDecision = "host" | "terminal";
6
+
7
+ export interface TermiganTheme {
8
+ background?: string;
9
+ foreground?: string;
10
+ cursor?: string;
11
+ cursorAccent?: string;
12
+ selection?: string;
13
+ scrollbarTrack?: string;
14
+ scrollbarThumb?: string;
15
+ palette?: string[];
16
+ }
17
+
18
+ export interface TermiganKeySpec {
19
+ key: string;
20
+ ctrl?: boolean;
21
+ alt?: boolean;
22
+ shift?: boolean;
23
+ meta?: boolean;
24
+ }
25
+
26
+ export interface TermiganOptions {
27
+ wasmUrl?: TermiganWasmSource;
28
+ cols?: number;
29
+ rows?: number;
30
+ scrollbackCap?: number;
31
+ fontSize?: number;
32
+ minFontSize?: number;
33
+ fontFamily?: string;
34
+ theme?: TermiganTheme;
35
+ isMac?: boolean;
36
+ shouldHandleKey?: (event: KeyboardEvent) => TermiganKeyDecision;
37
+ }
38
+
39
+ export interface TermiganSize {
40
+ cols: number;
41
+ rows: number;
42
+ }
43
+
44
+ export interface TermiganState {
45
+ cols: number;
46
+ rows: number;
47
+ sizeMode: TermiganSizeMode;
48
+ expanded: boolean;
49
+ scrollOffset: number;
50
+ scrollbackLen: number;
51
+ fontSize: number;
52
+ altScreen: boolean;
53
+ focused: boolean;
54
+ }
55
+
56
+ export type TermiganUnsubscribe = () => boolean;
57
+
58
+ export type TermiganDetach = () => void;
59
+
60
+ export type TermiganPtyMessage =
61
+ | { type: "output"; bytes: string | Uint8Array | ArrayBuffer | ArrayLike<number> }
62
+ | { type: "size"; cols: number; rows: number };
63
+
64
+ export interface TermiganPtySocket {
65
+ readonly readyState: number;
66
+ readonly OPEN?: number;
67
+ binaryType?: string;
68
+ addEventListener(type: "message", listener: (event: MessageEvent) => void): void;
69
+ removeEventListener(type: "message", listener: (event: MessageEvent) => void): void;
70
+ send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;
71
+ }
72
+
73
+ export interface TermiganPtySocketOptions {
74
+ bidirectional?: boolean;
75
+ decodeMessage?: (data: unknown) => TermiganPtyMessage | null | undefined;
76
+ encodeResize?: ((cols: number, rows: number) => string | ArrayBufferLike | ArrayBufferView | null | undefined) | null;
77
+ }
78
+
79
+ export function attachPtySocket(
80
+ viewer: Pick<TermiganViewer, "write" | "setRemoteSize" | "onInput" | "onResize">,
81
+ socket: TermiganPtySocket,
82
+ options?: TermiganPtySocketOptions,
83
+ ): TermiganDetach;
84
+
85
+ export interface TermiganViewer {
86
+ readonly element: HTMLDivElement;
87
+ write(bytes: string | Uint8Array | ArrayBuffer | ArrayLike<number>): void;
88
+ reset(): void;
89
+ scrollToBottom(): void;
90
+ setRemoteSize(cols: number, rows: number): void;
91
+ setSizeMode(mode: TermiganSizeMode): void;
92
+ setExpanded(expanded: boolean): void;
93
+ setKeyInterceptor(fn: ((event: KeyboardEvent) => TermiganKeyDecision) | null): void;
94
+ sendKey(keySpec: TermiganKeySpec): void;
95
+ proposeFitSize(): TermiganSize;
96
+ focus(): void;
97
+ blur(): void;
98
+ onInput(fn: (bytes: Uint8Array) => void): TermiganUnsubscribe;
99
+ onFocus(fn: () => void): TermiganUnsubscribe;
100
+ onBlur(fn: () => void): TermiganUnsubscribe;
101
+ onResize(fn: (cols: number, rows: number) => void): TermiganUnsubscribe;
102
+ onExpandedChange(fn: (expanded: boolean) => void): TermiganUnsubscribe;
103
+ onTitleChange(fn: (title: string) => void): TermiganUnsubscribe;
104
+ getSelectedText(): string;
105
+ getLastCopiedText(): string;
106
+ getState(): TermiganState;
107
+ dispose(): void;
108
+ }
109
+
110
+ export function createTermiganViewer(
111
+ container: HTMLElement,
112
+ options?: TermiganOptions,
113
+ ): Promise<TermiganViewer>;
114
+
115
+ export class TermiganViewerElement extends HTMLElement {
116
+ ready(): Promise<TermiganViewer | null> | null;
117
+ }
118
+
119
+ declare global {
120
+ interface HTMLElementTagNameMap {
121
+ "termigan-viewer": TermiganViewerElement;
122
+ }
123
+ }