@gjermundgaraba/clankermux 0.0.0-stage → 0.1.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.
@@ -0,0 +1,32 @@
1
+ import { isText } from "../engine/index.js";
2
+ /** Whether the browser keeps the key: its own shortcuts with the platform's
3
+ * command modifier, and Ctrl+Shift+V, the paste shortcut where Ctrl+V is
4
+ * the terminal's. */
5
+ export function browserKeeps(e) {
6
+ return e.metaKey || (e.ctrlKey && e.shiftKey && e.code === "KeyV");
7
+ }
8
+ export function keyInput(e, keyboard) {
9
+ const input = {
10
+ code: e.code,
11
+ key: e.key,
12
+ action: e.type === "keyup" ? "release" : e.repeat ? "repeat" : "press",
13
+ shift: e.shiftKey,
14
+ ctrl: e.ctrlKey,
15
+ alt: e.altKey,
16
+ meta: e.metaKey,
17
+ };
18
+ if (e.isComposing)
19
+ input.composing = true;
20
+ const unshifted = keyboard.layout?.get(e.code);
21
+ if (unshifted !== undefined)
22
+ input.unshifted = unshifted;
23
+ // Alt composed the text when it differs from the key's own character
24
+ // (Option on macOS, AltGr elsewhere). Without a layout to compare
25
+ // against, macOS Option composes and other platforms' Alt modifies.
26
+ if (e.altKey && isText(e.key)) {
27
+ const composed = unshifted !== undefined ? e.key.toLowerCase() !== unshifted.toLowerCase() : keyboard.mac;
28
+ if (composed)
29
+ input.altComposed = true;
30
+ }
31
+ return input;
32
+ }
@@ -0,0 +1,65 @@
1
+ /** The page side of a terminal: canvas, keyboard, paste and resize, with
2
+ * the engine in a worker running `runWorker`. */
3
+ import type { OnExit, Scheme, Session } from "../proto/index.ts";
4
+ import type { Link } from "./worker.ts";
5
+ /** The terminal's default colours as CSS colours (hex or `rgb()`). */
6
+ export interface Colors {
7
+ fg: string;
8
+ bg: string;
9
+ cursor: string;
10
+ }
11
+ export interface MountOptions {
12
+ /** A module worker whose script calls `runWorker(self)`; the terminal
13
+ * owns it from here. */
14
+ worker: Worker;
15
+ /** Drawn on; takes keys and paste while focused. */
16
+ canvas: HTMLCanvasElement;
17
+ /** The element whose size sets the grid. */
18
+ container: HTMLElement;
19
+ /** ghostty-vt.wasm, resolved against the page. */
20
+ wasm: string;
21
+ /** The server's WebSocket carrier, `wss://<node>:<port>/`. */
22
+ url: string;
23
+ /** The session to attach at once. */
24
+ session?: string | undefined;
25
+ /** A CSS font shorthand with its size in px. */
26
+ font: string;
27
+ /** Read again on every report. */
28
+ colors: () => Colors;
29
+ /** The colour scheme reported to the session; the page's preferred
30
+ * scheme by default. */
31
+ scheme?: () => Scheme;
32
+ /** A line of text for each change, for display. */
33
+ onStatus?: (text: string) => void;
34
+ /** Each change of the link to the session, to switch on. */
35
+ onLink?: (link: Link) => void;
36
+ onSessions?: (sessions: Session[], current: string | undefined) => void;
37
+ }
38
+ export interface CreateOptions {
39
+ /** `keep`: the session stays listed as `exited` when its program
40
+ * exits; `remove`: it is removed `limits.remove_grace` after. The
41
+ * server's default (`remove`) when absent. */
42
+ onExit?: OnExit;
43
+ }
44
+ export interface MountedTerminal {
45
+ /** Detaches the current session and attaches `session`. */
46
+ attach(session: string): void;
47
+ /** Creates a session at the current size and attaches it; resolves
48
+ * with it as created. Like `end` and `remove`, it needs a connection:
49
+ * call it after a `connected` link. */
50
+ create(options?: CreateOptions): Promise<Session>;
51
+ /** Hangs up the attached session's processes (SIGHUP); its exit
52
+ * follows as a link `ended` with reason `exited`. Resolves too when the
53
+ * session is not running (`exited` or `restored`). */
54
+ end(): Promise<void>;
55
+ /** Removes the attached session, which must be `exited` or `restored`
56
+ * (else `running`); the link ends with `removed`. */
57
+ remove(): Promise<void>;
58
+ /** Reports the container's size, the colours and the scheme again. */
59
+ report(): void;
60
+ paste(text: string): void;
61
+ /** Removes the listeners and terminates the worker, which ends its
62
+ * connection; requests in flight reject. */
63
+ dispose(): void;
64
+ }
65
+ export declare function mountTerminal(options: MountOptions): MountedTerminal;
@@ -0,0 +1,177 @@
1
+ import { CanvasRenderer } from "../renderer/index.js";
2
+ import { ClientError } from "./connection.js";
3
+ import { browserKeeps, keyInput } from "./keyboard.js";
4
+ import { profileFrom } from "./profile.js";
5
+ /** Cell metrics from the font. */
6
+ function measure(font) {
7
+ const ctx = document.createElement("canvas").getContext("2d");
8
+ ctx.font = font;
9
+ const m = ctx.measureText("M");
10
+ const size = Number(/(\d+(?:\.\d+)?)px/.exec(font)?.[1] ?? 14);
11
+ const ascent = m.fontBoundingBoxAscent || size * 0.8;
12
+ const descent = m.fontBoundingBoxDescent || size * 0.25;
13
+ return {
14
+ cellWidth: Math.ceil(m.width),
15
+ cellHeight: Math.ceil(ascent + descent),
16
+ baseline: Math.round(ascent),
17
+ font,
18
+ boldFont: `bold ${font}`,
19
+ italicFont: `italic ${font}`,
20
+ boldItalicFont: `bold italic ${font}`,
21
+ };
22
+ }
23
+ export function mountTerminal(options) {
24
+ const { worker, canvas, container, colors } = options;
25
+ const light = matchMedia("(prefers-color-scheme: light)");
26
+ const scheme = options.scheme ?? (() => (light.matches ? "light" : "dark"));
27
+ const metrics = measure(options.font);
28
+ const ctx = canvas.getContext("2d");
29
+ const renderer = new CanvasRenderer(ctx, metrics, { cursor: colors().cursor });
30
+ const dpr = () => window.devicePixelRatio || 1;
31
+ const listening = new AbortController();
32
+ const signal = listening.signal;
33
+ function viewport() {
34
+ const rect = container.getBoundingClientRect();
35
+ return {
36
+ cols: Math.max(1, Math.floor(rect.width / metrics.cellWidth)),
37
+ rows: Math.max(1, Math.floor(rect.height / metrics.cellHeight)),
38
+ cell_width: Math.round(metrics.cellWidth * dpr()),
39
+ cell_height: Math.round(metrics.cellHeight * dpr()),
40
+ };
41
+ }
42
+ /** The canvas backing store for the grid at the current pixel ratio;
43
+ * the next frame is drawn in full after a change. */
44
+ let grid = { cols: 0, rows: 0, dpr: 0 };
45
+ let fullNext = false;
46
+ function fitCanvas(cols, rows) {
47
+ const scale = dpr();
48
+ if (grid.cols === cols && grid.rows === rows && grid.dpr === scale)
49
+ return;
50
+ grid = { cols, rows, dpr: scale };
51
+ canvas.width = cols * metrics.cellWidth * scale;
52
+ canvas.height = rows * metrics.cellHeight * scale;
53
+ canvas.style.width = `${cols * metrics.cellWidth}px`;
54
+ canvas.style.height = `${rows * metrics.cellHeight}px`;
55
+ ctx.setTransform(scale, 0, 0, scale, 0, 0);
56
+ ctx.textBaseline = "alphabetic";
57
+ fullNext = true;
58
+ }
59
+ /** The keyboard layout, when the browser exposes it (Chromium does). */
60
+ const keyboard = { layout: undefined, mac: /Mac|iPhone|iPad/.test(navigator.platform) };
61
+ navigator.keyboard
62
+ ?.getLayoutMap()
63
+ .then((map) => (keyboard.layout = map))
64
+ .catch(() => { });
65
+ const send = (message) => worker.postMessage(message);
66
+ /** Requests waiting for their `done`, by id. They reject with a
67
+ * `ClientError` for a server's refusal, a lost connection or a
68
+ * disposed terminal, or an `Error` when no session is attached. */
69
+ const pending = new Map();
70
+ let nextId = 1;
71
+ let disposed = false;
72
+ function request(message) {
73
+ if (disposed)
74
+ return Promise.reject(new ClientError("closed", "disposed"));
75
+ const id = nextId++;
76
+ return new Promise((resolve, reject) => {
77
+ pending.set(id, { resolve, reject });
78
+ send(message(id));
79
+ });
80
+ }
81
+ const failure = (error) => error.kind ? new ClientError(error.kind, error.message, error.server) : new Error(error.message);
82
+ worker.onmessage = (e) => {
83
+ const message = e.data;
84
+ switch (message.type) {
85
+ case "status":
86
+ options.onStatus?.(message.text);
87
+ break;
88
+ case "link":
89
+ options.onLink?.(message.link);
90
+ break;
91
+ case "done": {
92
+ const waiter = pending.get(message.id);
93
+ pending.delete(message.id);
94
+ if (message.error)
95
+ waiter?.reject(failure(message.error));
96
+ else
97
+ waiter?.resolve(message.session);
98
+ break;
99
+ }
100
+ case "frame":
101
+ fitCanvas(message.frame.cols, message.frame.rows);
102
+ if (fullNext && !message.frame.full) {
103
+ // The backing store was recreated; a partial frame cannot fill it.
104
+ send({ type: "repaint" });
105
+ }
106
+ else {
107
+ fullNext = false;
108
+ renderer.draw(message.frame);
109
+ }
110
+ break;
111
+ case "sessions":
112
+ options.onSessions?.(message.sessions, message.current);
113
+ break;
114
+ case "clipboard":
115
+ navigator.clipboard?.writeText(message.text).catch(() => { });
116
+ break;
117
+ }
118
+ };
119
+ for (const type of ["keydown", "keyup"]) {
120
+ canvas.addEventListener(type, (e) => {
121
+ if (browserKeeps(e))
122
+ return;
123
+ send({ type: "key", input: keyInput(e, keyboard) });
124
+ e.preventDefault();
125
+ }, { signal });
126
+ }
127
+ canvas.addEventListener("paste", (e) => {
128
+ const text = e.clipboardData?.getData("text");
129
+ if (text)
130
+ send({ type: "paste", text });
131
+ e.preventDefault();
132
+ }, { signal });
133
+ canvas.addEventListener("mousedown", () => canvas.focus(), { signal });
134
+ const report = () => send({ type: "viewport", size: viewport(), profile: profileFrom(colors(), scheme()) });
135
+ const resizes = new ResizeObserver(report);
136
+ resizes.observe(container);
137
+ light.addEventListener("change", report, { signal });
138
+ // Zoom or a move to another screen changes the pixel ratio: the canvas
139
+ // is refitted on the next frame; the cell size in pixels is re-reported.
140
+ const watchRatio = () => {
141
+ matchMedia(`(resolution: ${dpr()}dppx)`).addEventListener("change", () => {
142
+ send({ type: "repaint" });
143
+ report();
144
+ watchRatio();
145
+ }, { once: true, signal });
146
+ };
147
+ watchRatio();
148
+ send({
149
+ type: "init",
150
+ wasm: new URL(options.wasm, location.href).toString(),
151
+ url: options.url,
152
+ viewport: viewport(),
153
+ profile: profileFrom(colors(), scheme()),
154
+ session: options.session,
155
+ });
156
+ return {
157
+ attach: (session) => send({ type: "attach", session }),
158
+ create: async (create) => {
159
+ const session = await request((id) => ({ type: "create", id, ...(create?.onExit && { onExit: create.onExit }) }));
160
+ return session;
161
+ },
162
+ end: async () => void (await request((id) => ({ type: "end", id }))),
163
+ remove: async () => void (await request((id) => ({ type: "remove", id }))),
164
+ report,
165
+ paste: (text) => send({ type: "paste", text }),
166
+ dispose: () => {
167
+ disposed = true;
168
+ listening.abort();
169
+ resizes.disconnect();
170
+ worker.onmessage = null;
171
+ worker.terminate();
172
+ for (const waiter of pending.values())
173
+ waiter.reject(new ClientError("closed", "disposed"));
174
+ pending.clear();
175
+ },
176
+ };
177
+ }
@@ -0,0 +1,14 @@
1
+ export interface ClipboardWrite {
2
+ /** The selection parameter: `c` or empty for the clipboard, `p`, `s`, `q` otherwise. */
3
+ selection: string;
4
+ text: string;
5
+ }
6
+ export declare class Osc52Scanner {
7
+ private state;
8
+ private payload;
9
+ /** Forgets a sequence in progress: the stream it came from is gone. */
10
+ reset(): void;
11
+ /** Feeds output bytes; returns the clipboard writes they completed. */
12
+ feed(bytes: Uint8Array): ClipboardWrite[];
13
+ private finish;
14
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Finds OSC 52 clipboard writes in output bytes, across chunk boundaries,
3
+ * ending them as the engine's parser does: BEL or any byte after ESC
4
+ * dispatches the sequence (ESC `\` is the string terminator; ESC `]`
5
+ * begins the next one), CAN and SUB abandon it. The engine raises the
6
+ * clipboard effect through a callback, which from wasm would need a JS
7
+ * function in the module's function table (a generated wrapper per
8
+ * signature); the scan is less machinery. OSC 1337 and 5522 clipboard
9
+ * forms are not scanned for, and an OSC 52 inside another string (a DCS
10
+ * passthrough) is taken as one, where the engine would not.
11
+ */
12
+ const ESC = 0x1b;
13
+ const BEL = 0x07;
14
+ const CAN = 0x18;
15
+ const SUB = 0x1a;
16
+ /** Longer OSC 52 payloads are abandoned, not buffered. */
17
+ const MAX_OSC = 1 << 20;
18
+ const PREFIX = "52;";
19
+ export class Osc52Scanner {
20
+ state = "text";
21
+ payload = [];
22
+ /** Forgets a sequence in progress: the stream it came from is gone. */
23
+ reset() {
24
+ this.state = "text";
25
+ this.payload = [];
26
+ }
27
+ /** Feeds output bytes; returns the clipboard writes they completed. */
28
+ feed(bytes) {
29
+ const writes = [];
30
+ for (const b of bytes) {
31
+ switch (this.state) {
32
+ case "text":
33
+ if (b === ESC)
34
+ this.state = "esc";
35
+ break;
36
+ case "esc":
37
+ // The payload is empty: every way out of an OSC clears it.
38
+ if (b === 0x5d)
39
+ this.state = "osc";
40
+ else
41
+ this.state = b === ESC ? "esc" : "text";
42
+ break;
43
+ case "osc":
44
+ case "skip":
45
+ if (b === BEL) {
46
+ this.finish(writes);
47
+ }
48
+ else if (b === ESC) {
49
+ this.finish(writes);
50
+ this.state = "esc";
51
+ }
52
+ else if (b === CAN || b === SUB) {
53
+ this.reset();
54
+ }
55
+ else if (this.state === "osc") {
56
+ this.payload.push(b);
57
+ const head = String.fromCharCode(...this.payload.slice(0, PREFIX.length));
58
+ if (!PREFIX.startsWith(head) || this.payload.length > MAX_OSC) {
59
+ this.state = "skip";
60
+ this.payload = [];
61
+ }
62
+ }
63
+ break;
64
+ }
65
+ }
66
+ return writes;
67
+ }
68
+ finish(writes) {
69
+ const collected = this.state === "osc";
70
+ const payload = new TextDecoder().decode(Uint8Array.from(this.payload));
71
+ this.reset();
72
+ if (!collected)
73
+ return;
74
+ const match = /^52;([^;]*);(.*)$/s.exec(payload);
75
+ if (!match || match[2] === "?")
76
+ return;
77
+ try {
78
+ writes.push({ selection: match[1], text: new TextDecoder().decode(base64(match[2])) });
79
+ }
80
+ catch {
81
+ // Not base64: ignored, as a terminal would.
82
+ }
83
+ }
84
+ }
85
+ function base64(text) {
86
+ const binary = atob(text.replace(/\s+/g, ""));
87
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
88
+ }
@@ -0,0 +1,10 @@
1
+ import type { Profile, Scheme } from "../proto/index.ts";
2
+ /** `#rrggbb` from a CSS colour as a custom property holds it (hex, or
3
+ * `rgb()` when the stylesheet writes it that way); undefined otherwise. */
4
+ export declare function hexColor(value: string): string | undefined;
5
+ /** The profile a page with these colours and scheme reports. */
6
+ export declare function profileFrom(colors: {
7
+ fg: string;
8
+ bg: string;
9
+ cursor: string;
10
+ }, scheme: Scheme): Profile;
@@ -0,0 +1,30 @@
1
+ /** `#rrggbb` from a CSS colour as a custom property holds it (hex, or
2
+ * `rgb()` when the stylesheet writes it that way); undefined otherwise. */
3
+ export function hexColor(value) {
4
+ const text = value.trim();
5
+ const hex = /^#([0-9a-f]{6})$/i.exec(text);
6
+ if (hex)
7
+ return `#${hex[1].toLowerCase()}`;
8
+ const short = /^#([0-9a-f]{3})$/i.exec(text);
9
+ if (short)
10
+ return `#${[...short[1]].map((c) => c + c).join("").toLowerCase()}`;
11
+ const rgb = /^rgba?\(\s*(\d+)\s*[, ]\s*(\d+)\s*[, ]\s*(\d+)/.exec(text);
12
+ if (!rgb)
13
+ return undefined;
14
+ const channel = (s) => Math.min(255, Number(s)).toString(16).padStart(2, "0");
15
+ return `#${channel(rgb[1])}${channel(rgb[2])}${channel(rgb[3])}`;
16
+ }
17
+ /** The profile a page with these colours and scheme reports. */
18
+ export function profileFrom(colors, scheme) {
19
+ const profile = { scheme };
20
+ const fg = hexColor(colors.fg);
21
+ const bg = hexColor(colors.bg);
22
+ const cursor = hexColor(colors.cursor);
23
+ if (fg)
24
+ profile.fg = fg;
25
+ if (bg)
26
+ profile.bg = bg;
27
+ if (cursor)
28
+ profile.cursor = cursor;
29
+ return profile;
30
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The engine side of a mounted terminal: the connection, the attachment
3
+ * and the render state live in a worker; the page draws frames and
4
+ * reports input. Imported as `@gjermundgaraba/clankermux/worker`, so a worker
5
+ * typechecked without the DOM library does not see the page's types.
6
+ */
7
+ import { type Frame, type KeyInput } from "../engine/index.ts";
8
+ import { type ErrorCode, type ErrorMessage, type Exit, type OnExit, type Profile, type Session, type Size } from "../proto/index.ts";
9
+ import { type ErrorKind } from "./connection.ts";
10
+ /** Why the link to the session ended. `closed`: the connection closed
11
+ * (not a `CLOSED` frame, which the worker does not wait for when it
12
+ * detaches); `removed` and `stopping`: the server's `CLOSED`; `exited`:
13
+ * the session's program exited; `no_such_session` and `engine_mismatch`:
14
+ * an `OPEN` refused; `error`: any other error, the server's or the
15
+ * client's own. */
16
+ export type LinkEnd = "closed" | "removed" | "stopping" | "exited" | "no_such_session" | "engine_mismatch" | "error";
17
+ /** The page's link to its session, through the connection and the
18
+ * attachment. */
19
+ export type Link =
20
+ /** Opening a connection; `attempt` counts from 1 and starts again once
21
+ * a server answers. */
22
+ {
23
+ state: "connecting";
24
+ attempt: number;
25
+ }
26
+ /** Connected, and showing `session` as `ATTACHED` described it (its
27
+ * `status` may be `restored` or `exited`), or attached to none. */
28
+ | {
29
+ state: "connected";
30
+ session: Session | undefined;
31
+ }
32
+ /** The link ended. `code` and `message` are the error's, when there is
33
+ * one; `exit` is the program's, for `exited`. `retry`: the worker
34
+ * reconnects or attaches again by itself, so `connecting` or
35
+ * `connected` follows; otherwise nothing does until the page attaches
36
+ * or creates. */
37
+ | {
38
+ state: "ended";
39
+ reason: LinkEnd;
40
+ code?: ErrorCode;
41
+ message?: string;
42
+ exit?: Exit;
43
+ retry: boolean;
44
+ };
45
+ /** A failed request, as it crosses to the page. */
46
+ export interface Failure {
47
+ /** Absent for a request that needs a session when none is attached. */
48
+ kind?: ErrorKind;
49
+ message: string;
50
+ server?: ErrorMessage;
51
+ }
52
+ /** Messages from the page to the worker. */
53
+ export type ToWorker = {
54
+ type: "init";
55
+ wasm: string;
56
+ url: string;
57
+ viewport: Size;
58
+ profile: Profile;
59
+ session: string | undefined;
60
+ } | {
61
+ type: "attach";
62
+ session: string;
63
+ }
64
+ /** Each request is answered by a `done` with its `id`. */
65
+ | {
66
+ type: "create";
67
+ id: number;
68
+ onExit?: OnExit;
69
+ } | {
70
+ type: "end";
71
+ id: number;
72
+ } | {
73
+ type: "remove";
74
+ id: number;
75
+ } | {
76
+ type: "key";
77
+ input: KeyInput;
78
+ } | {
79
+ type: "paste";
80
+ text: string;
81
+ } | {
82
+ type: "viewport";
83
+ size: Size;
84
+ profile: Profile;
85
+ }
86
+ /** The page lost its drawing: send the whole screen again. */
87
+ | {
88
+ type: "repaint";
89
+ };
90
+ /** Messages from the worker to the page. */
91
+ export type ToPage = {
92
+ type: "status";
93
+ text: string;
94
+ } | {
95
+ type: "link";
96
+ link: Link;
97
+ } | {
98
+ type: "done";
99
+ id: number;
100
+ session?: Session;
101
+ error?: Failure;
102
+ } | {
103
+ type: "frame";
104
+ frame: Frame;
105
+ } | {
106
+ type: "sessions";
107
+ sessions: Session[];
108
+ current: string | undefined;
109
+ } | {
110
+ type: "clipboard";
111
+ text: string;
112
+ };
113
+ /** The worker's end of the page's messages: `self` in a dedicated worker. */
114
+ export interface WorkerPort {
115
+ postMessage(message: ToPage): void;
116
+ onmessage: ((e: MessageEvent<ToWorker>) => void) | null;
117
+ }
118
+ /** Serves a page's `mountTerminal` on `port`: the worker module the page
119
+ * starts calls `runWorker(self)`. */
120
+ export declare function runWorker(port: WorkerPort): void;