herdview 0.0.0-stage → 0.1.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 +128 -2
- package/index.js +783 -0
- package/json-lines.js +1 -0
- package/package.json +32 -4
package/README.md
CHANGED
|
@@ -1,3 +1,129 @@
|
|
|
1
|
-
#
|
|
1
|
+
# herdview
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`herdview` is a framework-independent ES module for embedding herdr terminals. It owns the WebSocket protocol and ghostty-web lifecycle; the host application owns all UI.
|
|
4
|
+
|
|
5
|
+
- `HerdConnection`: token-authenticated WebSocket, RPC, automatic reconnect, `terminal.list`, event subscription, incremental JSON-lines parsing, frame codec, and CREDIT backpressure.
|
|
6
|
+
- `HerdView`: one mountable terminal with attach, observe mode, keyboard input, resize/focus reporting, and lifecycle events.
|
|
7
|
+
- One connection can drive any number of views. No sidebar, terminal list, status indicator, or other application UI is included.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install herdview ghostty-web
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Use a bundler with the bare `herdview` and `ghostty-web` imports, or serve both packages and provide an import map:
|
|
16
|
+
|
|
17
|
+
```html
|
|
18
|
+
<script type="importmap">
|
|
19
|
+
{
|
|
20
|
+
"imports": {
|
|
21
|
+
"herdview": "/node_modules/herdview/index.js",
|
|
22
|
+
"ghostty-web": "/node_modules/ghostty-web/dist/ghostty-web.js"
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
</script>
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The ghostty WASM file must also be served at `/node_modules/ghostty-web/ghostty-vt.wasm` for that mapping.
|
|
29
|
+
|
|
30
|
+
## Minimal example
|
|
31
|
+
|
|
32
|
+
```js
|
|
33
|
+
import { HerdConnection, HerdView } from 'herdview';
|
|
34
|
+
|
|
35
|
+
const connection = new HerdConnection({
|
|
36
|
+
url: `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws`,
|
|
37
|
+
token: window.__TOKEN__,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const view = new HerdView(connection, {
|
|
41
|
+
terminalOptions: { fontSize: 14, scrollback: 10000 },
|
|
42
|
+
history: 500,
|
|
43
|
+
}).mount(document.querySelector('#terminal'));
|
|
44
|
+
|
|
45
|
+
view.on('title', ({ title }) => {
|
|
46
|
+
document.title = title;
|
|
47
|
+
});
|
|
48
|
+
view.on('closed', ({ reason, exit_code }) => {
|
|
49
|
+
console.log('terminal closed', reason, exit_code);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
await connection.connect();
|
|
53
|
+
await view.attach('t1');
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The mount element is owned by the view while attached. Mount before calling `attach()`.
|
|
57
|
+
|
|
58
|
+
## HerdConnection
|
|
59
|
+
|
|
60
|
+
```js
|
|
61
|
+
const connection = new HerdConnection({
|
|
62
|
+
url: 'ws://localhost:8787/ws',
|
|
63
|
+
token: 'secret',
|
|
64
|
+
reconnect: true,
|
|
65
|
+
reconnectDelay: 500,
|
|
66
|
+
maxReconnectDelay: 10000,
|
|
67
|
+
rpcTimeout: 20000,
|
|
68
|
+
});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`connect()` resolves after the gateway handshake, event subscription, and initial `terminal.list({ all: true })`. Reconnects automatically repeat that initialization. `whenReady()` waits for the current connection cycle.
|
|
72
|
+
|
|
73
|
+
- `terminals`: current terminal records as a new array.
|
|
74
|
+
- `getTerminal(address)`: one current record.
|
|
75
|
+
- `listTerminals({ all, labels })`: refresh and return terminal records.
|
|
76
|
+
- `rpc(method, params)`: call another herdr RPC method.
|
|
77
|
+
- `on(type, listener)`: subscribe; returns an unsubscribe function.
|
|
78
|
+
- `destroy()`: stop reconnecting, close streams, and release listeners.
|
|
79
|
+
|
|
80
|
+
Connection events:
|
|
81
|
+
|
|
82
|
+
- `status`: `{ state, attempt, ... }`, where state is `connecting`, `connected`, `ready`, `disconnected`, `reconnecting`, or `destroyed`.
|
|
83
|
+
- `ready`: `{ terminals }` after every successful initialization.
|
|
84
|
+
- `terminals`: `{ terminals }` after snapshots or terminal events.
|
|
85
|
+
- `event`: raw `event` notification params.
|
|
86
|
+
- `missed`: raw snapshot notification params after the local snapshot is replaced.
|
|
87
|
+
- `error`: `{ error }` for socket or initialization errors.
|
|
88
|
+
|
|
89
|
+
## HerdView
|
|
90
|
+
|
|
91
|
+
```js
|
|
92
|
+
const view = new HerdView(connection, {
|
|
93
|
+
terminalOptions: {},
|
|
94
|
+
history: 500,
|
|
95
|
+
autoFocus: true,
|
|
96
|
+
autoResize: true,
|
|
97
|
+
});
|
|
98
|
+
view.mount(element);
|
|
99
|
+
await view.attach(address, { observe: false });
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
- `attach(address, { observe })`: attach and render first paint plus live output. Active attachments are re-established after reconnect.
|
|
103
|
+
- `setObserve(value)`: reattach the current terminal in viewer or observer mode.
|
|
104
|
+
- `write(data)`: send keyboard-equivalent input; returns `false` in observe mode or while inactive.
|
|
105
|
+
- `focus()`: focus the terminal and report focus for a viewer.
|
|
106
|
+
- `detach()`: close the attachment and dispose the renderer without destroying the connection.
|
|
107
|
+
- `destroy()`: permanently release the view, renderer, connection listener, and window listeners.
|
|
108
|
+
- `on(type, listener)`: subscribe; returns an unsubscribe function.
|
|
109
|
+
- `active`, `address`, `observe`, `terminal`: current view state.
|
|
110
|
+
|
|
111
|
+
View events:
|
|
112
|
+
|
|
113
|
+
- `status`: `{ state, address, observe, ... }`; states include `attaching`, `attached`, `reconnecting`, `closed`, `detached`, `error`, and `destroyed`.
|
|
114
|
+
- `title`: `{ title }` from terminal OSC title changes.
|
|
115
|
+
- `closed`: decoded close payload, usually `{ reason, exit_code }`.
|
|
116
|
+
- `resize`: `{ cols, rows }` from ghostty-web.
|
|
117
|
+
- `focus`: `{ focused }` when a viewer reports focus or blur.
|
|
118
|
+
- `error`: `{ error }` if automatic reattachment fails.
|
|
119
|
+
|
|
120
|
+
Observers never send input, RESIZE, or FOCUS frames. DATA is credited only after it is delivered to the terminal renderer. All protocol framing and JSON-lines boundaries are handled internally.
|
|
121
|
+
|
|
122
|
+
## Development
|
|
123
|
+
|
|
124
|
+
```sh
|
|
125
|
+
npm test
|
|
126
|
+
npm run check
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
`test/browser-check.cjs` is an optional consumer smoke test for a running herdgate instance. It requires Playwright and uses `HERDVIEW_URL` (default `http://127.0.0.1:8795/`) and `HERDVIEW_SCREENSHOT`. Set `PLAYWRIGHT_MODULE` when Playwright is installed outside the project.
|
package/index.js
ADDED
|
@@ -0,0 +1,783 @@
|
|
|
1
|
+
import { init, Terminal, FitAddon } from 'ghostty-web';
|
|
2
|
+
|
|
3
|
+
const DATA = 0;
|
|
4
|
+
const CREDIT = 1;
|
|
5
|
+
const CLOSE = 2;
|
|
6
|
+
const RESIZE = 3;
|
|
7
|
+
const FOCUS = 4;
|
|
8
|
+
const EMPTY = new Uint8Array(0);
|
|
9
|
+
const encoder = new TextEncoder();
|
|
10
|
+
const decoder = new TextDecoder();
|
|
11
|
+
|
|
12
|
+
class Emitter {
|
|
13
|
+
constructor() {
|
|
14
|
+
this.listeners = new Map();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
on(type, listener) {
|
|
18
|
+
if (typeof listener !== 'function') throw new TypeError('listener must be a function');
|
|
19
|
+
let listeners = this.listeners.get(type);
|
|
20
|
+
if (!listeners) {
|
|
21
|
+
listeners = new Set();
|
|
22
|
+
this.listeners.set(type, listeners);
|
|
23
|
+
}
|
|
24
|
+
listeners.add(listener);
|
|
25
|
+
return () => {
|
|
26
|
+
listeners.delete(listener);
|
|
27
|
+
if (!listeners.size) this.listeners.delete(type);
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
emit(type, detail) {
|
|
32
|
+
for (const listener of [...(this.listeners.get(type) || [])]) listener(detail);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
clear() {
|
|
36
|
+
this.listeners.clear();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const deferred = () => {
|
|
41
|
+
let resolve;
|
|
42
|
+
let reject;
|
|
43
|
+
const promise = new Promise((res, rej) => {
|
|
44
|
+
resolve = res;
|
|
45
|
+
reject = rej;
|
|
46
|
+
});
|
|
47
|
+
return { promise, resolve, reject };
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const asBytes = (value) => {
|
|
51
|
+
if (value instanceof Uint8Array) return value;
|
|
52
|
+
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
|
53
|
+
if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
54
|
+
throw new TypeError('expected an ArrayBuffer or typed array');
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export function createJsonLineParser(onLine) {
|
|
58
|
+
const textDecoder = new TextDecoder();
|
|
59
|
+
let pending = '';
|
|
60
|
+
|
|
61
|
+
return (chunk) => {
|
|
62
|
+
pending += textDecoder.decode(chunk, { stream: true });
|
|
63
|
+
let newline;
|
|
64
|
+
while ((newline = pending.indexOf('\n')) !== -1) {
|
|
65
|
+
const line = pending.slice(0, newline);
|
|
66
|
+
if (line.trim()) onLine(line);
|
|
67
|
+
pending = pending.slice(newline + 1);
|
|
68
|
+
}
|
|
69
|
+
if (pending.trim()) {
|
|
70
|
+
try {
|
|
71
|
+
JSON.parse(pending);
|
|
72
|
+
onLine(pending);
|
|
73
|
+
pending = '';
|
|
74
|
+
} catch {}
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function encodeFrame(channel, kind, payload = EMPTY) {
|
|
80
|
+
const bytes = asBytes(payload);
|
|
81
|
+
const output = new Uint8Array(9 + bytes.byteLength);
|
|
82
|
+
const view = new DataView(output.buffer);
|
|
83
|
+
view.setUint32(0, channel, true);
|
|
84
|
+
view.setUint8(4, kind);
|
|
85
|
+
view.setUint32(5, bytes.byteLength, true);
|
|
86
|
+
output.set(bytes, 9);
|
|
87
|
+
return output;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function decodeFrame(input) {
|
|
91
|
+
const bytes = asBytes(input);
|
|
92
|
+
if (bytes.byteLength < 9) return null;
|
|
93
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
94
|
+
const length = view.getUint32(5, true);
|
|
95
|
+
if (length !== bytes.byteLength - 9) return null;
|
|
96
|
+
return {
|
|
97
|
+
channel: view.getUint32(0, true),
|
|
98
|
+
kind: view.getUint8(4),
|
|
99
|
+
payload: bytes.subarray(9),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function encodeCredit(bytes) {
|
|
104
|
+
const output = new Uint8Array(4);
|
|
105
|
+
new DataView(output.buffer).setUint32(0, bytes, true);
|
|
106
|
+
return output;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function encodeResize(cols, rows) {
|
|
110
|
+
const output = new Uint8Array(4);
|
|
111
|
+
const view = new DataView(output.buffer);
|
|
112
|
+
view.setUint16(0, cols, true);
|
|
113
|
+
view.setUint16(2, rows, true);
|
|
114
|
+
return output;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function webSocketUrl(url, token) {
|
|
118
|
+
const result = new URL(url, globalThis.location?.origin);
|
|
119
|
+
if (token != null) result.searchParams.set('token', token);
|
|
120
|
+
return result.href;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const closeReason = (payload) => {
|
|
124
|
+
if (!payload.byteLength) return null;
|
|
125
|
+
try {
|
|
126
|
+
return JSON.parse(decoder.decode(payload));
|
|
127
|
+
} catch {
|
|
128
|
+
return { reason: decoder.decode(payload) };
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const terminalArray = (result) => {
|
|
133
|
+
if (Array.isArray(result)) return result;
|
|
134
|
+
return Array.isArray(result?.terminals) ? result.terminals : [];
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
export class HerdConnection {
|
|
138
|
+
constructor({
|
|
139
|
+
url,
|
|
140
|
+
token,
|
|
141
|
+
WebSocket: WebSocketClass = globalThis.WebSocket,
|
|
142
|
+
reconnect = true,
|
|
143
|
+
reconnectDelay = 500,
|
|
144
|
+
maxReconnectDelay = 10000,
|
|
145
|
+
rpcTimeout = 20000,
|
|
146
|
+
} = {}) {
|
|
147
|
+
if (!url) throw new TypeError('url is required');
|
|
148
|
+
if (!WebSocketClass) throw new TypeError('WebSocket is unavailable');
|
|
149
|
+
this.url = url;
|
|
150
|
+
this.token = token;
|
|
151
|
+
this.state = 'idle';
|
|
152
|
+
this.reconnect = reconnect;
|
|
153
|
+
this.reconnectDelay = reconnectDelay;
|
|
154
|
+
this.maxReconnectDelay = maxReconnectDelay;
|
|
155
|
+
this.rpcTimeout = rpcTimeout;
|
|
156
|
+
this.WebSocketClass = WebSocketClass;
|
|
157
|
+
this.emitter = new Emitter();
|
|
158
|
+
this.records = new Map();
|
|
159
|
+
this.pending = new Map();
|
|
160
|
+
this.attachments = new Map();
|
|
161
|
+
this.parsers = new Map();
|
|
162
|
+
this.nextId = 1;
|
|
163
|
+
this.socket = null;
|
|
164
|
+
this.gatewayReady = false;
|
|
165
|
+
this.started = false;
|
|
166
|
+
this.destroyed = false;
|
|
167
|
+
this.attempt = 0;
|
|
168
|
+
this.reconnectTimer = null;
|
|
169
|
+
this.eventsChannel = null;
|
|
170
|
+
this.firstReady = deferred();
|
|
171
|
+
this.cycle = deferred();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
on(type, listener) {
|
|
175
|
+
return this.emitter.on(type, listener);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
get terminals() {
|
|
179
|
+
return [...this.records.values()];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
getTerminal(address) {
|
|
183
|
+
return this.records.get(address);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
connect() {
|
|
187
|
+
if (this.destroyed) return Promise.reject(new Error('connection destroyed'));
|
|
188
|
+
if (!this.started) {
|
|
189
|
+
this.started = true;
|
|
190
|
+
this.openSocket();
|
|
191
|
+
}
|
|
192
|
+
return this.firstReady.promise;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
whenReady() {
|
|
196
|
+
if (this.state === 'ready') return Promise.resolve(true);
|
|
197
|
+
return this.cycle.promise;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
setState(state, detail = {}) {
|
|
201
|
+
this.state = state;
|
|
202
|
+
this.emitter.emit('status', { state, attempt: this.attempt, ...detail });
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
openSocket() {
|
|
206
|
+
if (!this.started || this.destroyed) return;
|
|
207
|
+
clearTimeout(this.reconnectTimer);
|
|
208
|
+
this.reconnectTimer = null;
|
|
209
|
+
const reconnecting = this.state === 'reconnecting';
|
|
210
|
+
this.attempt += 1;
|
|
211
|
+
this.cycle = deferred();
|
|
212
|
+
this.gatewayReady = false;
|
|
213
|
+
this.parsers.clear();
|
|
214
|
+
this.eventsChannel = null;
|
|
215
|
+
this.setState(reconnecting ? 'reconnecting' : 'connecting');
|
|
216
|
+
|
|
217
|
+
let socket;
|
|
218
|
+
try {
|
|
219
|
+
socket = new this.WebSocketClass(webSocketUrl(this.url, this.token));
|
|
220
|
+
} catch (error) {
|
|
221
|
+
this.emitter.emit('error', { error });
|
|
222
|
+
this.cycle.resolve(false);
|
|
223
|
+
this.scheduleReconnect();
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
this.socket = socket;
|
|
227
|
+
socket.binaryType = 'arraybuffer';
|
|
228
|
+
socket.onopen = () => {
|
|
229
|
+
if (this.socket === socket) this.setState('connected');
|
|
230
|
+
};
|
|
231
|
+
socket.onerror = (event) => {
|
|
232
|
+
if (this.socket === socket) this.emitter.emit('error', { error: event });
|
|
233
|
+
};
|
|
234
|
+
socket.onmessage = (event) => {
|
|
235
|
+
if (this.socket !== socket) return;
|
|
236
|
+
if (typeof event.data === 'string') this.handleText(socket, event.data);
|
|
237
|
+
else this.handleBinary(socket, event.data);
|
|
238
|
+
};
|
|
239
|
+
socket.onclose = (event) => {
|
|
240
|
+
if (this.socket === socket) this.handleClose(socket, event);
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
handleText(socket, text) {
|
|
245
|
+
let message;
|
|
246
|
+
try {
|
|
247
|
+
message = JSON.parse(text);
|
|
248
|
+
} catch {
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (message.type === 'gateway' && message.event === 'ready' && !this.gatewayReady) {
|
|
252
|
+
this.gatewayReady = true;
|
|
253
|
+
this.initialize(socket).catch((error) => {
|
|
254
|
+
if (this.socket !== socket) return;
|
|
255
|
+
this.emitter.emit('error', { error });
|
|
256
|
+
socket.close();
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async initialize(socket) {
|
|
262
|
+
const subscription = await this.rpcNow('events.subscribe', {});
|
|
263
|
+
if (this.socket !== socket) return;
|
|
264
|
+
this.eventsChannel = subscription?.channel ?? null;
|
|
265
|
+
const listed = await this.rpcNow('terminal.list', { all: true });
|
|
266
|
+
if (this.socket !== socket) return;
|
|
267
|
+
this.replaceTerminals(terminalArray(listed), false);
|
|
268
|
+
this.setState('ready');
|
|
269
|
+
this.attempt = 0;
|
|
270
|
+
this.cycle.resolve(true);
|
|
271
|
+
this.firstReady.resolve(true);
|
|
272
|
+
this.emitter.emit('terminals', { terminals: this.terminals });
|
|
273
|
+
this.emitter.emit('ready', { terminals: this.terminals });
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
handleClose(socket, event = {}) {
|
|
277
|
+
if (this.socket !== socket) return;
|
|
278
|
+
this.socket = null;
|
|
279
|
+
this.gatewayReady = false;
|
|
280
|
+
this.eventsChannel = null;
|
|
281
|
+
this.rejectPending(new Error('connection closed'));
|
|
282
|
+
this.dropAttachments();
|
|
283
|
+
this.cycle.resolve(false);
|
|
284
|
+
const detail = { code: event.code, reason: event.reason || '' };
|
|
285
|
+
this.setState('disconnected', detail);
|
|
286
|
+
this.scheduleReconnect(detail);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
scheduleReconnect(detail = {}) {
|
|
290
|
+
if (!this.started || this.destroyed) return;
|
|
291
|
+
if (!this.reconnect) {
|
|
292
|
+
this.firstReady.resolve(false);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
const delay = Math.min(
|
|
296
|
+
this.maxReconnectDelay,
|
|
297
|
+
this.reconnectDelay * 2 ** Math.max(0, this.attempt - 1),
|
|
298
|
+
);
|
|
299
|
+
this.setState('reconnecting', { ...detail, delay });
|
|
300
|
+
this.reconnectTimer = setTimeout(() => this.openSocket(), delay);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
rejectPending(error) {
|
|
304
|
+
for (const request of this.pending.values()) {
|
|
305
|
+
clearTimeout(request.timer);
|
|
306
|
+
request.reject(error);
|
|
307
|
+
}
|
|
308
|
+
this.pending.clear();
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
dropAttachments() {
|
|
312
|
+
const attachments = [...this.attachments.values()];
|
|
313
|
+
this.attachments.clear();
|
|
314
|
+
for (const attachment of attachments) {
|
|
315
|
+
attachment.open = false;
|
|
316
|
+
attachment.onDisconnect?.();
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async rpc(method, params = {}) {
|
|
321
|
+
if (this.destroyed) throw new Error('connection destroyed');
|
|
322
|
+
if (!this.started) this.connect();
|
|
323
|
+
if (this.state !== 'ready') {
|
|
324
|
+
const ready = await this.cycle.promise;
|
|
325
|
+
if (!ready || this.state !== 'ready') throw new Error('connection is not ready');
|
|
326
|
+
}
|
|
327
|
+
return this.rpcNow(method, params);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
rpcNow(method, params) {
|
|
331
|
+
const socket = this.socket;
|
|
332
|
+
if (!socket || socket.readyState !== 1 || !this.gatewayReady) {
|
|
333
|
+
return Promise.reject(new Error('connection is not ready'));
|
|
334
|
+
}
|
|
335
|
+
return new Promise((resolve, reject) => {
|
|
336
|
+
const id = this.nextId++;
|
|
337
|
+
const timer = setTimeout(() => {
|
|
338
|
+
if (!this.pending.has(id)) return;
|
|
339
|
+
this.pending.delete(id);
|
|
340
|
+
reject(new Error(`RPC timeout: ${method}`));
|
|
341
|
+
}, this.rpcTimeout);
|
|
342
|
+
this.pending.set(id, { resolve, reject, timer, method });
|
|
343
|
+
try {
|
|
344
|
+
socket.send(JSON.stringify({ jsonrpc: '2.0', id, method, params }));
|
|
345
|
+
} catch (error) {
|
|
346
|
+
clearTimeout(timer);
|
|
347
|
+
this.pending.delete(id);
|
|
348
|
+
reject(error);
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
handleBinary(socket, input) {
|
|
354
|
+
let frame;
|
|
355
|
+
try {
|
|
356
|
+
frame = decodeFrame(input);
|
|
357
|
+
} catch {
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if (!frame) return;
|
|
361
|
+
const { channel, kind, payload } = frame;
|
|
362
|
+
const attachment = this.attachments.get(channel);
|
|
363
|
+
if (attachment) {
|
|
364
|
+
if (kind === DATA) {
|
|
365
|
+
try {
|
|
366
|
+
attachment.onData(payload);
|
|
367
|
+
} finally {
|
|
368
|
+
this.sendFrame(channel, CREDIT, encodeCredit(payload.byteLength), socket);
|
|
369
|
+
}
|
|
370
|
+
} else if (kind === CLOSE) {
|
|
371
|
+
this.attachments.delete(channel);
|
|
372
|
+
attachment.open = false;
|
|
373
|
+
attachment.onClose?.(closeReason(payload));
|
|
374
|
+
}
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
if (kind !== DATA) return;
|
|
378
|
+
let parse = this.parsers.get(channel);
|
|
379
|
+
if (!parse) {
|
|
380
|
+
parse = createJsonLineParser((line) => this.handleJsonLine(line));
|
|
381
|
+
this.parsers.set(channel, parse);
|
|
382
|
+
}
|
|
383
|
+
try {
|
|
384
|
+
parse(payload);
|
|
385
|
+
} finally {
|
|
386
|
+
this.sendFrame(channel, CREDIT, encodeCredit(payload.byteLength), socket);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
handleJsonLine(line) {
|
|
391
|
+
if (!line.trim()) return;
|
|
392
|
+
let message;
|
|
393
|
+
try {
|
|
394
|
+
message = JSON.parse(line);
|
|
395
|
+
} catch {
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
if (message.id != null) {
|
|
399
|
+
const request = this.pending.get(message.id);
|
|
400
|
+
if (!request) return;
|
|
401
|
+
this.pending.delete(message.id);
|
|
402
|
+
clearTimeout(request.timer);
|
|
403
|
+
if (message.error) {
|
|
404
|
+
request.reject(new Error(message.error.message || JSON.stringify(message.error)));
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
this.rememberResult(message.result);
|
|
408
|
+
request.resolve(message.result);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (message.method) this.handleNotification(message);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
rememberResult(result) {
|
|
415
|
+
if (result?.address) this.records.set(result.address, result);
|
|
416
|
+
if (result?.terminal?.address) this.records.set(result.terminal.address, result.terminal);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
handleNotification(message) {
|
|
420
|
+
if (message.method === 'missed') {
|
|
421
|
+
this.replaceTerminals(message.params?.terminals || []);
|
|
422
|
+
this.emitter.emit('missed', message.params);
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
if (message.method !== 'event') return;
|
|
426
|
+
this.applyEvent(message.params || {});
|
|
427
|
+
this.emitter.emit('event', message.params);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
replaceTerminals(terminals, notify = true) {
|
|
431
|
+
this.records.clear();
|
|
432
|
+
for (const terminal of terminals) {
|
|
433
|
+
if (terminal?.address) this.records.set(terminal.address, terminal);
|
|
434
|
+
}
|
|
435
|
+
if (notify) this.emitter.emit('terminals', { terminals: this.terminals });
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
applyEvent(event) {
|
|
439
|
+
const terminal = this.records.get(event.terminal);
|
|
440
|
+
const data = event.data || {};
|
|
441
|
+
switch (event.type) {
|
|
442
|
+
case 'created':
|
|
443
|
+
case 'restarted':
|
|
444
|
+
this.records.set(event.terminal, data);
|
|
445
|
+
break;
|
|
446
|
+
case 'removed':
|
|
447
|
+
this.records.delete(event.terminal);
|
|
448
|
+
break;
|
|
449
|
+
case 'labels':
|
|
450
|
+
if (terminal) {
|
|
451
|
+
terminal.labels = data.labels;
|
|
452
|
+
if (data.record) this.records.set(event.terminal, data.record);
|
|
453
|
+
}
|
|
454
|
+
break;
|
|
455
|
+
case 'finished':
|
|
456
|
+
if (terminal) Object.assign(terminal, data, { state: 'finished' });
|
|
457
|
+
break;
|
|
458
|
+
case 'lost':
|
|
459
|
+
case 'keep':
|
|
460
|
+
case 'status':
|
|
461
|
+
case 'turn':
|
|
462
|
+
case 'title':
|
|
463
|
+
case 'size':
|
|
464
|
+
if (terminal) Object.assign(terminal, data);
|
|
465
|
+
break;
|
|
466
|
+
case 'foreground':
|
|
467
|
+
if (terminal) terminal.foreground = data;
|
|
468
|
+
break;
|
|
469
|
+
}
|
|
470
|
+
this.emitter.emit('terminals', { terminals: this.terminals });
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
async listTerminals({ all = true, labels = {} } = {}) {
|
|
474
|
+
const result = await this.rpc('terminal.list', { all, labels });
|
|
475
|
+
this.replaceTerminals(terminalArray(result));
|
|
476
|
+
return this.terminals;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
sendFrame(channel, kind, payload = EMPTY, socket = this.socket) {
|
|
480
|
+
if (socket && socket === this.socket && socket.readyState === 1) {
|
|
481
|
+
socket.send(encodeFrame(channel, kind, payload));
|
|
482
|
+
return true;
|
|
483
|
+
}
|
|
484
|
+
return false;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
async openAttachment({ terminal, cols, rows, history = 500, observe = false, onData, onClose, onDisconnect }) {
|
|
488
|
+
const result = await this.rpc('terminal.attach', { terminal, cols, rows, history, observe });
|
|
489
|
+
const socket = this.socket;
|
|
490
|
+
if (!socket || socket.readyState !== 1) throw new Error('connection closed during attach');
|
|
491
|
+
const attachment = {
|
|
492
|
+
channel: result.channel,
|
|
493
|
+
result,
|
|
494
|
+
socket,
|
|
495
|
+
open: true,
|
|
496
|
+
onData,
|
|
497
|
+
onClose,
|
|
498
|
+
onDisconnect,
|
|
499
|
+
write: (data) => this.sendFrame(
|
|
500
|
+
result.channel,
|
|
501
|
+
DATA,
|
|
502
|
+
typeof data === 'string' ? encoder.encode(data) : asBytes(data),
|
|
503
|
+
socket,
|
|
504
|
+
),
|
|
505
|
+
resize: (nextCols, nextRows) => this.sendFrame(
|
|
506
|
+
result.channel,
|
|
507
|
+
RESIZE,
|
|
508
|
+
encodeResize(nextCols, nextRows),
|
|
509
|
+
socket,
|
|
510
|
+
),
|
|
511
|
+
focus: (focused) => this.sendFrame(
|
|
512
|
+
result.channel,
|
|
513
|
+
FOCUS,
|
|
514
|
+
Uint8Array.of(focused ? 1 : 0),
|
|
515
|
+
socket,
|
|
516
|
+
),
|
|
517
|
+
close: () => {
|
|
518
|
+
if (!attachment.open) return;
|
|
519
|
+
attachment.open = false;
|
|
520
|
+
this.attachments.delete(result.channel);
|
|
521
|
+
this.sendFrame(result.channel, CLOSE, EMPTY, socket);
|
|
522
|
+
},
|
|
523
|
+
};
|
|
524
|
+
this.attachments.set(result.channel, attachment);
|
|
525
|
+
return attachment;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
destroy() {
|
|
529
|
+
if (this.destroyed) return;
|
|
530
|
+
this.destroyed = true;
|
|
531
|
+
this.started = false;
|
|
532
|
+
clearTimeout(this.reconnectTimer);
|
|
533
|
+
this.reconnectTimer = null;
|
|
534
|
+
this.rejectPending(new Error('connection destroyed'));
|
|
535
|
+
this.dropAttachments();
|
|
536
|
+
const socket = this.socket;
|
|
537
|
+
this.socket = null;
|
|
538
|
+
if (socket) {
|
|
539
|
+
socket.onclose = null;
|
|
540
|
+
socket.onmessage = null;
|
|
541
|
+
socket.onerror = null;
|
|
542
|
+
socket.onopen = null;
|
|
543
|
+
socket.close();
|
|
544
|
+
}
|
|
545
|
+
this.cycle.resolve(false);
|
|
546
|
+
this.firstReady.resolve(false);
|
|
547
|
+
this.setState('destroyed');
|
|
548
|
+
this.emitter.clear();
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
let ghosttyPromise;
|
|
553
|
+
const loadGhostty = () => {
|
|
554
|
+
if (!ghosttyPromise) {
|
|
555
|
+
ghosttyPromise = Promise.resolve(init()).catch((error) => {
|
|
556
|
+
ghosttyPromise = null;
|
|
557
|
+
throw error;
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
return ghosttyPromise;
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
export class HerdView {
|
|
564
|
+
constructor(connection, {
|
|
565
|
+
terminalOptions = {},
|
|
566
|
+
history = 500,
|
|
567
|
+
autoFocus = true,
|
|
568
|
+
autoResize = true,
|
|
569
|
+
focusTarget = globalThis.window,
|
|
570
|
+
} = {}) {
|
|
571
|
+
if (!connection) throw new TypeError('connection is required');
|
|
572
|
+
this.connection = connection;
|
|
573
|
+
this.terminalOptions = terminalOptions;
|
|
574
|
+
this.history = history;
|
|
575
|
+
this.autoFocus = autoFocus;
|
|
576
|
+
this.autoResize = autoResize;
|
|
577
|
+
this.focusTarget = focusTarget;
|
|
578
|
+
this.emitter = new Emitter();
|
|
579
|
+
this.container = null;
|
|
580
|
+
this.address = null;
|
|
581
|
+
this.observe = false;
|
|
582
|
+
this.attachment = null;
|
|
583
|
+
this.terminal = null;
|
|
584
|
+
this.fit = null;
|
|
585
|
+
this.disposables = [];
|
|
586
|
+
this.generation = 0;
|
|
587
|
+
this.wantsAttach = false;
|
|
588
|
+
this.reconnectNeeded = false;
|
|
589
|
+
this.destroyed = false;
|
|
590
|
+
this.handleWindowFocus = () => this.reportFocus(true);
|
|
591
|
+
this.handleWindowBlur = () => this.reportFocus(false);
|
|
592
|
+
this.focusTarget?.addEventListener?.('focus', this.handleWindowFocus);
|
|
593
|
+
this.focusTarget?.addEventListener?.('blur', this.handleWindowBlur);
|
|
594
|
+
this.offConnection = connection.on('status', ({ state }) => {
|
|
595
|
+
if (state === 'ready' && this.reconnectNeeded && this.wantsAttach && !this.destroyed) {
|
|
596
|
+
this.reconnectNeeded = false;
|
|
597
|
+
this.attach(this.address, { observe: this.observe }).catch((error) => {
|
|
598
|
+
this.emitter.emit('error', { error });
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
on(type, listener) {
|
|
605
|
+
return this.emitter.on(type, listener);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
get active() {
|
|
609
|
+
return Boolean(this.attachment?.open);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
mount(element) {
|
|
613
|
+
if (this.destroyed) throw new Error('view destroyed');
|
|
614
|
+
if (!element) throw new TypeError('mount element is required');
|
|
615
|
+
if (this.terminal) throw new Error('detach or destroy the view before remounting');
|
|
616
|
+
this.container = element;
|
|
617
|
+
return this;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
emitStatus(state, detail = {}) {
|
|
621
|
+
this.emitter.emit('status', {
|
|
622
|
+
state,
|
|
623
|
+
address: this.address,
|
|
624
|
+
observe: this.observe,
|
|
625
|
+
...detail,
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async attach(address, { observe = this.observe } = {}) {
|
|
630
|
+
if (this.destroyed) throw new Error('view destroyed');
|
|
631
|
+
if (!this.container) throw new Error('mount the view before attaching');
|
|
632
|
+
if (!address) throw new TypeError('terminal address is required');
|
|
633
|
+
const generation = ++this.generation;
|
|
634
|
+
this.wantsAttach = true;
|
|
635
|
+
this.reconnectNeeded = false;
|
|
636
|
+
this.address = address;
|
|
637
|
+
this.observe = Boolean(observe);
|
|
638
|
+
this.attachment?.close();
|
|
639
|
+
this.attachment = null;
|
|
640
|
+
this.disposeTerminal();
|
|
641
|
+
this.container.replaceChildren();
|
|
642
|
+
this.emitStatus('attaching');
|
|
643
|
+
|
|
644
|
+
try {
|
|
645
|
+
await loadGhostty();
|
|
646
|
+
if (generation !== this.generation) return this;
|
|
647
|
+
const terminal = new Terminal(this.terminalOptions);
|
|
648
|
+
const fit = new FitAddon();
|
|
649
|
+
this.terminal = terminal;
|
|
650
|
+
this.fit = fit;
|
|
651
|
+
terminal.loadAddon(fit);
|
|
652
|
+
terminal.open(this.container);
|
|
653
|
+
try {
|
|
654
|
+
fit.fit();
|
|
655
|
+
if (this.autoResize) fit.observeResize();
|
|
656
|
+
} catch {}
|
|
657
|
+
this.disposables.push(terminal.onData((data) => this.write(data)));
|
|
658
|
+
this.disposables.push(terminal.onResize(({ cols, rows }) => {
|
|
659
|
+
this.emitter.emit('resize', { cols, rows });
|
|
660
|
+
if (this.active && !this.observe) this.attachment.resize(cols, rows);
|
|
661
|
+
}));
|
|
662
|
+
if (terminal.onTitleChange) {
|
|
663
|
+
this.disposables.push(terminal.onTitleChange((title) => {
|
|
664
|
+
if (!title || generation !== this.generation) return;
|
|
665
|
+
this.emitter.emit('title', { title });
|
|
666
|
+
}));
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
const attachment = await this.connection.openAttachment({
|
|
670
|
+
terminal: address,
|
|
671
|
+
cols: terminal.cols || 100,
|
|
672
|
+
rows: terminal.rows || 30,
|
|
673
|
+
history: this.history,
|
|
674
|
+
observe: this.observe,
|
|
675
|
+
onData: (bytes) => {
|
|
676
|
+
if (generation === this.generation) terminal.write(bytes);
|
|
677
|
+
},
|
|
678
|
+
onClose: (reason) => {
|
|
679
|
+
if (generation !== this.generation) return;
|
|
680
|
+
this.attachment = null;
|
|
681
|
+
this.wantsAttach = false;
|
|
682
|
+
this.reconnectNeeded = false;
|
|
683
|
+
this.emitter.emit('closed', reason || {});
|
|
684
|
+
this.emitStatus('closed', { reason });
|
|
685
|
+
},
|
|
686
|
+
onDisconnect: () => {
|
|
687
|
+
if (generation !== this.generation) return;
|
|
688
|
+
this.attachment = null;
|
|
689
|
+
this.reconnectNeeded = this.wantsAttach;
|
|
690
|
+
if (this.reconnectNeeded) this.emitStatus('reconnecting');
|
|
691
|
+
},
|
|
692
|
+
});
|
|
693
|
+
if (generation !== this.generation) {
|
|
694
|
+
attachment.close();
|
|
695
|
+
return this;
|
|
696
|
+
}
|
|
697
|
+
this.attachment = attachment;
|
|
698
|
+
this.reconnectNeeded = false;
|
|
699
|
+
this.emitStatus('attached', { terminal: attachment.result.terminal });
|
|
700
|
+
if (!this.observe && this.autoFocus) this.focus();
|
|
701
|
+
return this;
|
|
702
|
+
} catch (error) {
|
|
703
|
+
if (generation !== this.generation) return this;
|
|
704
|
+
if (this.reconnectNeeded || this.connection.state === 'reconnecting') {
|
|
705
|
+
this.reconnectNeeded = this.wantsAttach;
|
|
706
|
+
this.emitStatus('reconnecting');
|
|
707
|
+
return this;
|
|
708
|
+
}
|
|
709
|
+
this.wantsAttach = false;
|
|
710
|
+
this.attachment = null;
|
|
711
|
+
this.disposeTerminal();
|
|
712
|
+
this.emitStatus('error', { error });
|
|
713
|
+
throw error;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
setObserve(observe) {
|
|
718
|
+
const next = Boolean(observe);
|
|
719
|
+
if (this.wantsAttach && this.address) return this.attach(this.address, { observe: next });
|
|
720
|
+
this.observe = next;
|
|
721
|
+
return Promise.resolve(this);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
write(data) {
|
|
725
|
+
if (!this.active || this.observe) return false;
|
|
726
|
+
return this.attachment.write(data);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
focus() {
|
|
730
|
+
if (!this.active || this.observe) return false;
|
|
731
|
+
this.terminal?.focus();
|
|
732
|
+
return this.reportFocus(true);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
reportFocus(focused) {
|
|
736
|
+
if (!this.active || this.observe) return false;
|
|
737
|
+
this.emitter.emit('focus', { focused });
|
|
738
|
+
return this.attachment.focus(focused);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
detach() {
|
|
742
|
+
if (this.destroyed) return;
|
|
743
|
+
++this.generation;
|
|
744
|
+
this.wantsAttach = false;
|
|
745
|
+
this.reconnectNeeded = false;
|
|
746
|
+
this.attachment?.close();
|
|
747
|
+
this.attachment = null;
|
|
748
|
+
this.disposeTerminal();
|
|
749
|
+
this.address = null;
|
|
750
|
+
this.emitStatus('detached');
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
disposeTerminal() {
|
|
754
|
+
for (const disposable of this.disposables.splice(0)) {
|
|
755
|
+
try {
|
|
756
|
+
disposable?.dispose();
|
|
757
|
+
} catch {}
|
|
758
|
+
}
|
|
759
|
+
try {
|
|
760
|
+
this.fit?.dispose();
|
|
761
|
+
this.terminal?.dispose();
|
|
762
|
+
} catch {}
|
|
763
|
+
this.fit = null;
|
|
764
|
+
this.terminal = null;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
destroy() {
|
|
768
|
+
if (this.destroyed) return;
|
|
769
|
+
++this.generation;
|
|
770
|
+
this.wantsAttach = false;
|
|
771
|
+
this.reconnectNeeded = false;
|
|
772
|
+
this.attachment?.close();
|
|
773
|
+
this.attachment = null;
|
|
774
|
+
this.disposeTerminal();
|
|
775
|
+
this.offConnection?.();
|
|
776
|
+
this.focusTarget?.removeEventListener?.('focus', this.handleWindowFocus);
|
|
777
|
+
this.focusTarget?.removeEventListener?.('blur', this.handleWindowBlur);
|
|
778
|
+
this.destroyed = true;
|
|
779
|
+
this.emitStatus('destroyed');
|
|
780
|
+
this.emitter.clear();
|
|
781
|
+
this.container = null;
|
|
782
|
+
}
|
|
783
|
+
}
|
package/json-lines.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createJsonLineParser } from './index.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "herdview",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Embeddable herdr terminal connections and terminal views",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./index.js",
|
|
8
|
+
"./json-lines": "./json-lines.js",
|
|
9
|
+
"./json-lines.js": "./json-lines.js",
|
|
10
|
+
"./package.json": "./package.json"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"index.js",
|
|
14
|
+
"json-lines.js",
|
|
15
|
+
"README.md"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"check": "node --check index.js && node --check json-lines.js",
|
|
19
|
+
"test": "node --test test/*.test.mjs"
|
|
20
|
+
},
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=20"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"ghostty-web": "^0.4.0"
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"herdr",
|
|
29
|
+
"terminal",
|
|
30
|
+
"ghostty",
|
|
31
|
+
"web-terminal"
|
|
32
|
+
],
|
|
33
|
+
"license": "MIT"
|
|
34
|
+
}
|