simcast-host 0.0.0-stage → 0.9.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.
@@ -0,0 +1,464 @@
1
+ // The tunnel (docs/protocol.md, "Tunnel"): each PC holds one /tunnel control
2
+ // WebSocket; the agent listens on the Mac's 127.0.0.1 and ::1 for the PC's
3
+ // ports, and every accepted TCP connection becomes one PC-opened
4
+ // GET /tunnel/data?id= upgraded to a raw TCP stream (Upgrade: simcast-tcp).
5
+ // The agent never opens a connection to the PC.
6
+ //
7
+ // State, per PC (by client id):
8
+ // control the live /tunnel WebSocket, or null (lost: the grace runs)
9
+ // ports port -> { port, pcPort, macPort, name, servers, listening, error, connections }
10
+ // pending accepted Mac-side sockets, paused, waiting for their data stream
11
+ // streams joined pairs { mac, pc } (the Mac-side socket and the upgraded one)
12
+ // A PC's entry lives while it has a control connection or is in its grace.
13
+ import crypto from 'node:crypto';
14
+ import net from 'node:net';
15
+ import { PROTOCOL, VERSION, heartbeat } from '../common.js';
16
+ import * as awake from './awake.js';
17
+
18
+ // Limits (plan 2.6).
19
+ export const MAX_PORTS = 16;
20
+ export const MAX_CONNECTIONS = 256; // waiting or open, per PC
21
+ export const PENDING_MS = 5000; // an accepted connection waits this long for its data stream
22
+ export const GRACE_MS = 10000; // listeners stay up this long after the control connection is lost
23
+ // Test-only: macPort = port + offset (0 in real use).
24
+ export const portOffset = () => Number(process.env.SIMCAST_TUNNEL_PORT_OFFSET) || 0;
25
+ // Test-only: shorter timers (SIMCAST_TUNNEL_PENDING_MS, SIMCAST_TUNNEL_GRACE_MS).
26
+ const msFromEnv = (name, fallback) => {
27
+ const ms = Number(process.env[name]);
28
+ return Number.isFinite(ms) && ms > 0 ? ms : fallback;
29
+ };
30
+ const pendingMs = () => msFromEnv('SIMCAST_TUNNEL_PENDING_MS', PENDING_MS);
31
+ const graceMs = () => msFromEnv('SIMCAST_TUNNEL_GRACE_MS', GRACE_MS);
32
+
33
+ const UPGRADE = 'simcast-tcp';
34
+ const EXPIRED_KEEP_MS = 60_000; // an expired id answers 410 (not 404) this long
35
+ const EXPIRED_MAX = 4096;
36
+
37
+ const log = (msg) => console.log(`[${new Date().toISOString()}] tunnel: ${msg}`);
38
+
39
+ const pcs = new Map(); // client id -> PC state
40
+ const pendingById = new Map(); // id -> pending entry (of any PC)
41
+ const expired = new Map(); // id -> { clientId, at }
42
+ let agentPort = null; // learnt from the control connection's socket
43
+
44
+ function pcFor(client) {
45
+ let pc = pcs.get(client.id);
46
+ if (!pc) {
47
+ pc = { id: client.id, name: client.name, control: null, ports: new Map(), pending: new Set(), streams: new Set(), graceTimer: null, queue: Promise.resolve(), closed: false, limitLogged: false };
48
+ pcs.set(client.id, pc);
49
+ }
50
+ pc.name = client.name || pc.name;
51
+ return pc;
52
+ }
53
+
54
+ function send(ctl, msg) {
55
+ if (!ctl || ctl.ws.readyState !== 1) return;
56
+ try { ctl.ws.send(JSON.stringify(msg)); } catch { /* closing */ }
57
+ }
58
+
59
+ // A reset (RST) when the socket still has a connection, else a plain destroy.
60
+ function reset(socket) {
61
+ if (!socket || socket.destroyed) return;
62
+ try {
63
+ socket.resetAndDestroy();
64
+ } catch {
65
+ socket.destroy();
66
+ }
67
+ }
68
+
69
+ function remember(id, clientId) {
70
+ const now = Date.now();
71
+ expired.set(id, { clientId, at: now });
72
+ if (expired.size > EXPIRED_MAX) {
73
+ for (const [key, v] of expired) {
74
+ if (expired.size <= EXPIRED_MAX / 2 && now - v.at < EXPIRED_KEEP_MS) break;
75
+ expired.delete(key);
76
+ }
77
+ }
78
+ }
79
+
80
+ // ---- the control connection ------------------------------------------------
81
+
82
+ // A PC's /tunnel control WebSocket, after the upgrade passed the auth checks.
83
+ // `client` is { id, name }; `protocol` is the negotiated protocol for the hello.
84
+ // `agentPort` (optional) is the agent's own port, else taken from the socket.
85
+ // A newer /tunnel from the same PC closes this one with 4009 and takes over its
86
+ // listeners, pending connections and streams. Heartbeat as /session.
87
+ export function attachControl(ws, client, { protocol = PROTOCOL, agentPort: port } = {}) {
88
+ agentPort = Number(port) || ws._socket?.localPort || agentPort;
89
+ const pc = pcFor(client);
90
+ pc.closed = false;
91
+ const old = pc.control;
92
+ const ctl = { ws };
93
+ pc.control = ctl;
94
+ if (pc.graceTimer) {
95
+ clearTimeout(pc.graceTimer);
96
+ pc.graceTimer = null;
97
+ log(`${pc.name} is back`);
98
+ } else if (old) {
99
+ log(`${pc.name} opened a new tunnel; closing the old one`);
100
+ } else {
101
+ log(`${pc.name} connected`);
102
+ }
103
+ if (old) {
104
+ try { old.ws.close(4009, 'Replaced by a newer tunnel from this PC'); } catch { /* gone */ }
105
+ }
106
+
107
+ heartbeat(ws);
108
+ ws.on('error', () => {});
109
+ ws.on('message', (data, isBinary) => onMessage(pc, ctl, data, isBinary));
110
+ ws.on('close', () => {
111
+ if (pc.control !== ctl) return; // replaced, or closed by closeFor
112
+ pc.control = null;
113
+ lost(pc);
114
+ });
115
+
116
+ send(ctl, { t: 'hello', version: VERSION, protocol });
117
+ send(ctl, portsMessage(pc));
118
+ // Connections that waited (during the grace, or announced to a replaced
119
+ // control) are announced to this one.
120
+ for (const entry of pc.pending) announce(entry);
121
+ }
122
+
123
+ function lost(pc) {
124
+ const ms = graceMs();
125
+ log(`${pc.name} lost its tunnel; keeping its ports for ${Math.round(ms / 1000)} s`);
126
+ pc.graceTimer = setTimeout(() => {
127
+ pc.graceTimer = null;
128
+ if (pc.control) return;
129
+ log(`${pc.name}'s tunnel didn't come back; closing its ports`);
130
+ teardown(pc);
131
+ }, ms);
132
+ pc.graceTimer.unref();
133
+ }
134
+
135
+ function onMessage(pc, ctl, data, isBinary) {
136
+ if (pc.control !== ctl) return;
137
+ let msg;
138
+ try {
139
+ if (isBinary) throw new Error('binary');
140
+ msg = JSON.parse(data.toString('utf8'));
141
+ } catch {
142
+ return send(ctl, { t: 'error', msg: 'Messages on /tunnel are JSON text.' });
143
+ }
144
+ if (!msg || typeof msg !== 'object' || typeof msg.t !== 'string') return send(ctl, { t: 'error', msg: 'A message needs a type in "t".' });
145
+ if (msg.t === 'ports') {
146
+ pc.queue = pc.queue.then(() => reconcile(pc, msg.ports)).catch((err) => log(`ports: ${err.message}`));
147
+ } else if (msg.t === 'refused') {
148
+ const entry = pendingById.get(String(msg.id));
149
+ if (entry && entry.pc === pc) fail(entry, typeof msg.msg === 'string' ? msg.msg.slice(0, 200) : null);
150
+ }
151
+ // Unknown types are ignored (newer PCs).
152
+ }
153
+
154
+ // ---- ports -----------------------------------------------------------------
155
+
156
+ const validPort = (v) => Number.isInteger(v) && v >= 1 && v <= 65535;
157
+
158
+ function portsMessage(pc) {
159
+ return {
160
+ t: 'ports',
161
+ ports: [...pc.ports.values()].map(({ port, pcPort, macPort, listening: up, error }) => (
162
+ up ? { port, pcPort, macPort, listening: true } : { port, pcPort, macPort, listening: false, error })),
163
+ };
164
+ }
165
+
166
+ // The PC's whole wanted set: opens new ports, closes removed ones (their open
167
+ // connections keep going), retries ports that failed, then reports.
168
+ async function reconcile(pc, list) {
169
+ if (pc.closed) return;
170
+ const errors = [];
171
+ const wanted = new Map();
172
+ if (!Array.isArray(list)) {
173
+ errors.push('"ports" must be a list.');
174
+ } else {
175
+ for (const item of list) {
176
+ const port = Number(item?.port);
177
+ const pcPort = item?.pcPort === undefined ? port : Number(item.pcPort);
178
+ if (!validPort(port) || !validPort(pcPort)) {
179
+ errors.push(`Not a port: ${JSON.stringify(item?.port ?? item)}.`);
180
+ continue;
181
+ }
182
+ if (wanted.has(port)) continue;
183
+ if (wanted.size >= MAX_PORTS) {
184
+ errors.push(`At most ${MAX_PORTS} ports can be tunnelled; port ${port} was left out.`);
185
+ continue;
186
+ }
187
+ wanted.set(port, { port, pcPort, name: typeof item.name === 'string' ? item.name.slice(0, 20) : 'reverse' });
188
+ }
189
+ }
190
+ for (const msg of errors) send(pc.control, { t: 'error', msg });
191
+ if (!Array.isArray(list)) return;
192
+
193
+ for (const [port, p] of pc.ports) {
194
+ if (wanted.has(port)) continue;
195
+ pc.ports.delete(port);
196
+ closePort(p);
197
+ log(`${pc.name}: closed port ${p.macPort}`);
198
+ }
199
+ const opening = [];
200
+ for (const want of wanted.values()) {
201
+ const p = pc.ports.get(want.port);
202
+ if (p) {
203
+ p.pcPort = want.pcPort;
204
+ p.name = want.name;
205
+ if (!p.listening) opening.push(openPort(pc, p));
206
+ } else {
207
+ const fresh = { ...want, macPort: want.port + portOffset(), servers: [], listening: false, error: null, connections: 0, closed: false };
208
+ pc.ports.set(want.port, fresh);
209
+ opening.push(openPort(pc, fresh));
210
+ }
211
+ }
212
+ await Promise.all(opening);
213
+ if (!pc.closed) send(pc.control, portsMessage(pc));
214
+ }
215
+
216
+ function closePort(p) {
217
+ p.closed = true;
218
+ p.listening = false;
219
+ for (const s of p.servers) s.close();
220
+ p.servers = [];
221
+ }
222
+
223
+ function listen(server, host, port) {
224
+ return new Promise((resolve, reject) => {
225
+ const onError = (err) => reject(err);
226
+ server.once('error', onError);
227
+ server.listen({ host, port, exclusive: true }, () => {
228
+ server.off('error', onError);
229
+ server.on('error', (err) => log(`listener ${host}:${port}: ${err.message}`));
230
+ resolve();
231
+ });
232
+ });
233
+ }
234
+
235
+ // macOS lets a socket bind 127.0.0.1:<p> while another program listens on
236
+ // *:<p> (Node sets SO_REUSEADDR), so EADDRINUSE alone misses a Metro already
237
+ // running on the Mac. A quick connect finds it. Not on other systems: there the
238
+ // bind fails as it should, and Windows takes about a second to refuse.
239
+ function answers(port) {
240
+ if (process.platform !== 'darwin') return Promise.resolve(false);
241
+ return new Promise((resolve) => {
242
+ const s = net.connect({ host: '127.0.0.1', port });
243
+ const done = (yes) => { s.destroy(); resolve(yes); };
244
+ s.setTimeout(300, () => done(false));
245
+ s.once('connect', () => done(true));
246
+ s.once('error', () => done(false));
247
+ });
248
+ }
249
+
250
+ const errorText = (macPort, err) => (
251
+ err.code === 'EADDRINUSE' ? `Port ${macPort} is in use on the Mac.`
252
+ : err.code === 'EACCES' ? 'Ports below 1024 can\'t be used on the Mac.'
253
+ : `Port ${macPort} can't be used on the Mac (${err.code || err.message}).`);
254
+
255
+ async function openPort(pc, p) {
256
+ const { port, macPort } = p;
257
+ p.error = null;
258
+ if (port < 1024 || macPort < 1024) p.error = 'Ports below 1024 can\'t be used on the Mac.';
259
+ else if (macPort > 65535) p.error = `Port ${macPort} can't be used on the Mac.`;
260
+ else if (macPort === agentPort) p.error = `Port ${macPort} is the simcast agent's own port.`;
261
+ else if (await answers(macPort)) p.error = `Port ${macPort} is in use on the Mac.`;
262
+ if (p.error) {
263
+ log(`${pc.name}: port ${macPort}: ${p.error}`);
264
+ return;
265
+ }
266
+ const make = () => net.createServer({ pauseOnConnect: true, allowHalfOpen: true }, (sock) => accept(pc, p, sock));
267
+ const v4 = make();
268
+ try {
269
+ await listen(v4, '127.0.0.1', macPort);
270
+ } catch (err) {
271
+ p.error = errorText(macPort, err);
272
+ log(`${pc.name}: port ${macPort}: ${p.error}`);
273
+ return;
274
+ }
275
+ const servers = [v4];
276
+ const v6 = make();
277
+ try {
278
+ await listen(v6, '::1', macPort);
279
+ servers.push(v6);
280
+ } catch (err) {
281
+ // No IPv6 loopback on this Mac (EADDRNOTAVAIL; EAFNOSUPPORT without IPv6 at all).
282
+ if (err.code !== 'EADDRNOTAVAIL' && err.code !== 'EAFNOSUPPORT') {
283
+ v4.close();
284
+ p.error = errorText(macPort, err);
285
+ log(`${pc.name}: port ${macPort} on ::1: ${p.error}`);
286
+ return;
287
+ }
288
+ }
289
+ if (p.closed || pc.closed) { // removed or torn down while listening
290
+ for (const s of servers) s.close();
291
+ return;
292
+ }
293
+ p.servers = servers;
294
+ p.listening = true;
295
+ log(`${pc.name}: localhost:${macPort} on the Mac -> port ${p.pcPort} on the PC`);
296
+ }
297
+
298
+ // ---- connections -----------------------------------------------------------
299
+
300
+ function accept(pc, p, sock) {
301
+ sock.on('error', () => {}); // handled by the stream or the pending entry
302
+ if (pc.closed || pc.pending.size + pc.streams.size >= MAX_CONNECTIONS) {
303
+ if (!pc.limitLogged) log(`${pc.name}: ${MAX_CONNECTIONS} tunnel connections already; refusing more`);
304
+ pc.limitLogged = true;
305
+ sock.destroy();
306
+ return;
307
+ }
308
+ pc.limitLogged = false;
309
+ const entry = { id: crypto.randomBytes(16).toString('base64url'), pc, port: p, sock, timer: null, announcedTo: null };
310
+ pc.pending.add(entry);
311
+ pendingById.set(entry.id, entry);
312
+ p.connections++;
313
+ entry.timer = setTimeout(() => fail(entry, null), pendingMs());
314
+ entry.timer.unref();
315
+ // The Mac-side program gave up before the PC answered.
316
+ sock.once('close', () => { if (pendingById.get(entry.id) === entry) drop(entry); });
317
+ if (pc.control) announce(entry);
318
+ }
319
+
320
+ function announce(entry) {
321
+ const ctl = entry.pc.control;
322
+ if (!ctl || entry.announcedTo === ctl) return;
323
+ entry.announcedTo = ctl;
324
+ send(ctl, { t: 'open', id: entry.id, port: entry.port.macPort, pcPort: entry.port.pcPort });
325
+ }
326
+
327
+ // Takes a pending entry out (the id then answers 410).
328
+ function drop(entry) {
329
+ clearTimeout(entry.timer);
330
+ pendingById.delete(entry.id);
331
+ entry.pc.pending.delete(entry);
332
+ entry.port.connections--;
333
+ remember(entry.id, entry.pc.id);
334
+ }
335
+
336
+ // No data stream in time, or the PC said its port didn't answer.
337
+ function fail(entry, msg) {
338
+ if (pendingById.get(entry.id) !== entry) return;
339
+ drop(entry);
340
+ reset(entry.sock);
341
+ log(`PC's port ${entry.port.pcPort} didn't answer${msg ? ` (${msg})` : ''}`);
342
+ }
343
+
344
+ function refuse(socket, status, msg) {
345
+ socket.write(`HTTP/1.1 ${status}\r\nx-simcast-error: ${encodeURIComponent(msg)}\r\nConnection: close\r\n\r\n`);
346
+ socket.destroy();
347
+ }
348
+
349
+ // GET /tunnel/data?id=<id> with Upgrade: simcast-tcp, after the auth checks
350
+ // (`client` is the PC; the id must belong to a pending connection of that PC,
351
+ // else 404, or 410 once it expired). Answers 101 and joins `socket` (with
352
+ // `head` written first) to the waiting Mac-side connection. Never goes through
353
+ // the WebSocket server.
354
+ export function handleData(req, socket, head, client) {
355
+ socket.on('error', () => {});
356
+ const id = new URL(req.url, 'http://agent').searchParams.get('id') || '';
357
+ const entry = pendingById.get(id);
358
+ if (!entry || entry.pc.id !== client?.id) {
359
+ // Another PC's id is unknown to this one: 404, the same as a made-up id.
360
+ const gone = expired.get(id);
361
+ if (client && gone?.clientId === client.id && Date.now() - gone.at < EXPIRED_KEEP_MS) return refuse(socket, '410 Gone', 'This tunnel connection has expired.');
362
+ return refuse(socket, '404 Not Found', 'No such tunnel connection.');
363
+ }
364
+ if (String(req.headers.upgrade || '').toLowerCase() !== UPGRADE) {
365
+ return refuse(socket, '400 Bad Request', `A tunnel data stream needs "Upgrade: ${UPGRADE}".`);
366
+ }
367
+ const { pc, port: p, sock: mac } = entry;
368
+ clearTimeout(entry.timer);
369
+ pendingById.delete(id);
370
+ pc.pending.delete(entry);
371
+ remember(id, pc.id); // a second upgrade for the same id gets 410
372
+
373
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: ${UPGRADE}\r\n\r\n`);
374
+ socket.setNoDelay(true);
375
+ mac.setNoDelay(true);
376
+ const stream = { mac, pc: socket, release: awake.hold('tunnel') };
377
+ pc.streams.add(stream);
378
+ let open = 2;
379
+ const closed = () => {
380
+ if (--open) return;
381
+ stream.release();
382
+ pc.streams.delete(stream);
383
+ p.connections--;
384
+ };
385
+ join(mac, socket, closed);
386
+ if (head?.length) mac.write(head);
387
+ mac.resume();
388
+ }
389
+
390
+ // Pipes both ways. A FIN becomes end() on the other side (pipe's default, with
391
+ // allowHalfOpen on both); an error, or a close before both directions ended
392
+ // cleanly, becomes a reset of the other side.
393
+ function join(a, b, onClose) {
394
+ for (const [from, to] of [[a, b], [b, a]]) {
395
+ from.pipe(to);
396
+ from.on('error', () => reset(to));
397
+ from.once('close', () => {
398
+ if (!(from.readableEnded && from.writableFinished)) reset(to);
399
+ onClose();
400
+ });
401
+ }
402
+ }
403
+
404
+ // ---- queries and shutdown --------------------------------------------------
405
+
406
+ // GET /tunnel/ports for one PC: { connected, ports: [{ port, pcPort, macPort,
407
+ // listening, error?, connections }] }.
408
+ export function portsFor(clientId) {
409
+ const pc = pcs.get(clientId);
410
+ if (!pc) return { connected: false, ports: [] };
411
+ return {
412
+ connected: !!pc.control,
413
+ ports: [...pc.ports.values()].map(({ port, pcPort, macPort, listening: up, error, connections }) => (
414
+ up ? { port, pcPort, macPort, listening: true, connections } : { port, pcPort, macPort, listening: false, error, connections })),
415
+ };
416
+ }
417
+
418
+ // Whether a Mac port is listening for any PC's tunnel (the recipe's
419
+ // ctx.tunnel.listening(port), for the Metro warning).
420
+ export function listening(port) {
421
+ const n = Number(port);
422
+ for (const pc of pcs.values()) {
423
+ for (const p of pc.ports.values()) if (p.listening && p.macPort === n) return true;
424
+ }
425
+ return false;
426
+ }
427
+
428
+ // Everything of one PC: listeners, pending connections (reset), streams.
429
+ function teardown(pc) {
430
+ pc.closed = true;
431
+ if (pc.graceTimer) clearTimeout(pc.graceTimer);
432
+ pc.graceTimer = null;
433
+ for (const p of pc.ports.values()) closePort(p);
434
+ pc.ports.clear();
435
+ for (const entry of [...pc.pending]) {
436
+ drop(entry);
437
+ reset(entry.sock);
438
+ }
439
+ for (const s of [...pc.streams]) {
440
+ reset(s.mac);
441
+ reset(s.pc);
442
+ }
443
+ if (pcs.get(pc.id) === pc) pcs.delete(pc.id);
444
+ }
445
+
446
+ // Closes one PC's tunnel at once: the control WebSocket with `code` and
447
+ // `reason` (4001 unpaired, 4003 taken over), its listeners, its pending and
448
+ // open data streams.
449
+ export function closeFor(clientId, code, reason) {
450
+ const pc = pcs.get(clientId);
451
+ if (!pc) return;
452
+ const ctl = pc.control;
453
+ pc.control = null;
454
+ if (ctl) {
455
+ try { ctl.ws.close(code, String(reason || '').slice(0, 120)); } catch { /* gone */ }
456
+ }
457
+ log(`${pc.name}: tunnel closed (${code})`);
458
+ teardown(pc);
459
+ }
460
+
461
+ // Agent shutdown: closes every listener and stream (1001 to the control sockets).
462
+ export function stopAll() {
463
+ for (const id of [...pcs.keys()]) closeFor(id, 1001, 'agent stopping');
464
+ }
package/src/common.js ADDED
@@ -0,0 +1,119 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+
4
+ export const VERSION = '0.9.0';
5
+ // The agent's protocol range: it serves clients of protocol MIN_CLIENT_PROTOCOL
6
+ // to PROTOCOL, and reports the one it agrees on with each client (see
7
+ // negotiateProtocol). PROTOCOL must match the Rust core's (crates/core/src/version.rs,
8
+ // which also has MIN_AGENT_PROTOCOL, the client's half of the rule).
9
+ // test/version.test.js checks both. See "Versioning" in docs/protocol.md.
10
+ export const PROTOCOL = 2;
11
+ export const MIN_CLIENT_PROTOCOL = 2;
12
+ // Clients send their protocol with every request and upgrade.
13
+ export const PROTOCOL_HEADER = 'x-simcast-protocol';
14
+
15
+ // The protocol the agent reports to a client (`protocol` in /health and the
16
+ // hellos): min(header, max), where a missing or malformed header means 1 (a
17
+ // client too old to send it). Below `min` the agent reports `max`, so the
18
+ // client says "update this PC".
19
+ export function negotiateProtocol(header, { min = MIN_CLIENT_PROTOCOL, max = PROTOCOL } = {}) {
20
+ const raw = Array.isArray(header) ? header[0] : header;
21
+ const n = typeof raw === 'string' && /^\s*\d+\s*$/.test(raw) ? Number(raw) : 1;
22
+ const p = Math.min(n, max);
23
+ return p < min ? max : p;
24
+ }
25
+ export const DEFAULT_PORT = 7878;
26
+ export const DEFAULT_METRO_PORT = 8081;
27
+
28
+ // Never synced, at any depth.
29
+ export const IGNORE_ANYWHERE = new Set([
30
+ 'node_modules', '.git', '.expo', '.simcast', '.turbo', '.next',
31
+ 'coverage', 'Pods', '.DS_Store', 'Thumbs.db', '.gradle', '.idea',
32
+ ]);
33
+ // Never synced when they sit at the project root. ("ios" is added in prebuild mode.)
34
+ export const IGNORE_AT_ROOT = new Set(['android', 'dist', 'web-build']);
35
+
36
+ export const LOCKFILES = [
37
+ ['bun.lock', ['bun', 'install', '--frozen-lockfile']],
38
+ ['bun.lockb', ['bun', 'install', '--frozen-lockfile']],
39
+ ['pnpm-lock.yaml', ['pnpm', 'install', '--frozen-lockfile']],
40
+ ['yarn.lock', ['yarn', 'install', '--frozen-lockfile']],
41
+ ['package-lock.json', ['npm', 'ci']],
42
+ ];
43
+
44
+ export function sha1(data) {
45
+ return crypto.createHash('sha1').update(data).digest('hex');
46
+ }
47
+
48
+ export function sha1File(file) {
49
+ return new Promise((resolve, reject) => {
50
+ const hash = crypto.createHash('sha1');
51
+ fs.createReadStream(file)
52
+ .on('data', (chunk) => hash.update(chunk))
53
+ .on('end', () => resolve(hash.digest('hex')))
54
+ .on('error', reject);
55
+ });
56
+ }
57
+
58
+ export function globToRegExp(glob) {
59
+ const body = glob
60
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
61
+ .replace(/\*\*/g, '\u0000')
62
+ .replace(/\*/g, '[^/]*')
63
+ .replace(/\?/g, '[^/]')
64
+ .replace(/\u0000/g, '.*');
65
+ return new RegExp(`^${body}$`);
66
+ }
67
+
68
+ export function isValidProjectId(id) {
69
+ return typeof id === 'string' && /^[A-Za-z0-9._-]{1,120}$/.test(id) && id !== '.' && id !== '..';
70
+ }
71
+
72
+ // Relative POSIX path that cannot escape the project folder.
73
+ export function isSafeRelPath(p) {
74
+ if (typeof p !== 'string' || !p || p.includes('\0') || p.includes('\\')) return false;
75
+ if (p.startsWith('/') || /^[A-Za-z]:/.test(p)) return false;
76
+ return !p.split('/').some((seg) => seg === '..' || seg === '' || seg === '.');
77
+ }
78
+
79
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
80
+ const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : String(s));
81
+ export const color = {
82
+ bold: paint('1'), dim: paint('2'), red: paint('31'),
83
+ green: paint('32'), yellow: paint('33'), cyan: paint('36'),
84
+ };
85
+
86
+ // Pings a WebSocket and ends it when the other side stops answering, so a pulled
87
+ // cable, a dropped Wi-Fi link or a sleeping machine is noticed in seconds rather
88
+ // than when TCP gives up minutes later. Any incoming data also counts as a sign of life.
89
+ export const HEARTBEAT_MS = 1000;
90
+ export const HEARTBEAT_TIMEOUT_MS = 3000;
91
+ export function heartbeat(ws, { onDead } = {}) {
92
+ let lastSeen = Date.now();
93
+ const alive = () => { lastSeen = Date.now(); };
94
+ ws.on('pong', alive);
95
+ ws.on('message', alive);
96
+ const timer = setInterval(() => {
97
+ if (ws.readyState !== 1) return;
98
+ if (Date.now() - lastSeen > HEARTBEAT_TIMEOUT_MS) {
99
+ clearInterval(timer);
100
+ onDead?.();
101
+ ws.terminate();
102
+ return;
103
+ }
104
+ try { ws.ping(); } catch { /* closing */ }
105
+ }, HEARTBEAT_MS);
106
+ ws.on('close', () => clearInterval(timer));
107
+ return { lastSeen: () => lastSeen };
108
+ }
109
+
110
+ export async function mapLimit(items, limit, fn) {
111
+ let i = 0;
112
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
113
+ while (i < items.length) {
114
+ const idx = i++;
115
+ await fn(items[idx], idx);
116
+ }
117
+ });
118
+ await Promise.all(workers);
119
+ }