riteshjs 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/LICENSE +21 -0
- package/README.md +68 -2
- package/THIRD_PARTY_NOTICES +104 -0
- package/dist/contracts-C55jYvFz.d.ts +555 -0
- package/dist/contracts-CFeF8xY8.js +65 -0
- package/dist/contracts-CFeF8xY8.js.map +1 -0
- package/dist/define-9nO3xQor.d.ts +6 -0
- package/dist/eggs-Dtm-FrKN.js +88 -0
- package/dist/eggs-Dtm-FrKN.js.map +1 -0
- package/dist/eggs.d.ts +10 -0
- package/dist/eggs.js +4 -0
- package/dist/index.d.ts +116 -0
- package/dist/index.js +6544 -0
- package/dist/index.js.map +1 -0
- package/dist/remote.d.ts +51 -0
- package/dist/remote.js +1084 -0
- package/dist/remote.js.map +1 -0
- package/dist/rite.bundle.min.js +171 -0
- package/dist/rite.css +292 -0
- package/dist/rolldown-runtime-dOZj-Y2f.js +13 -0
- package/dist/vendor/xterm-Bn51SPNn.js +12256 -0
- package/dist/vendor/xterm-Bn51SPNn.js.map +1 -0
- package/package.json +92 -4
package/dist/remote.js
ADDED
|
@@ -0,0 +1,1084 @@
|
|
|
1
|
+
/*! ritesh | MIT | Copyright (c) 2026 Jarrod Baumann | bundles xterm.js (MIT, see THIRD_PARTY_NOTICES) */
|
|
2
|
+
import { a as RiteError, r as EXIT, t as ERRNOS } from "./contracts-CFeF8xY8.js";
|
|
3
|
+
// src/remote/chunk.ts
|
|
4
|
+
const encoder = new TextEncoder();
|
|
5
|
+
function byteLength(text) {
|
|
6
|
+
return encoder.encode(text).length;
|
|
7
|
+
}
|
|
8
|
+
/** UTF-8 bytes one code point takes inside a JSON string, as JSON.stringify writes it. */
|
|
9
|
+
function jsonBytes(codePoint) {
|
|
10
|
+
if (codePoint === 34 || codePoint === 92) return 2;
|
|
11
|
+
if (codePoint < 32) return codePoint === 8 || codePoint === 9 || codePoint === 10 || codePoint === 12 || codePoint === 13 ? 2 : 6;
|
|
12
|
+
if (codePoint < 128) return 1;
|
|
13
|
+
if (codePoint < 2048) return 2;
|
|
14
|
+
if (codePoint >= 55296 && codePoint <= 57343) return 6;
|
|
15
|
+
return codePoint < 65536 ? 3 : 4;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Pieces of `text`, in order, whose JSON string bodies are each at most
|
|
19
|
+
* `budget` bytes. Never splits a surrogate pair. A piece holds at least one
|
|
20
|
+
* code point, so a budget below one code point's size is exceeded by it.
|
|
21
|
+
*/
|
|
22
|
+
function splitByJsonBytes(text, budget) {
|
|
23
|
+
if (text === "") return [];
|
|
24
|
+
if (text.length * 6 <= budget) return [text];
|
|
25
|
+
const pieces = [];
|
|
26
|
+
let start = 0;
|
|
27
|
+
let used = 0;
|
|
28
|
+
let i = 0;
|
|
29
|
+
while (i < text.length) {
|
|
30
|
+
const codePoint = text.codePointAt(i) ?? 0;
|
|
31
|
+
const cost = jsonBytes(codePoint);
|
|
32
|
+
if (used + cost > budget && i > start) {
|
|
33
|
+
pieces.push(text.slice(start, i));
|
|
34
|
+
start = i;
|
|
35
|
+
used = 0;
|
|
36
|
+
}
|
|
37
|
+
used += cost;
|
|
38
|
+
i += codePoint > 65535 ? 2 : 1;
|
|
39
|
+
}
|
|
40
|
+
pieces.push(text.slice(start));
|
|
41
|
+
return pieces;
|
|
42
|
+
}
|
|
43
|
+
// src/remote/wire.ts
|
|
44
|
+
const SUBPROTOCOL = "rite.1";
|
|
45
|
+
/** Sent as `version` in rite.hello. Bumped with the package version. */
|
|
46
|
+
const CLIENT_VERSION = "0.0.0";
|
|
47
|
+
const systemClock = {
|
|
48
|
+
now: () => Date.now(),
|
|
49
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
50
|
+
clearTimeout: (handle) => {
|
|
51
|
+
clearTimeout(handle);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const defaultSocket = (url, protocols) => {
|
|
55
|
+
if (typeof Reflect.get(globalThis, "WebSocket") !== "function") throw new RiteError("ENOTSUP", void 0, "WebSocket is not available");
|
|
56
|
+
return new globalThis.WebSocket(url, protocols);
|
|
57
|
+
};
|
|
58
|
+
function isRecord(value) {
|
|
59
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
60
|
+
}
|
|
61
|
+
function isErrno(value) {
|
|
62
|
+
return typeof value === "string" && ERRNOS.includes(value);
|
|
63
|
+
}
|
|
64
|
+
function notConnected(message) {
|
|
65
|
+
return new RiteError("ENOTCONN", void 0, message);
|
|
66
|
+
}
|
|
67
|
+
function canceled() {
|
|
68
|
+
return new RiteError("ECANCELED");
|
|
69
|
+
}
|
|
70
|
+
function messageOf(error) {
|
|
71
|
+
if (error instanceof Error) return error.message;
|
|
72
|
+
return typeof error === "string" ? error : "unknown error";
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* A JSON-RPC error object as a RiteError. Application errors (-32000 with
|
|
76
|
+
* data.errno) keep their errno and path and take the message from the
|
|
77
|
+
* contracts; protocol faults keep the server's message.
|
|
78
|
+
*/
|
|
79
|
+
function errorFromResponse(error, fallbackPath) {
|
|
80
|
+
if (!isRecord(error)) return new RiteError("EIO", fallbackPath, "malformed error response");
|
|
81
|
+
const data = error.data;
|
|
82
|
+
if (error.code === -32e3 && isRecord(data) && isErrno(data.errno)) return new RiteError(data.errno, typeof data.path === "string" ? data.path : fallbackPath);
|
|
83
|
+
const errno = error.code === -32601 ? "ENOTSUP" : error.code === -32602 ? "EINVAL" : "EIO";
|
|
84
|
+
return new RiteError(errno, fallbackPath, typeof error.message === "string" ? error.message : void 0);
|
|
85
|
+
}
|
|
86
|
+
// src/remote/parse.ts
|
|
87
|
+
/**
|
|
88
|
+
* Owner of remote files as rite shows them. The protocol carries no owner;
|
|
89
|
+
* the host's user owns them so the mode's owner bits are the ones that apply.
|
|
90
|
+
*/
|
|
91
|
+
const REMOTE_UID = 1e3;
|
|
92
|
+
function items(value) {
|
|
93
|
+
return Array.isArray(value) ? value : void 0;
|
|
94
|
+
}
|
|
95
|
+
function isCount(value) {
|
|
96
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
97
|
+
}
|
|
98
|
+
function isRemoteType(value) {
|
|
99
|
+
return value === "dir" || value === "file";
|
|
100
|
+
}
|
|
101
|
+
function parseFlag(value) {
|
|
102
|
+
if (!isRecord(value)) return void 0;
|
|
103
|
+
const { type, long, short, repeat, description } = value;
|
|
104
|
+
if (type !== "boolean" && type !== "string" && type !== "number") return void 0;
|
|
105
|
+
return {
|
|
106
|
+
type,
|
|
107
|
+
...typeof long === "string" ? { long } : {},
|
|
108
|
+
...typeof short === "string" ? { short } : {},
|
|
109
|
+
...typeof repeat === "boolean" ? { repeat } : {},
|
|
110
|
+
...typeof description === "string" ? { description } : {}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function parseCommand(value) {
|
|
114
|
+
if (!isRecord(value)) return void 0;
|
|
115
|
+
const { name, summary, usage } = value;
|
|
116
|
+
if (typeof name !== "string" || typeof summary !== "string" || typeof usage !== "string") return void 0;
|
|
117
|
+
if (name === "" || name === "." || name === ".." || name.includes("/") || name.includes("\0")) return void 0;
|
|
118
|
+
const info = {
|
|
119
|
+
name,
|
|
120
|
+
summary,
|
|
121
|
+
usage,
|
|
122
|
+
builtin: false,
|
|
123
|
+
remote: true
|
|
124
|
+
};
|
|
125
|
+
if (isRecord(value.flags)) {
|
|
126
|
+
const flags = {};
|
|
127
|
+
for (const [key, raw] of Object.entries(value.flags)) {
|
|
128
|
+
const flag = parseFlag(raw);
|
|
129
|
+
if (flag) flags[key] = flag;
|
|
130
|
+
}
|
|
131
|
+
info.flags = flags;
|
|
132
|
+
}
|
|
133
|
+
if (isRecord(value.subcommands)) {
|
|
134
|
+
const subcommands = {};
|
|
135
|
+
for (const [key, raw] of Object.entries(value.subcommands)) if (isRecord(raw) && typeof raw.summary === "string" && typeof raw.usage === "string") subcommands[key] = {
|
|
136
|
+
summary: raw.summary,
|
|
137
|
+
usage: raw.usage
|
|
138
|
+
};
|
|
139
|
+
info.subcommands = subcommands;
|
|
140
|
+
}
|
|
141
|
+
return info;
|
|
142
|
+
}
|
|
143
|
+
function parseHello(value) {
|
|
144
|
+
if (!isRecord(value) || typeof value.session !== "string" || !isRecord(value.limits)) return void 0;
|
|
145
|
+
const descriptors = items(value.commands);
|
|
146
|
+
const { maxMessageBytes, maxProcs, maxOutputBytes, idleSeconds } = value.limits;
|
|
147
|
+
if (!descriptors || !isCount(maxMessageBytes) || !isCount(maxProcs) || !isCount(maxOutputBytes) || !isCount(idleSeconds)) return void 0;
|
|
148
|
+
const commands = /* @__PURE__ */ new Map();
|
|
149
|
+
for (const descriptor of descriptors) {
|
|
150
|
+
const info = parseCommand(descriptor);
|
|
151
|
+
if (info && !commands.has(info.name)) commands.set(info.name, info);
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
session: value.session,
|
|
155
|
+
commands: [...commands.values()],
|
|
156
|
+
limits: {
|
|
157
|
+
maxMessageBytes,
|
|
158
|
+
maxProcs,
|
|
159
|
+
maxOutputBytes,
|
|
160
|
+
idleSeconds
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
function parseStat(value) {
|
|
165
|
+
if (!isRecord(value)) return void 0;
|
|
166
|
+
const { type, size, mode, mtime } = value;
|
|
167
|
+
if (!isRemoteType(type) || !isCount(size) || !isCount(mode) || typeof mtime !== "number") return void 0;
|
|
168
|
+
return {
|
|
169
|
+
type,
|
|
170
|
+
mode,
|
|
171
|
+
uid: REMOTE_UID,
|
|
172
|
+
gid: REMOTE_UID,
|
|
173
|
+
size,
|
|
174
|
+
mtime
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function parseList(value) {
|
|
178
|
+
if (!isRecord(value)) return void 0;
|
|
179
|
+
const entries = items(value.entries);
|
|
180
|
+
if (!entries) return void 0;
|
|
181
|
+
const out = [];
|
|
182
|
+
for (const entry of entries) {
|
|
183
|
+
if (!isRecord(entry) || typeof entry.name !== "string" || !isRemoteType(entry.type)) return void 0;
|
|
184
|
+
out.push({
|
|
185
|
+
name: entry.name,
|
|
186
|
+
type: entry.type
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
function parseRead(value) {
|
|
192
|
+
if (!isRecord(value) || typeof value.data !== "string" || typeof value.eof !== "boolean") return void 0;
|
|
193
|
+
return {
|
|
194
|
+
data: value.data,
|
|
195
|
+
eof: value.eof
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
function parseCandidates(value) {
|
|
199
|
+
if (!isRecord(value)) return void 0;
|
|
200
|
+
const candidates = items(value.candidates);
|
|
201
|
+
if (!candidates) return void 0;
|
|
202
|
+
const out = [];
|
|
203
|
+
for (const candidate of candidates) {
|
|
204
|
+
if (!isRecord(candidate) || typeof candidate.value !== "string") return void 0;
|
|
205
|
+
const { display, description, suffix } = candidate;
|
|
206
|
+
out.push({
|
|
207
|
+
value: candidate.value,
|
|
208
|
+
...typeof display === "string" ? { display } : {},
|
|
209
|
+
...typeof description === "string" ? { description } : {},
|
|
210
|
+
...typeof suffix === "string" ? { suffix } : {}
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
function parseNotify(value) {
|
|
216
|
+
if (!isRecord(value) || typeof value.text !== "string") return void 0;
|
|
217
|
+
const level = value.level;
|
|
218
|
+
if (level !== "info" && level !== "warn" && level !== "error") return void 0;
|
|
219
|
+
return {
|
|
220
|
+
text: value.text,
|
|
221
|
+
level
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
/** Past this many entries the expired ones are swept; if that is not enough the cache starts over. */
|
|
225
|
+
const CACHE_MAX_ENTRIES = 2048;
|
|
226
|
+
function parentOf(path) {
|
|
227
|
+
const slash = path.lastIndexOf("/");
|
|
228
|
+
return slash < 0 ? "" : path.slice(0, slash);
|
|
229
|
+
}
|
|
230
|
+
var RemoteFs = class {
|
|
231
|
+
readonly = true;
|
|
232
|
+
link;
|
|
233
|
+
clock;
|
|
234
|
+
stats = /* @__PURE__ */ new Map();
|
|
235
|
+
lists = /* @__PURE__ */ new Map();
|
|
236
|
+
watchers = /* @__PURE__ */ new Set();
|
|
237
|
+
/** Bumped on every invalidation, so a result requested before it is not cached after it. */
|
|
238
|
+
epoch = 0;
|
|
239
|
+
constructor(link, clock) {
|
|
240
|
+
this.link = link;
|
|
241
|
+
this.clock = clock;
|
|
242
|
+
}
|
|
243
|
+
async stat(rel, o) {
|
|
244
|
+
const hit = this.fresh(this.stats, rel);
|
|
245
|
+
if (hit) return { ...hit };
|
|
246
|
+
const epoch = this.epoch;
|
|
247
|
+
const params = { path: rel };
|
|
248
|
+
const stat = parseStat(await this.link.request("fs.stat", params, o.signal));
|
|
249
|
+
if (!stat) throw new RiteError("EIO", rel, "malformed fs.stat result");
|
|
250
|
+
if (epoch === this.epoch) this.store(this.stats, rel, stat);
|
|
251
|
+
return { ...stat };
|
|
252
|
+
}
|
|
253
|
+
async list(rel, o) {
|
|
254
|
+
const hit = this.fresh(this.lists, rel);
|
|
255
|
+
if (hit) return hit.map((entry) => ({ ...entry }));
|
|
256
|
+
const epoch = this.epoch;
|
|
257
|
+
const params = { path: rel };
|
|
258
|
+
const entries = parseList(await this.link.request("fs.list", params, o.signal));
|
|
259
|
+
if (!entries) throw new RiteError("EIO", rel, "malformed fs.list result");
|
|
260
|
+
if (epoch === this.epoch) this.store(this.lists, rel, entries);
|
|
261
|
+
return entries.map((entry) => ({ ...entry }));
|
|
262
|
+
}
|
|
263
|
+
/** Reads to the end, continuing by byte offset while the server answers eof: false. */
|
|
264
|
+
async read(rel, o) {
|
|
265
|
+
let text = "";
|
|
266
|
+
let offset = 0;
|
|
267
|
+
for (;;) {
|
|
268
|
+
const params = offset === 0 ? { path: rel } : {
|
|
269
|
+
path: rel,
|
|
270
|
+
offset
|
|
271
|
+
};
|
|
272
|
+
const chunk = parseRead(await this.link.request("fs.read", params, o.signal));
|
|
273
|
+
if (!chunk) throw new RiteError("EIO", rel, "malformed fs.read result");
|
|
274
|
+
text += chunk.data;
|
|
275
|
+
if (chunk.eof) return text;
|
|
276
|
+
if (chunk.data === "") throw new RiteError("EIO", rel, "fs.read made no progress");
|
|
277
|
+
offset += byteLength(chunk.data);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
write(rel) {
|
|
281
|
+
return Promise.reject(new RiteError("EROFS", rel));
|
|
282
|
+
}
|
|
283
|
+
mkdir(rel) {
|
|
284
|
+
return Promise.reject(new RiteError("EROFS", rel));
|
|
285
|
+
}
|
|
286
|
+
remove(rel) {
|
|
287
|
+
return Promise.reject(new RiteError("EROFS", rel));
|
|
288
|
+
}
|
|
289
|
+
watch(onChange) {
|
|
290
|
+
const watcher = (rel) => {
|
|
291
|
+
onChange(rel);
|
|
292
|
+
};
|
|
293
|
+
this.watchers.add(watcher);
|
|
294
|
+
return () => {
|
|
295
|
+
this.watchers.delete(watcher);
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
/** fs.changed: drops the path and its parent listing, then tells the watchers. */
|
|
299
|
+
changed(path, kind) {
|
|
300
|
+
this.epoch++;
|
|
301
|
+
this.stats.delete(path);
|
|
302
|
+
this.lists.delete(path);
|
|
303
|
+
this.lists.delete(parentOf(path));
|
|
304
|
+
if (kind === "delete") {
|
|
305
|
+
const prefix = path === "" ? "" : path + "/";
|
|
306
|
+
for (const cache of [this.stats, this.lists]) for (const key of [...cache.keys()]) if (key.startsWith(prefix)) cache.delete(key);
|
|
307
|
+
}
|
|
308
|
+
for (const watcher of [...this.watchers]) try {
|
|
309
|
+
watcher(path);
|
|
310
|
+
} catch {}
|
|
311
|
+
}
|
|
312
|
+
/** Changes cannot be heard while disconnected, so nothing cached then can be trusted. */
|
|
313
|
+
clear() {
|
|
314
|
+
this.epoch++;
|
|
315
|
+
this.stats.clear();
|
|
316
|
+
this.lists.clear();
|
|
317
|
+
}
|
|
318
|
+
fresh(cache, key) {
|
|
319
|
+
const hit = cache.get(key);
|
|
320
|
+
if (!hit) return void 0;
|
|
321
|
+
if (this.clock.now() - hit.at < 3e4) return hit.value;
|
|
322
|
+
cache.delete(key);
|
|
323
|
+
}
|
|
324
|
+
store(cache, key, value) {
|
|
325
|
+
const now = this.clock.now();
|
|
326
|
+
if (cache.size >= CACHE_MAX_ENTRIES) {
|
|
327
|
+
for (const [k, cached] of cache) if (now - cached.at >= 3e4) cache.delete(k);
|
|
328
|
+
if (cache.size >= CACHE_MAX_ENTRIES) cache.clear();
|
|
329
|
+
}
|
|
330
|
+
cache.set(key, {
|
|
331
|
+
at: now,
|
|
332
|
+
value
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
// src/remote/backoff.ts
|
|
337
|
+
const BACKOFF_BASE_MS = 1e3;
|
|
338
|
+
const BACKOFF_MAX_MS = 3e4;
|
|
339
|
+
/** Close codes the client never retries: bad hello, unauthorized, origin, session replaced. */
|
|
340
|
+
const NO_RETRY_CODES = /* @__PURE__ */ new Set([
|
|
341
|
+
4e3,
|
|
342
|
+
4001,
|
|
343
|
+
4003,
|
|
344
|
+
4040
|
|
345
|
+
]);
|
|
346
|
+
/**
|
|
347
|
+
* Exponential backoff with full jitter: uniform in [0, ceiling), where the
|
|
348
|
+
* ceiling doubles from 1 s with each consecutive failure and stops at 30 s.
|
|
349
|
+
*/
|
|
350
|
+
function backoffDelay(failures, random) {
|
|
351
|
+
const ceiling = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.min(Math.max(failures, 0), 16));
|
|
352
|
+
return Math.floor(random() * ceiling);
|
|
353
|
+
}
|
|
354
|
+
// src/remote/link.ts
|
|
355
|
+
/** From opening the socket to the rite.hello result. */
|
|
356
|
+
const HELLO_TIMEOUT_MS = 1e4;
|
|
357
|
+
function newAttempt() {
|
|
358
|
+
let resolve = () => void 0;
|
|
359
|
+
let reject = () => void 0;
|
|
360
|
+
const promise = new Promise((res, rej) => {
|
|
361
|
+
resolve = res;
|
|
362
|
+
reject = rej;
|
|
363
|
+
});
|
|
364
|
+
promise.catch(() => void 0);
|
|
365
|
+
return {
|
|
366
|
+
promise,
|
|
367
|
+
resolve,
|
|
368
|
+
reject
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
function untilAborted(promise, signal) {
|
|
372
|
+
return new Promise((resolve, reject) => {
|
|
373
|
+
const onAbort = () => {
|
|
374
|
+
reject(canceled());
|
|
375
|
+
};
|
|
376
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
377
|
+
promise.then((value) => {
|
|
378
|
+
signal.removeEventListener("abort", onAbort);
|
|
379
|
+
resolve(value);
|
|
380
|
+
}, (error) => {
|
|
381
|
+
signal.removeEventListener("abort", onAbort);
|
|
382
|
+
reject(error instanceof Error ? error : notConnected(messageOf(error)));
|
|
383
|
+
});
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
var Link = class {
|
|
387
|
+
/** The terminal size sent in rite.hello. Whoever sends tty.resize updates it. */
|
|
388
|
+
tty = {
|
|
389
|
+
cols: 80,
|
|
390
|
+
rows: 24
|
|
391
|
+
};
|
|
392
|
+
cfg;
|
|
393
|
+
state = "idle";
|
|
394
|
+
socket;
|
|
395
|
+
/** Bumped per attempt and on dispose, so a late token() result is dropped. */
|
|
396
|
+
generation = 0;
|
|
397
|
+
nextId = 1;
|
|
398
|
+
helloId = 0;
|
|
399
|
+
pending = /* @__PURE__ */ new Map();
|
|
400
|
+
attempt;
|
|
401
|
+
/** Consecutive failures since the last successful hello. */
|
|
402
|
+
failures = 0;
|
|
403
|
+
/** No attempt starts before this time. */
|
|
404
|
+
notBefore = 0;
|
|
405
|
+
retryTimer;
|
|
406
|
+
helloTimer;
|
|
407
|
+
idleTimer;
|
|
408
|
+
lastActivity = 0;
|
|
409
|
+
known;
|
|
410
|
+
session;
|
|
411
|
+
constructor(cfg) {
|
|
412
|
+
this.cfg = cfg;
|
|
413
|
+
}
|
|
414
|
+
get ready() {
|
|
415
|
+
return this.state === "ready";
|
|
416
|
+
}
|
|
417
|
+
/** What the last successful rite.hello returned. Kept across disconnects. */
|
|
418
|
+
get hello() {
|
|
419
|
+
return this.known;
|
|
420
|
+
}
|
|
421
|
+
get bufferedAmount() {
|
|
422
|
+
return this.socket?.bufferedAmount ?? 0;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Resolves once rite.hello has succeeded. Starts an attempt when there is
|
|
426
|
+
* none, after any backoff still owed. Waits for one attempt only: when it
|
|
427
|
+
* fails the caller gets ENOTCONN and the next use tries again.
|
|
428
|
+
*/
|
|
429
|
+
ensure(signal) {
|
|
430
|
+
if (this.state === "disposed") return Promise.reject(notConnected("remote disposed"));
|
|
431
|
+
if (this.state === "ready") return Promise.resolve();
|
|
432
|
+
if (signal?.aborted) return Promise.reject(canceled());
|
|
433
|
+
const attempt = this.attempt ?? this.schedule();
|
|
434
|
+
return signal ? untilAborted(attempt.promise, signal) : attempt.promise;
|
|
435
|
+
}
|
|
436
|
+
/** Sends a request, connecting first if needed. Not replayed when the connection drops. */
|
|
437
|
+
request(method, params, signal) {
|
|
438
|
+
if (this.state === "ready") return this.exchange(method, params, signal);
|
|
439
|
+
return this.ensure(signal).then(() => this.exchange(method, params, signal));
|
|
440
|
+
}
|
|
441
|
+
/** Sends a notification if the connection is up. Returns whether it was sent. */
|
|
442
|
+
notify(method, params) {
|
|
443
|
+
if (this.state !== "ready") return false;
|
|
444
|
+
return this.transmit({
|
|
445
|
+
jsonrpc: "2.0",
|
|
446
|
+
method,
|
|
447
|
+
params
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
/** Closes the socket for good. Pending requests and waiters fail ENOTCONN. */
|
|
451
|
+
dispose() {
|
|
452
|
+
if (this.state === "disposed") return;
|
|
453
|
+
this.state = "disposed";
|
|
454
|
+
this.generation++;
|
|
455
|
+
this.cfg.clock.clearTimeout(this.retryTimer);
|
|
456
|
+
this.retryTimer = void 0;
|
|
457
|
+
this.release()?.close(1e3, "disposed");
|
|
458
|
+
const error = notConnected("remote disposed");
|
|
459
|
+
this.failPending(error);
|
|
460
|
+
const attempt = this.attempt;
|
|
461
|
+
this.attempt = void 0;
|
|
462
|
+
attempt?.reject(error);
|
|
463
|
+
}
|
|
464
|
+
schedule() {
|
|
465
|
+
const attempt = newAttempt();
|
|
466
|
+
this.attempt = attempt;
|
|
467
|
+
const delay = this.notBefore - this.cfg.clock.now();
|
|
468
|
+
if (delay > 0) {
|
|
469
|
+
this.state = "waiting";
|
|
470
|
+
this.retryTimer = this.cfg.clock.setTimeout(() => {
|
|
471
|
+
this.retryTimer = void 0;
|
|
472
|
+
this.start();
|
|
473
|
+
}, delay);
|
|
474
|
+
} else this.start();
|
|
475
|
+
return attempt;
|
|
476
|
+
}
|
|
477
|
+
start() {
|
|
478
|
+
this.state = "connecting";
|
|
479
|
+
this.open(++this.generation);
|
|
480
|
+
}
|
|
481
|
+
async open(generation) {
|
|
482
|
+
let token;
|
|
483
|
+
try {
|
|
484
|
+
token = await Promise.resolve().then(() => this.cfg.token());
|
|
485
|
+
} catch (error) {
|
|
486
|
+
if (generation === this.generation) this.failed(notConnected(`token: ${messageOf(error)}`), true);
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
if (generation !== this.generation) return;
|
|
490
|
+
let socket;
|
|
491
|
+
try {
|
|
492
|
+
socket = this.cfg.socket(this.cfg.url, [SUBPROTOCOL]);
|
|
493
|
+
} catch (error) {
|
|
494
|
+
this.failed(notConnected(messageOf(error)), false);
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
this.socket = socket;
|
|
498
|
+
this.nextId = 1;
|
|
499
|
+
this.helloTimer = this.cfg.clock.setTimeout(() => {
|
|
500
|
+
this.helloTimer = void 0;
|
|
501
|
+
this.hangUp("hello timeout");
|
|
502
|
+
this.failed(notConnected("hello timed out"), true);
|
|
503
|
+
}, HELLO_TIMEOUT_MS);
|
|
504
|
+
socket.addEventListener("open", () => {
|
|
505
|
+
if (this.socket === socket) this.sendHello(socket, token);
|
|
506
|
+
});
|
|
507
|
+
socket.addEventListener("message", (event) => {
|
|
508
|
+
if (this.socket === socket) this.receive(event.data);
|
|
509
|
+
});
|
|
510
|
+
socket.addEventListener("close", (event) => {
|
|
511
|
+
if (this.socket === socket) this.closed(event.code);
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
sendHello(socket, token) {
|
|
515
|
+
if (socket.protocol !== "rite.1") {
|
|
516
|
+
this.hangUp("subprotocol");
|
|
517
|
+
this.failed(notConnected(`server did not select ${SUBPROTOCOL}`), false);
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
const params = {
|
|
521
|
+
protocol: "rite.1",
|
|
522
|
+
version: CLIENT_VERSION,
|
|
523
|
+
token,
|
|
524
|
+
...this.session !== void 0 ? { session: this.session } : {},
|
|
525
|
+
tty: {
|
|
526
|
+
cols: this.tty.cols,
|
|
527
|
+
rows: this.tty.rows
|
|
528
|
+
},
|
|
529
|
+
capabilities: []
|
|
530
|
+
};
|
|
531
|
+
this.helloId = this.nextId++;
|
|
532
|
+
this.transmit({
|
|
533
|
+
jsonrpc: "2.0",
|
|
534
|
+
id: this.helloId,
|
|
535
|
+
method: "rite.hello",
|
|
536
|
+
params
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
helloAnswered(msg) {
|
|
540
|
+
if ("error" in msg) {
|
|
541
|
+
const error = errorFromResponse(msg.error);
|
|
542
|
+
this.hangUp("hello rejected");
|
|
543
|
+
this.failed(notConnected(`hello rejected: ${error.message}`), false);
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
const hello = parseHello(msg.result);
|
|
547
|
+
if (!hello) {
|
|
548
|
+
this.hangUp("bad hello result");
|
|
549
|
+
this.failed(notConnected("malformed rite.hello result"), false);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
this.cfg.clock.clearTimeout(this.helloTimer);
|
|
553
|
+
this.helloTimer = void 0;
|
|
554
|
+
this.known = hello;
|
|
555
|
+
this.session = hello.session;
|
|
556
|
+
this.failures = 0;
|
|
557
|
+
this.notBefore = 0;
|
|
558
|
+
this.state = "ready";
|
|
559
|
+
this.cfg.onUp(hello);
|
|
560
|
+
this.armIdle(this.idleMs());
|
|
561
|
+
const attempt = this.attempt;
|
|
562
|
+
this.attempt = void 0;
|
|
563
|
+
attempt?.resolve();
|
|
564
|
+
}
|
|
565
|
+
/** The attempt in progress did not reach ready. */
|
|
566
|
+
failed(error, retry) {
|
|
567
|
+
this.release();
|
|
568
|
+
this.state = "idle";
|
|
569
|
+
const attempt = this.attempt;
|
|
570
|
+
this.attempt = void 0;
|
|
571
|
+
this.backOff();
|
|
572
|
+
attempt?.reject(error);
|
|
573
|
+
if (retry && this.cfg.eager) this.schedule();
|
|
574
|
+
}
|
|
575
|
+
/** The server or the network closed the current socket. */
|
|
576
|
+
closed(code) {
|
|
577
|
+
if (code === 4001) this.session = void 0;
|
|
578
|
+
const retry = !NO_RETRY_CODES.has(code);
|
|
579
|
+
const error = notConnected(`connection closed (${code})`);
|
|
580
|
+
if (this.state !== "ready") {
|
|
581
|
+
this.failed(error, retry);
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
this.release();
|
|
585
|
+
this.state = "idle";
|
|
586
|
+
this.backOff();
|
|
587
|
+
this.failPending(error);
|
|
588
|
+
this.cfg.onDown();
|
|
589
|
+
if (retry && this.cfg.eager) this.schedule();
|
|
590
|
+
}
|
|
591
|
+
backOff() {
|
|
592
|
+
this.notBefore = this.cfg.clock.now() + backoffDelay(this.failures, this.cfg.random);
|
|
593
|
+
this.failures++;
|
|
594
|
+
}
|
|
595
|
+
/** Detaches the current socket and its timers. Its later events are ignored. */
|
|
596
|
+
release() {
|
|
597
|
+
const socket = this.socket;
|
|
598
|
+
this.socket = void 0;
|
|
599
|
+
this.cfg.clock.clearTimeout(this.helloTimer);
|
|
600
|
+
this.cfg.clock.clearTimeout(this.idleTimer);
|
|
601
|
+
this.helloTimer = void 0;
|
|
602
|
+
this.idleTimer = void 0;
|
|
603
|
+
return socket;
|
|
604
|
+
}
|
|
605
|
+
hangUp(reason) {
|
|
606
|
+
this.release()?.close(1e3, reason);
|
|
607
|
+
}
|
|
608
|
+
failPending(error) {
|
|
609
|
+
const pending = [...this.pending.values()];
|
|
610
|
+
this.pending.clear();
|
|
611
|
+
for (const p of pending) p.reject(error);
|
|
612
|
+
}
|
|
613
|
+
idleMs() {
|
|
614
|
+
return (this.known?.limits.idleSeconds ?? 0) * 1e3;
|
|
615
|
+
}
|
|
616
|
+
armIdle(ms) {
|
|
617
|
+
if (this.cfg.eager || ms <= 0) return;
|
|
618
|
+
this.idleTimer = this.cfg.clock.setTimeout(() => {
|
|
619
|
+
this.idleTimer = void 0;
|
|
620
|
+
this.idleCheck();
|
|
621
|
+
}, ms);
|
|
622
|
+
}
|
|
623
|
+
idleCheck() {
|
|
624
|
+
if (this.state !== "ready") return;
|
|
625
|
+
const limit = this.idleMs();
|
|
626
|
+
if (this.pending.size > 0 || this.cfg.busy()) {
|
|
627
|
+
this.armIdle(limit);
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
const quiet = this.cfg.clock.now() - this.lastActivity;
|
|
631
|
+
if (quiet < limit) {
|
|
632
|
+
this.armIdle(limit - quiet);
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
this.hangUp("idle");
|
|
636
|
+
this.state = "idle";
|
|
637
|
+
this.cfg.onDown();
|
|
638
|
+
}
|
|
639
|
+
exchange(method, params, signal) {
|
|
640
|
+
if (this.state !== "ready") return Promise.reject(notConnected());
|
|
641
|
+
if (signal?.aborted) return Promise.reject(canceled());
|
|
642
|
+
const id = this.nextId++;
|
|
643
|
+
const path = isRecord(params) && typeof params.path === "string" ? params.path : void 0;
|
|
644
|
+
return new Promise((resolve, reject) => {
|
|
645
|
+
const onAbort = () => {
|
|
646
|
+
this.pending.delete(id);
|
|
647
|
+
reject(canceled());
|
|
648
|
+
};
|
|
649
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
650
|
+
this.pending.set(id, {
|
|
651
|
+
path,
|
|
652
|
+
resolve: (value) => {
|
|
653
|
+
signal?.removeEventListener("abort", onAbort);
|
|
654
|
+
resolve(value);
|
|
655
|
+
},
|
|
656
|
+
reject: (error) => {
|
|
657
|
+
signal?.removeEventListener("abort", onAbort);
|
|
658
|
+
reject(error);
|
|
659
|
+
}
|
|
660
|
+
});
|
|
661
|
+
if (!this.transmit({
|
|
662
|
+
jsonrpc: "2.0",
|
|
663
|
+
id,
|
|
664
|
+
method,
|
|
665
|
+
params
|
|
666
|
+
})) {
|
|
667
|
+
this.pending.delete(id);
|
|
668
|
+
signal?.removeEventListener("abort", onAbort);
|
|
669
|
+
reject(notConnected());
|
|
670
|
+
}
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
transmit(message) {
|
|
674
|
+
const socket = this.socket;
|
|
675
|
+
if (!socket) return false;
|
|
676
|
+
this.lastActivity = this.cfg.clock.now();
|
|
677
|
+
try {
|
|
678
|
+
socket.send(JSON.stringify(message));
|
|
679
|
+
return true;
|
|
680
|
+
} catch {
|
|
681
|
+
return false;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
receive(data) {
|
|
685
|
+
if (typeof data !== "string") return;
|
|
686
|
+
let msg;
|
|
687
|
+
try {
|
|
688
|
+
msg = JSON.parse(data);
|
|
689
|
+
} catch {
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
if (!isRecord(msg)) return;
|
|
693
|
+
this.lastActivity = this.cfg.clock.now();
|
|
694
|
+
if (typeof msg.method === "string") {
|
|
695
|
+
if (this.state !== "ready") return;
|
|
696
|
+
if (!("id" in msg)) this.cfg.onNotification(msg.method, msg.params);
|
|
697
|
+
else if (typeof msg.id === "number" || typeof msg.id === "string") this.transmit({
|
|
698
|
+
jsonrpc: "2.0",
|
|
699
|
+
id: msg.id,
|
|
700
|
+
error: {
|
|
701
|
+
code: -32601,
|
|
702
|
+
message: "method not found"
|
|
703
|
+
}
|
|
704
|
+
});
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
if (typeof msg.id !== "number") return;
|
|
708
|
+
if (this.state === "connecting") {
|
|
709
|
+
if (msg.id === this.helloId) this.helloAnswered(msg);
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
const pending = this.pending.get(msg.id);
|
|
713
|
+
if (!pending) return;
|
|
714
|
+
this.pending.delete(msg.id);
|
|
715
|
+
if ("error" in msg) pending.reject(errorFromResponse(msg.error, pending.path));
|
|
716
|
+
else pending.resolve(msg.result);
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
// src/remote/procs.ts
|
|
720
|
+
/** What the server reports for a killed process; used when the client ends one itself. */
|
|
721
|
+
const EXIT_KILLED = 137;
|
|
722
|
+
const CONNECTION_LOST = "rite: connection lost\n";
|
|
723
|
+
/** Used only if a process starts before any hello reported limits. */
|
|
724
|
+
const DEFAULT_MAX_MESSAGE_BYTES = 65536;
|
|
725
|
+
/** The client's cwd relative to the remote root, or "" when it is outside the remote. */
|
|
726
|
+
function remoteCwd(root, cwd) {
|
|
727
|
+
if (cwd === root || cwd === root + "/") return "";
|
|
728
|
+
return cwd.startsWith(root + "/") ? cwd.slice(root.length + 1) : "";
|
|
729
|
+
}
|
|
730
|
+
/** Only the variables the host allows leave the page. */
|
|
731
|
+
function pickEnv(env, allow) {
|
|
732
|
+
const out = {};
|
|
733
|
+
for (const name of allow) {
|
|
734
|
+
const value = Object.hasOwn(env, name) ? env[name] : void 0;
|
|
735
|
+
if (value !== void 0) out[name] = value;
|
|
736
|
+
}
|
|
737
|
+
return out;
|
|
738
|
+
}
|
|
739
|
+
function wireStdio(kind) {
|
|
740
|
+
return kind === "tty" ? "tty" : "pipe";
|
|
741
|
+
}
|
|
742
|
+
/** Read through a call: an abort or an exit can land during any await. */
|
|
743
|
+
function isAborted(signal) {
|
|
744
|
+
return signal.aborted;
|
|
745
|
+
}
|
|
746
|
+
function hasEnded(entry) {
|
|
747
|
+
return entry.ended;
|
|
748
|
+
}
|
|
749
|
+
function abortedCode(signal) {
|
|
750
|
+
return signal.reason === "INT" ? EXIT.INTERRUPTED : EXIT_KILLED;
|
|
751
|
+
}
|
|
752
|
+
function exitCode(params) {
|
|
753
|
+
const code = isRecord(params) ? params.code : void 0;
|
|
754
|
+
if (typeof code !== "number" || !Number.isInteger(code)) return EXIT.FAILURE;
|
|
755
|
+
return Math.min(255, Math.max(0, code));
|
|
756
|
+
}
|
|
757
|
+
var RemoteProcs = class {
|
|
758
|
+
cfg;
|
|
759
|
+
running = /* @__PURE__ */ new Map();
|
|
760
|
+
/** Pids increase from 1 on each connection and are never reused on it. */
|
|
761
|
+
lastPid = 0;
|
|
762
|
+
constructor(cfg) {
|
|
763
|
+
this.cfg = cfg;
|
|
764
|
+
}
|
|
765
|
+
get busy() {
|
|
766
|
+
return this.running.size > 0;
|
|
767
|
+
}
|
|
768
|
+
names() {
|
|
769
|
+
const hello = this.cfg.link.hello;
|
|
770
|
+
return hello ? hello.commands.map((command) => command.name) : [...this.cfg.declared];
|
|
771
|
+
}
|
|
772
|
+
info(name) {
|
|
773
|
+
const hello = this.cfg.link.hello;
|
|
774
|
+
if (hello) return hello.commands.find((command) => command.name === name);
|
|
775
|
+
if (!this.cfg.declared.includes(name)) return void 0;
|
|
776
|
+
return {
|
|
777
|
+
name,
|
|
778
|
+
summary: "",
|
|
779
|
+
usage: name,
|
|
780
|
+
builtin: false,
|
|
781
|
+
remote: true
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
async run(name, proc) {
|
|
785
|
+
const { link } = this.cfg;
|
|
786
|
+
if (proc.signal.aborted) return abortedCode(proc.signal);
|
|
787
|
+
try {
|
|
788
|
+
await link.ensure(proc.signal);
|
|
789
|
+
} catch (error) {
|
|
790
|
+
if (isAborted(proc.signal)) return abortedCode(proc.signal);
|
|
791
|
+
await proc.err(`rite: ${name}: ${messageOf(error)}\n`).catch(() => void 0);
|
|
792
|
+
return EXIT.CONNECTION_LOST;
|
|
793
|
+
}
|
|
794
|
+
if (isAborted(proc.signal)) return abortedCode(proc.signal);
|
|
795
|
+
const pid = ++this.lastPid;
|
|
796
|
+
let resolve = () => void 0;
|
|
797
|
+
const done = new Promise((res) => {
|
|
798
|
+
resolve = res;
|
|
799
|
+
});
|
|
800
|
+
const entry = {
|
|
801
|
+
pid,
|
|
802
|
+
proc,
|
|
803
|
+
done,
|
|
804
|
+
resolve,
|
|
805
|
+
tail: Promise.resolve(),
|
|
806
|
+
ended: false,
|
|
807
|
+
broken: false,
|
|
808
|
+
killed: false,
|
|
809
|
+
reader: void 0,
|
|
810
|
+
onAbort: () => {
|
|
811
|
+
if (proc.signal.reason === "INT") this.signal(entry, "INT");
|
|
812
|
+
else this.kill(entry);
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
this.running.set(pid, entry);
|
|
816
|
+
if (proc.tty) this.syncTty(proc.tty);
|
|
817
|
+
const params = {
|
|
818
|
+
pid,
|
|
819
|
+
argv: [name, ...proc.argv.slice(1)],
|
|
820
|
+
cwd: remoteCwd(this.cfg.root, proc.cwd),
|
|
821
|
+
env: pickEnv(proc.env, this.cfg.env),
|
|
822
|
+
stdio: {
|
|
823
|
+
stdin: wireStdio(proc.stdio.stdin),
|
|
824
|
+
stdout: wireStdio(proc.stdio.stdout),
|
|
825
|
+
stderr: wireStdio(proc.stdio.stderr)
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
proc.signal.addEventListener("abort", entry.onAbort, { once: true });
|
|
829
|
+
link.request("proc.start", params).then(() => {
|
|
830
|
+
this.pump(entry);
|
|
831
|
+
}, (error) => {
|
|
832
|
+
this.startFailed(entry, name, error);
|
|
833
|
+
});
|
|
834
|
+
return done;
|
|
835
|
+
}
|
|
836
|
+
async complete(argv, index, signal) {
|
|
837
|
+
const params = {
|
|
838
|
+
argv: [...argv],
|
|
839
|
+
index
|
|
840
|
+
};
|
|
841
|
+
const candidates = parseCandidates(await this.cfg.link.request("proc.complete", params, signal));
|
|
842
|
+
if (!candidates) throw new RiteError("EIO", void 0, "malformed proc.complete result");
|
|
843
|
+
return candidates;
|
|
844
|
+
}
|
|
845
|
+
/** proc.stdout, proc.stderr, and proc.exit from the server. */
|
|
846
|
+
notification(method, params) {
|
|
847
|
+
if (!isRecord(params) || typeof params.pid !== "number") return;
|
|
848
|
+
const entry = this.running.get(params.pid);
|
|
849
|
+
if (!entry) return;
|
|
850
|
+
if (method === "proc.exit") this.end(entry, exitCode(params));
|
|
851
|
+
else if (typeof params.data === "string") this.output(entry, method === "proc.stdout" ? "stdout" : "stderr", params.data);
|
|
852
|
+
}
|
|
853
|
+
/** A new connection: its pids start again from 1. */
|
|
854
|
+
connected() {
|
|
855
|
+
this.lastPid = 0;
|
|
856
|
+
}
|
|
857
|
+
/** The connection is gone: no process survives it. */
|
|
858
|
+
lost() {
|
|
859
|
+
for (const entry of [...this.running.values()]) this.end(entry, EXIT.CONNECTION_LOST, CONNECTION_LOST);
|
|
860
|
+
}
|
|
861
|
+
/** The host is done: KILL what runs. Call before the link is disposed. */
|
|
862
|
+
dispose() {
|
|
863
|
+
for (const entry of [...this.running.values()]) {
|
|
864
|
+
this.kill(entry);
|
|
865
|
+
this.end(entry, EXIT_KILLED, void 0, false);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
startFailed(entry, name, error) {
|
|
869
|
+
if (entry.ended) return;
|
|
870
|
+
const errno = error instanceof RiteError ? error.errno : "EIO";
|
|
871
|
+
if (errno === "ENOTCONN") this.end(entry, EXIT.CONNECTION_LOST, CONNECTION_LOST);
|
|
872
|
+
else if (errno === "ENOENT") this.end(entry, EXIT.NOT_FOUND, `rite: command not found: ${name}\n`);
|
|
873
|
+
else if (errno === "EACCES" || errno === "EPERM") this.end(entry, EXIT.NOT_EXECUTABLE, `${name}: ${messageOf(error)}\n`);
|
|
874
|
+
else this.end(entry, EXIT.FAILURE, `${name}: ${messageOf(error)}\n`);
|
|
875
|
+
}
|
|
876
|
+
output(entry, to, data) {
|
|
877
|
+
if (to === "stderr") {
|
|
878
|
+
entry.tail = entry.tail.then(() => entry.proc.err(data)).catch(() => void 0);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
entry.tail = entry.tail.then(() => entry.broken ? void 0 : entry.proc.out(data)).catch(() => {
|
|
882
|
+
entry.broken = true;
|
|
883
|
+
this.kill(entry);
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
signal(entry, signal) {
|
|
887
|
+
if (entry.ended) return;
|
|
888
|
+
const params = {
|
|
889
|
+
pid: entry.pid,
|
|
890
|
+
signal
|
|
891
|
+
};
|
|
892
|
+
this.cfg.link.notify("proc.signal", params);
|
|
893
|
+
}
|
|
894
|
+
kill(entry) {
|
|
895
|
+
if (entry.killed) return;
|
|
896
|
+
entry.killed = true;
|
|
897
|
+
this.signal(entry, "KILL");
|
|
898
|
+
}
|
|
899
|
+
/** Resolves run once the output already received is written (unless `flush` is false), then `last` on stderr. */
|
|
900
|
+
end(entry, code, last, flush = true) {
|
|
901
|
+
if (entry.ended) return;
|
|
902
|
+
entry.ended = true;
|
|
903
|
+
this.running.delete(entry.pid);
|
|
904
|
+
entry.proc.signal.removeEventListener("abort", entry.onAbort);
|
|
905
|
+
entry.reader?.cancel().catch(() => void 0);
|
|
906
|
+
if (last !== void 0) entry.tail = entry.tail.then(() => entry.proc.err(last)).catch(() => void 0);
|
|
907
|
+
if (flush) entry.tail.then(() => {
|
|
908
|
+
entry.resolve(code);
|
|
909
|
+
});
|
|
910
|
+
else entry.resolve(code);
|
|
911
|
+
}
|
|
912
|
+
async pump(entry) {
|
|
913
|
+
if (entry.ended) return;
|
|
914
|
+
const { pid, proc } = entry;
|
|
915
|
+
try {
|
|
916
|
+
const reader = proc.stdin.getReader();
|
|
917
|
+
entry.reader = reader;
|
|
918
|
+
const budget = this.stdinBudget(pid);
|
|
919
|
+
for (;;) {
|
|
920
|
+
const chunk = await reader.read();
|
|
921
|
+
if (hasEnded(entry)) return;
|
|
922
|
+
if (chunk.done) break;
|
|
923
|
+
for (const piece of splitByJsonBytes(chunk.value, budget)) {
|
|
924
|
+
await this.drained(entry);
|
|
925
|
+
if (hasEnded(entry)) return;
|
|
926
|
+
this.stdin({
|
|
927
|
+
pid,
|
|
928
|
+
data: piece
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
} catch {
|
|
933
|
+
if (proc.signal.aborted) return;
|
|
934
|
+
}
|
|
935
|
+
if (!hasEnded(entry)) this.stdin({
|
|
936
|
+
pid,
|
|
937
|
+
eof: true
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
stdin(params) {
|
|
941
|
+
this.cfg.link.notify("proc.stdin", params);
|
|
942
|
+
}
|
|
943
|
+
/** The bytes left for `data` in a proc.stdin message for this pid. */
|
|
944
|
+
stdinBudget(pid) {
|
|
945
|
+
const max = this.cfg.link.hello?.limits.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;
|
|
946
|
+
const envelope = byteLength(JSON.stringify({
|
|
947
|
+
jsonrpc: "2.0",
|
|
948
|
+
method: "proc.stdin",
|
|
949
|
+
params: {
|
|
950
|
+
pid,
|
|
951
|
+
data: ""
|
|
952
|
+
}
|
|
953
|
+
}));
|
|
954
|
+
return Math.max(1, max - envelope);
|
|
955
|
+
}
|
|
956
|
+
/** WebSocket has no drain event: poll bufferedAmount until the socket has caught up. */
|
|
957
|
+
async drained(entry) {
|
|
958
|
+
const { link, clock } = this.cfg;
|
|
959
|
+
while (!entry.ended && link.bufferedAmount > 262144) await new Promise((resolve) => {
|
|
960
|
+
clock.setTimeout(resolve, 20);
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
/** A process with a terminal: tell the server when its size is not the one last sent. */
|
|
964
|
+
syncTty(tty) {
|
|
965
|
+
const { link } = this.cfg;
|
|
966
|
+
const { cols, rows } = tty;
|
|
967
|
+
if (!Number.isInteger(cols) || !Number.isInteger(rows) || cols <= 0 || rows <= 0) return;
|
|
968
|
+
if (cols === link.tty.cols && rows === link.tty.rows) return;
|
|
969
|
+
link.tty = {
|
|
970
|
+
cols,
|
|
971
|
+
rows
|
|
972
|
+
};
|
|
973
|
+
const params = {
|
|
974
|
+
cols,
|
|
975
|
+
rows
|
|
976
|
+
};
|
|
977
|
+
link.notify("tty.resize", params);
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
function absolute(path, option) {
|
|
981
|
+
if (!path.startsWith("/")) throw new RiteError("EINVAL", path, `remote: ${option} must be an absolute path`);
|
|
982
|
+
const trimmed = path.replace(/\/+$/, "");
|
|
983
|
+
return trimmed === "" ? "/" : trimmed;
|
|
984
|
+
}
|
|
985
|
+
function createRemote(options) {
|
|
986
|
+
const at = absolute(options.at, "at");
|
|
987
|
+
const root = at === "/" ? "" : at;
|
|
988
|
+
const bin = options.bin === void 0 ? `${root}/bin` : absolute(options.bin, "bin");
|
|
989
|
+
const clock = options.clock ?? systemClock;
|
|
990
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
991
|
+
/** When the notifications still inside the window were delivered. */
|
|
992
|
+
const delivered = [];
|
|
993
|
+
const link = new Link({
|
|
994
|
+
url: options.url,
|
|
995
|
+
token: options.token,
|
|
996
|
+
eager: options.connect === "eager",
|
|
997
|
+
socket: options.socket ?? defaultSocket,
|
|
998
|
+
clock,
|
|
999
|
+
random: options.random ?? Math.random,
|
|
1000
|
+
busy: () => procs.busy,
|
|
1001
|
+
onUp: () => {
|
|
1002
|
+
procs.connected();
|
|
1003
|
+
},
|
|
1004
|
+
onDown: () => {
|
|
1005
|
+
procs.lost();
|
|
1006
|
+
fs.clear();
|
|
1007
|
+
},
|
|
1008
|
+
onNotification: (method, params) => {
|
|
1009
|
+
if (method === "proc.stdout" || method === "proc.stderr" || method === "proc.exit") procs.notification(method, params);
|
|
1010
|
+
else if (method === "fs.changed") changed(params);
|
|
1011
|
+
else if (method === "term.notify") notified(params);
|
|
1012
|
+
}
|
|
1013
|
+
});
|
|
1014
|
+
const fs = new RemoteFs(link, clock);
|
|
1015
|
+
const procs = new RemoteProcs({
|
|
1016
|
+
link,
|
|
1017
|
+
clock,
|
|
1018
|
+
root,
|
|
1019
|
+
env: options.env ?? [],
|
|
1020
|
+
declared: options.commands ?? []
|
|
1021
|
+
});
|
|
1022
|
+
function changed(params) {
|
|
1023
|
+
if (isRecord(params) && typeof params.path === "string") fs.changed(params.path, params.kind);
|
|
1024
|
+
}
|
|
1025
|
+
function notified(params) {
|
|
1026
|
+
const note = parseNotify(params);
|
|
1027
|
+
if (!note || listeners.size === 0) return;
|
|
1028
|
+
const now = clock.now();
|
|
1029
|
+
while (delivered[0] !== void 0 && now - delivered[0] >= 1e4) delivered.shift();
|
|
1030
|
+
if (delivered.length >= 5) return;
|
|
1031
|
+
delivered.push(now);
|
|
1032
|
+
for (const listener of [...listeners]) try {
|
|
1033
|
+
listener(note.text, note.level);
|
|
1034
|
+
} catch {}
|
|
1035
|
+
}
|
|
1036
|
+
const client = {
|
|
1037
|
+
at,
|
|
1038
|
+
bin,
|
|
1039
|
+
provider: fs,
|
|
1040
|
+
commands: procs,
|
|
1041
|
+
link,
|
|
1042
|
+
connect: () => link.ensure(),
|
|
1043
|
+
resize: (cols, rows) => {
|
|
1044
|
+
if (!Number.isInteger(cols) || !Number.isInteger(rows) || cols <= 0 || rows <= 0) return;
|
|
1045
|
+
if (cols === link.tty.cols && rows === link.tty.rows) return;
|
|
1046
|
+
link.tty = {
|
|
1047
|
+
cols,
|
|
1048
|
+
rows
|
|
1049
|
+
};
|
|
1050
|
+
link.notify("tty.resize", {
|
|
1051
|
+
cols,
|
|
1052
|
+
rows
|
|
1053
|
+
});
|
|
1054
|
+
},
|
|
1055
|
+
dispose: () => {
|
|
1056
|
+
procs.dispose();
|
|
1057
|
+
link.dispose();
|
|
1058
|
+
fs.clear();
|
|
1059
|
+
listeners.clear();
|
|
1060
|
+
},
|
|
1061
|
+
onNotify: (listener) => {
|
|
1062
|
+
const entry = (text, level) => {
|
|
1063
|
+
listener(text, level);
|
|
1064
|
+
};
|
|
1065
|
+
listeners.add(entry);
|
|
1066
|
+
return () => {
|
|
1067
|
+
listeners.delete(entry);
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
if (options.connect === "eager") client.connect().catch(() => void 0);
|
|
1072
|
+
return client;
|
|
1073
|
+
}
|
|
1074
|
+
// src/remote.ts
|
|
1075
|
+
/**
|
|
1076
|
+
* A remote server as a mount and a command source for createRite. Nothing is
|
|
1077
|
+
* sent until the first use unless `connect` is "eager".
|
|
1078
|
+
*/
|
|
1079
|
+
function remote(options) {
|
|
1080
|
+
return createRemote(options);
|
|
1081
|
+
}
|
|
1082
|
+
export { remote };
|
|
1083
|
+
|
|
1084
|
+
//# sourceMappingURL=remote.js.map
|