@celljs/ta-exec 4.7.0 → 4.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.
Files changed (100) hide show
  1. package/esm/node/exec-peer.js +1 -1
  2. package/esm/node/exec-protocol.d.ts +5 -1
  3. package/esm/node/exec-remote-source.js +2 -2
  4. package/esm/node/local-exec-environment.d.ts +2 -2
  5. package/esm/node/local-exec-environment.js +3 -3
  6. package/esm/node/remote-exec-environment.d.ts +2 -2
  7. package/esm/node/remote-exec-environment.js +2 -2
  8. package/lib/node/exec-peer.js +1 -1
  9. package/lib/node/exec-protocol.d.ts +5 -1
  10. package/lib/node/exec-remote-source.js +2 -2
  11. package/lib/node/local-exec-environment.d.ts +2 -2
  12. package/lib/node/local-exec-environment.js +2 -2
  13. package/lib/node/remote-exec-environment.d.ts +2 -2
  14. package/lib/node/remote-exec-environment.js +2 -2
  15. package/package.json +4 -3
  16. package/esm/node/exec-client.js.map +0 -1
  17. package/esm/node/exec-peer.js.map +0 -1
  18. package/esm/node/exec-protocol.js.map +0 -1
  19. package/esm/node/exec-remote-source.js.map +0 -1
  20. package/esm/node/exec-rpc.js.map +0 -1
  21. package/esm/node/exec-server.js.map +0 -1
  22. package/esm/node/exec-stdio.js.map +0 -1
  23. package/esm/node/index.js.map +0 -1
  24. package/esm/node/local-exec-environment.js.map +0 -1
  25. package/esm/node/remote-exec-environment.js.map +0 -1
  26. package/esm/node/ssh/node-dist.js.map +0 -1
  27. package/esm/node/ssh/ssh-askpass.js.map +0 -1
  28. package/esm/node/ssh/ssh-config.js.map +0 -1
  29. package/esm/node/ssh/ssh-host.js.map +0 -1
  30. package/esm/node/ssh/ssh-util.js.map +0 -1
  31. package/lib/node/exec-client.d.ts.map +0 -1
  32. package/lib/node/exec-client.js.map +0 -1
  33. package/lib/node/exec-peer.d.ts.map +0 -1
  34. package/lib/node/exec-peer.js.map +0 -1
  35. package/lib/node/exec-protocol.d.ts.map +0 -1
  36. package/lib/node/exec-protocol.js.map +0 -1
  37. package/lib/node/exec-remote-source.d.ts.map +0 -1
  38. package/lib/node/exec-remote-source.js.map +0 -1
  39. package/lib/node/exec-rpc.d.ts.map +0 -1
  40. package/lib/node/exec-rpc.js.map +0 -1
  41. package/lib/node/exec-server.d.ts.map +0 -1
  42. package/lib/node/exec-server.js.map +0 -1
  43. package/lib/node/exec-server.spec.d.ts +0 -2
  44. package/lib/node/exec-server.spec.d.ts.map +0 -1
  45. package/lib/node/exec-server.spec.js +0 -101
  46. package/lib/node/exec-server.spec.js.map +0 -1
  47. package/lib/node/exec-stdio.d.ts.map +0 -1
  48. package/lib/node/exec-stdio.js.map +0 -1
  49. package/lib/node/exec-stdio.spec.d.ts +0 -2
  50. package/lib/node/exec-stdio.spec.d.ts.map +0 -1
  51. package/lib/node/exec-stdio.spec.js +0 -105
  52. package/lib/node/exec-stdio.spec.js.map +0 -1
  53. package/lib/node/index.d.ts.map +0 -1
  54. package/lib/node/index.js.map +0 -1
  55. package/lib/node/local-exec-environment.d.ts.map +0 -1
  56. package/lib/node/local-exec-environment.js.map +0 -1
  57. package/lib/node/local-exec-environment.spec.d.ts +0 -2
  58. package/lib/node/local-exec-environment.spec.d.ts.map +0 -1
  59. package/lib/node/local-exec-environment.spec.js +0 -55
  60. package/lib/node/local-exec-environment.spec.js.map +0 -1
  61. package/lib/node/remote-exec-environment.d.ts.map +0 -1
  62. package/lib/node/remote-exec-environment.js.map +0 -1
  63. package/lib/node/ssh/node-dist.d.ts.map +0 -1
  64. package/lib/node/ssh/node-dist.js.map +0 -1
  65. package/lib/node/ssh/ssh-askpass.d.ts.map +0 -1
  66. package/lib/node/ssh/ssh-askpass.js.map +0 -1
  67. package/lib/node/ssh/ssh-config.d.ts.map +0 -1
  68. package/lib/node/ssh/ssh-config.js.map +0 -1
  69. package/lib/node/ssh/ssh-host.d.ts.map +0 -1
  70. package/lib/node/ssh/ssh-host.js.map +0 -1
  71. package/lib/node/ssh/ssh-host.spec.d.ts +0 -2
  72. package/lib/node/ssh/ssh-host.spec.d.ts.map +0 -1
  73. package/lib/node/ssh/ssh-host.spec.js +0 -182
  74. package/lib/node/ssh/ssh-host.spec.js.map +0 -1
  75. package/lib/node/ssh/ssh-util.d.ts.map +0 -1
  76. package/lib/node/ssh/ssh-util.js.map +0 -1
  77. package/lib/node/ssh/ssh-util.spec.d.ts +0 -2
  78. package/lib/node/ssh/ssh-util.spec.d.ts.map +0 -1
  79. package/lib/node/ssh/ssh-util.spec.js +0 -87
  80. package/lib/node/ssh/ssh-util.spec.js.map +0 -1
  81. package/src/node/exec-client.ts +0 -221
  82. package/src/node/exec-peer.ts +0 -186
  83. package/src/node/exec-protocol.ts +0 -84
  84. package/src/node/exec-remote-source.ts +0 -7
  85. package/src/node/exec-rpc.ts +0 -124
  86. package/src/node/exec-server.spec.ts +0 -110
  87. package/src/node/exec-server.ts +0 -107
  88. package/src/node/exec-stdio.spec.ts +0 -107
  89. package/src/node/exec-stdio.ts +0 -75
  90. package/src/node/index.ts +0 -14
  91. package/src/node/local-exec-environment.spec.ts +0 -58
  92. package/src/node/local-exec-environment.ts +0 -112
  93. package/src/node/remote-exec-environment.ts +0 -162
  94. package/src/node/ssh/node-dist.ts +0 -83
  95. package/src/node/ssh/ssh-askpass.ts +0 -117
  96. package/src/node/ssh/ssh-config.ts +0 -128
  97. package/src/node/ssh/ssh-host.spec.ts +0 -189
  98. package/src/node/ssh/ssh-host.ts +0 -300
  99. package/src/node/ssh/ssh-util.spec.ts +0 -97
  100. package/src/node/ssh/ssh-util.ts +0 -127
@@ -1,107 +0,0 @@
1
- import { afterAll, describe, expect, it } from 'bun:test';
2
- import { spawn } from 'node:child_process';
3
- import { mkdtempSync, writeFileSync } from 'node:fs';
4
- import { createServer } from 'node:net';
5
- import { tmpdir } from 'node:os';
6
- import { join } from 'node:path';
7
- import { ExecClient, type ExecConnection } from './exec-client';
8
- import { EXEC_REMOTE_SOURCE } from './exec-remote-source';
9
- import { RemoteExecEnvironment } from './remote-exec-environment';
10
-
11
- const root = mkdtempSync(join(tmpdir(), 'ta-exec-stdio-'));
12
- const script = join(root, 'exec-server.js');
13
- writeFileSync(script, EXEC_REMOTE_SOURCE.script);
14
-
15
- /** The script ta copies to other machines, on the standard input and output of a child, as over ssh. */
16
- function connect(banner = ''): () => Promise<ExecConnection> {
17
- return async () => {
18
- const child = spawn('/bin/sh', ['-c', `printf %s "$0"; exec node "$1"`, banner, script], { cwd: root, stdio: ['pipe', 'pipe', 'inherit'] });
19
- let rest = '';
20
- const listeners = new Set<(text: string) => void>();
21
- child.stdout.on('data', data => {
22
- const lines = (rest + data.toString()).split('\n');
23
- rest = lines.pop() ?? '';
24
- for (const line of lines) {
25
- for (const listener of listeners) {
26
- listener(line);
27
- }
28
- }
29
- });
30
- return {
31
- send: text => child.stdin.write(`${text}\n`),
32
- close: () => child.stdin.end(),
33
- onMessage: listener => listeners.add(listener),
34
- onClose: listener => child.once('close', () => listener()),
35
- };
36
- };
37
- }
38
-
39
- describe('ta exec-server on stdio', () => {
40
- const clients: ExecClient[] = [];
41
- const environment = (banner?: string) => {
42
- const client = new ExecClient({ connect: connect(banner), epoch: 1 });
43
- clients.push(client);
44
- return new RemoteExecEnvironment(client, root);
45
- };
46
-
47
- afterAll(() => {
48
- for (const client of clients) {
49
- client.close();
50
- }
51
- });
52
-
53
- it('is one script that needs no package', () => {
54
- expect(EXEC_REMOTE_SOURCE.hash).toMatch(/^[0-9a-f]{16}$/);
55
- expect(EXEC_REMOTE_SOURCE.script).not.toMatch(/require\("@celljs/);
56
- });
57
-
58
- it('runs commands and touches files, past what a login shell printed first', async () => {
59
- const env = environment('Welcome to the host\n');
60
- const chunks: Uint8Array[] = [];
61
- const { exitCode } = await env.exec('echo hello', { onData: data => chunks.push(data) });
62
- expect(exitCode).toBe(0);
63
- expect(Buffer.concat(chunks).toString()).toBe('hello\n');
64
- await env.writeFile('a.txt', 'text');
65
- expect(Buffer.from(await env.readFile('a.txt')).toString()).toBe('text');
66
- expect((await env.stat('a.txt'))?.size).toBe(4);
67
- });
68
-
69
- it('connects to a port of its machine, both ways', async () => {
70
- const server = createServer(socket => socket.on('data', data => socket.end(`echo:${data}`)));
71
- await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
72
- const { port } = server.address() as { port: number };
73
- try {
74
- const socket = await environment().connect(port);
75
- const received: Uint8Array[] = [];
76
- socket.onData(data => received.push(data));
77
- const closed = new Promise<void>(resolve => socket.onClose(resolve));
78
- socket.write(Buffer.from('ping'));
79
- await closed;
80
- expect(Buffer.concat(received).toString()).toBe('echo:ping');
81
- } finally {
82
- server.close();
83
- }
84
- });
85
-
86
- it('refuses to connect where nothing listens', async () => {
87
- const server = createServer();
88
- await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
89
- const { port } = server.address() as { port: number };
90
- await new Promise<void>(resolve => server.close(() => resolve()));
91
- await expect(environment().connect(port)).rejects.toThrow();
92
- });
93
-
94
- it('ends what the host started when its input ends', async () => {
95
- const env = environment();
96
- const pidFile = join(root, 'sleep.pid');
97
- const running = env.exec(`sh -c 'echo $$ > ${pidFile}; exec sleep 30'`);
98
- for (let i = 0; i < 50 && !(await env.stat('sleep.pid'))?.size; i++) {
99
- await new Promise(resolve => setTimeout(resolve, 20));
100
- }
101
- const pid = Number(Buffer.from(await env.readFile('sleep.pid')).toString());
102
- clients.at(-1)?.close();
103
- await expect(running).rejects.toThrow();
104
- await new Promise(resolve => setTimeout(resolve, 200));
105
- expect(() => process.kill(pid, 0)).toThrow();
106
- });
107
- });
@@ -1,75 +0,0 @@
1
- import { ExecPeer, type ExecPeerServer } from './exec-peer';
2
-
3
- export interface ExecStdioOptions {
4
- input: NodeJS.ReadableStream;
5
- output: NodeJS.WritableStream;
6
- /** Default: the working directory of the process. */
7
- cwd?: string;
8
- /**
9
- * Ends when nothing came for this long (milliseconds; the host pings): over ssh, a connection that
10
- * died silently leaves the input open, and the processes of the host must not run on. Default: never.
11
- */
12
- idleMs?: number;
13
- }
14
-
15
- /**
16
- * `ta exec-server` for one host on the standard input and output, one JSON-RPC message per line: how it
17
- * runs at the other end of ssh, which takes care of access. Everything the host started ends with the
18
- * input. The process prints nothing else on its standard output.
19
- */
20
- export class ExecStdio implements ExecPeerServer {
21
- readonly cwd: string;
22
- protected epoch?: number;
23
-
24
- constructor(protected readonly options: ExecStdioOptions) {
25
- this.cwd = options.cwd ?? process.cwd();
26
- }
27
-
28
- /** Resolves when the input ends, the host closed the connection, or it was idle too long. */
29
- serve(): Promise<void> {
30
- const { input, output, idleMs } = this.options;
31
- return new Promise(resolve => {
32
- let timer: ReturnType<typeof setTimeout> | undefined;
33
- let rest = '';
34
- const end = () => {
35
- clearTimeout(timer);
36
- input.removeListener('data', receive);
37
- peer.dispose();
38
- resolve();
39
- };
40
- const peer = new ExecPeer(this, { send: text => output.write(`${text}\n`), close: end });
41
- const watch = () => {
42
- if (idleMs) {
43
- clearTimeout(timer);
44
- timer = setTimeout(end, idleMs);
45
- }
46
- };
47
- const receive = (data: Buffer | string) => {
48
- watch();
49
- const lines = (rest + data.toString()).split('\n');
50
- rest = lines.pop() ?? '';
51
- for (const line of lines) {
52
- if (line.trim()) {
53
- void peer.receive(line);
54
- }
55
- }
56
- };
57
- input.on('data', receive);
58
- input.once('end', end);
59
- input.once('error', end);
60
- watch();
61
- });
62
- }
63
-
64
- admit(_peer: ExecPeer, epoch: number): boolean {
65
- if (this.epoch !== undefined && epoch < this.epoch) {
66
- return false;
67
- }
68
- this.epoch = epoch;
69
- return true;
70
- }
71
-
72
- isCurrent(epoch: number | undefined): boolean {
73
- return epoch === this.epoch;
74
- }
75
- }
package/src/node/index.ts DELETED
@@ -1,14 +0,0 @@
1
- export * from './exec-client';
2
- export * from './exec-peer';
3
- export * from './exec-protocol';
4
- export * from './exec-remote-source';
5
- export * from './exec-rpc';
6
- export * from './exec-server';
7
- export * from './exec-stdio';
8
- export * from './local-exec-environment';
9
- export * from './remote-exec-environment';
10
- export * from './ssh/node-dist';
11
- export * from './ssh/ssh-askpass';
12
- export * from './ssh/ssh-config';
13
- export * from './ssh/ssh-host';
14
- export * from './ssh/ssh-util';
@@ -1,58 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { mkdtempSync } from 'node:fs';
3
- import { tmpdir } from 'node:os';
4
- import { join } from 'node:path';
5
- import { LocalExecEnvironment } from './local-exec-environment';
6
-
7
- const environment = () => new LocalExecEnvironment(mkdtempSync(join(tmpdir(), 'ta-exec-')));
8
- const text = (chunks: Uint8Array[]) => Buffer.concat(chunks).toString();
9
-
10
- describe('LocalExecEnvironment', () => {
11
- it('runs a command in its directory and streams the output', async () => {
12
- const env = environment();
13
- const chunks: Uint8Array[] = [];
14
- const result = await env.exec('pwd; echo out; echo err >&2; exit 3', { onData: data => chunks.push(data) });
15
- expect(result.exitCode).toBe(3);
16
- expect(text(chunks)).toContain('out');
17
- expect(text(chunks)).toContain('err');
18
- });
19
-
20
- it('kills what the command started when aborted', async () => {
21
- const controller = new AbortController();
22
- const running = environment().exec('sleep 30 & wait', { signal: controller.signal });
23
- controller.abort();
24
- expect((await running).exitCode).not.toBe(0);
25
- });
26
-
27
- it('kills the command at the timeout', async () => {
28
- const start = Date.now();
29
- await environment().exec('sleep 30', { timeout: 50 });
30
- expect(Date.now() - start).toBeLessThan(5000);
31
- });
32
-
33
- it('reports a program that cannot start', async () => {
34
- const exit = await new Promise(done => environment().spawn('/no/such/program', []).onExit(done));
35
- expect(exit).toBeNull();
36
- });
37
-
38
- it('talks to a long-lived program over stdin and stdout', async () => {
39
- const child = environment().spawn('cat', []);
40
- const output = new Promise<string>(done => child.onStdout(data => done(Buffer.from(data).toString())));
41
- child.write('hello');
42
- expect(await output).toBe('hello');
43
- const exit = new Promise(done => child.onExit(done));
44
- child.kill();
45
- await exit;
46
- });
47
-
48
- it('reads, writes, lists and removes files relative to its directory', async () => {
49
- const env = environment();
50
- await env.mkdir('a/b');
51
- await env.writeFile('a/b/c.txt', 'data');
52
- expect(Buffer.from(await env.readFile(join(env.cwd, 'a/b/c.txt'))).toString()).toBe('data');
53
- expect(await env.readdir('a')).toEqual([{ name: 'b', isDirectory: true }]);
54
- expect((await env.stat('a/b'))?.isDirectory).toBe(true);
55
- await env.remove('a', { recursive: true });
56
- expect(await env.stat('a')).toBeUndefined();
57
- });
58
- });
@@ -1,112 +0,0 @@
1
- import { type ChildProcess, spawn } from 'node:child_process';
2
- import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
3
- import { resolve } from 'node:path';
4
- import type { DirEntry, ExecEnvironment, ExecOptions, ExecProcess, ExecResult, FileStat, SpawnOptions } from './exec-protocol';
5
-
6
- /** This machine. */
7
- export class LocalExecEnvironment implements ExecEnvironment {
8
- readonly local: boolean = true;
9
-
10
- constructor(readonly cwd: string) {}
11
-
12
- exec(command: string, options: ExecOptions = {}): Promise<ExecResult> {
13
- const [shell, ...args] = process.platform === 'win32' ? ['cmd.exe', '/d', '/s', '/c'] : ['/bin/sh', '-c'];
14
- const child = spawn(shell, [...args, command], {
15
- cwd: resolve(this.cwd, options.cwd ?? '.'),
16
- env: options.env ?? process.env,
17
- stdio: ['ignore', 'pipe', 'pipe'],
18
- // Its own process group: killing the shell must also end what the command started.
19
- detached: process.platform !== 'win32',
20
- });
21
- return new Promise(done => {
22
- const kill = () => this.killGroup(child);
23
- const timer = options.timeout ? setTimeout(kill, options.timeout) : undefined;
24
- options.signal?.addEventListener('abort', kill, { once: true });
25
- if (options.signal?.aborted) {
26
- kill();
27
- }
28
- child.stdout?.on('data', data => options.onData?.(data));
29
- child.stderr?.on('data', data => options.onData?.(data));
30
- const finish = (exitCode: number | null) => {
31
- clearTimeout(timer);
32
- options.signal?.removeEventListener('abort', kill);
33
- done({ exitCode });
34
- };
35
- child.once('error', () => finish(null));
36
- child.once('close', finish);
37
- });
38
- }
39
-
40
- spawn(command: string, args: string[], options: SpawnOptions = {}): ExecProcess {
41
- const child = spawn(command, args, {
42
- cwd: resolve(this.cwd, options.cwd ?? '.'),
43
- env: options.env ?? process.env,
44
- stdio: ['pipe', 'pipe', 'pipe'],
45
- });
46
- // Writes after the program ended surface as EPIPE here; onExit tells the owner.
47
- child.stdin.on('error', () => undefined);
48
- return {
49
- write: data => child.stdin.write(data),
50
- onStdout: listener => child.stdout.on('data', listener),
51
- onStderr: listener => child.stderr.on('data', listener),
52
- onExit: listener => {
53
- child.once('error', () => listener(null));
54
- child.once('close', listener);
55
- },
56
- kill: () => child.kill(),
57
- };
58
- }
59
-
60
- readFile(path: string): Promise<Uint8Array> {
61
- return readFile(this.resolve(path));
62
- }
63
-
64
- writeFile(path: string, data: Uint8Array | string): Promise<void> {
65
- return writeFile(this.resolve(path), data);
66
- }
67
-
68
- async stat(path: string): Promise<FileStat | undefined> {
69
- try {
70
- const info = await stat(this.resolve(path));
71
- return { isDirectory: info.isDirectory(), size: info.size, mtimeMs: info.mtimeMs };
72
- } catch (error) {
73
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
74
- return undefined;
75
- }
76
- throw error;
77
- }
78
- }
79
-
80
- async readdir(path: string): Promise<DirEntry[]> {
81
- const entries = await readdir(this.resolve(path), { withFileTypes: true });
82
- return entries.map(entry => ({ name: entry.name, isDirectory: entry.isDirectory() }));
83
- }
84
-
85
- async mkdir(path: string): Promise<void> {
86
- await mkdir(this.resolve(path), { recursive: true });
87
- }
88
-
89
- remove(path: string, options: { recursive?: boolean } = {}): Promise<void> {
90
- return rm(this.resolve(path), { recursive: options.recursive, force: true });
91
- }
92
-
93
- protected resolve(path: string): string {
94
- return resolve(this.cwd, path);
95
- }
96
-
97
- protected killGroup(child: ChildProcess): void {
98
- if (child.pid === undefined) {
99
- return;
100
- }
101
- if (process.platform !== 'win32') {
102
- try {
103
- process.kill(-child.pid, 'SIGKILL');
104
- return;
105
- } catch {
106
- // No such group (it ended, or the runtime did not give the shell its own group): the shell
107
- // itself, below, which a single command replaces.
108
- }
109
- }
110
- child.kill('SIGKILL');
111
- }
112
- }
@@ -1,162 +0,0 @@
1
- import type { ExecClient } from './exec-client';
2
- import type { DirEntry, ExecEnvironment, ExecOptions, ExecProcess, ExecResult, ExecSocket, FileStat, SpawnOptions } from './exec-protocol';
3
- import { ExecRpc } from './exec-rpc';
4
-
5
- type Listener<T extends unknown[]> = (...args: T) => void;
6
-
7
- /** A directory on the machine of a `ta exec-server`. */
8
- export class RemoteExecEnvironment implements ExecEnvironment {
9
- readonly local: boolean = false;
10
-
11
- constructor(
12
- protected readonly client: ExecClient,
13
- readonly cwd: string,
14
- ) {}
15
-
16
- async exec(command: string, options: ExecOptions = {}): Promise<ExecResult> {
17
- if (options.signal?.aborted) {
18
- return { exitCode: null };
19
- }
20
- const id = this.client.processId();
21
- const stop = this.client.listen(id, (method, params) => {
22
- if (method === ExecRpc.Notification.OUTPUT && params.data) {
23
- options.onData?.(ExecRpc.fromBase64(params.data));
24
- }
25
- });
26
- const kill = () => void this.client.call(ExecRpc.Method.KILL, { root: this.cwd, id }).catch(() => undefined);
27
- options.signal?.addEventListener('abort', kill, { once: true });
28
- try {
29
- const params: ExecRpc.ExecParams = {
30
- root: this.cwd,
31
- id,
32
- command,
33
- cwd: options.cwd,
34
- env: RemoteExecEnvironment.delta(options.env),
35
- timeout: options.timeout,
36
- };
37
- return await this.client.call<ExecResult>(ExecRpc.Method.EXEC, params);
38
- } finally {
39
- options.signal?.removeEventListener('abort', kill);
40
- stop();
41
- }
42
- }
43
-
44
- spawn(command: string, args: string[], options: SpawnOptions = {}): ExecProcess {
45
- const id = this.client.processId();
46
- const stdout = new Set<Listener<[Uint8Array]>>();
47
- const stderr = new Set<Listener<[Uint8Array]>>();
48
- const exit = new Set<Listener<[number | null]>>();
49
- let ended = false;
50
- const end = (exitCode: number | null) => {
51
- if (!ended) {
52
- ended = true;
53
- stop();
54
- for (const listener of exit) {
55
- listener(exitCode);
56
- }
57
- }
58
- };
59
- const stop = this.client.listen(id, (method, params) => {
60
- if (method === ExecRpc.Notification.EXIT) {
61
- end(params.exitCode ?? null);
62
- } else if (params.data) {
63
- const data = ExecRpc.fromBase64(params.data);
64
- for (const listener of method === ExecRpc.Notification.STDERR ? stderr : stdout) {
65
- listener(data);
66
- }
67
- }
68
- });
69
- const params: ExecRpc.SpawnParams = { root: this.cwd, id, command, args, cwd: options.cwd, env: RemoteExecEnvironment.delta(options.env) };
70
- this.client.call(ExecRpc.Method.SPAWN, params).catch(() => end(null));
71
- return {
72
- write: data => void this.client.call(ExecRpc.Method.WRITE, { root: this.cwd, id, data: ExecRpc.toBase64(data) }).catch(() => undefined),
73
- onStdout: listener => stdout.add(listener),
74
- onStderr: listener => stderr.add(listener),
75
- onExit: listener => exit.add(listener),
76
- kill: () => void this.client.call(ExecRpc.Method.KILL, { root: this.cwd, id }).catch(() => undefined),
77
- };
78
- }
79
-
80
- async readFile(path: string): Promise<Uint8Array> {
81
- return ExecRpc.fromBase64(await this.client.call<string>(ExecRpc.Method.READ_FILE, this.path(path)));
82
- }
83
-
84
- writeFile(path: string, data: Uint8Array | string): Promise<void> {
85
- return this.client.call(ExecRpc.Method.WRITE_FILE, { ...this.path(path), data: ExecRpc.toBase64(data) });
86
- }
87
-
88
- async stat(path: string): Promise<FileStat | undefined> {
89
- return (await this.client.call<FileStat | null>(ExecRpc.Method.STAT, this.path(path))) ?? undefined;
90
- }
91
-
92
- readdir(path: string): Promise<DirEntry[]> {
93
- return this.client.call(ExecRpc.Method.READDIR, this.path(path));
94
- }
95
-
96
- mkdir(path: string): Promise<void> {
97
- return this.client.call(ExecRpc.Method.MKDIR, this.path(path));
98
- }
99
-
100
- remove(path: string, options: { recursive?: boolean } = {}): Promise<void> {
101
- return this.client.call(ExecRpc.Method.REMOVE, { ...this.path(path), recursive: options.recursive });
102
- }
103
-
104
- async connect(port: number, host?: string): Promise<ExecSocket> {
105
- const id = this.client.processId();
106
- const data = new Set<Listener<[Uint8Array]>>();
107
- const closed = new Set<Listener<[]>>();
108
- let ended = false;
109
- const end = () => {
110
- if (!ended) {
111
- ended = true;
112
- stop();
113
- for (const listener of closed) {
114
- listener();
115
- }
116
- }
117
- };
118
- const stop = this.client.listen(id, (method, params) => {
119
- if (method === ExecRpc.Notification.NET_DATA && params.data) {
120
- const bytes = ExecRpc.fromBase64(params.data);
121
- for (const listener of data) {
122
- listener(bytes);
123
- }
124
- } else if (method === ExecRpc.Notification.NET_CLOSED || method === ExecRpc.Notification.EXIT) {
125
- end();
126
- }
127
- });
128
- try {
129
- await this.client.call(ExecRpc.Method.NET_CONNECT, { id, port, host } satisfies ExecRpc.ConnectParams);
130
- } catch (error) {
131
- stop();
132
- throw error;
133
- }
134
- return {
135
- write: bytes => void this.client.call(ExecRpc.Method.NET_WRITE, { id, data: ExecRpc.toBase64(bytes) }).catch(end),
136
- end: () => void this.client.call(ExecRpc.Method.NET_CLOSE, { id }).catch(end),
137
- onData: listener => data.add(listener),
138
- onClose: listener => (ended ? listener() : closed.add(listener)),
139
- };
140
- }
141
-
142
- protected path(path: string): ExecRpc.PathParams {
143
- return { root: this.cwd, path };
144
- }
145
-
146
- /**
147
- * What a tool sets on top of the environment. Tools pass this process's whole environment plus
148
- * their own variables; the host's variables (API keys among them) must not reach the other machine.
149
- */
150
- static delta(env: NodeJS.ProcessEnv | undefined): Record<string, string> | undefined {
151
- if (!env) {
152
- return undefined;
153
- }
154
- const delta: Record<string, string> = {};
155
- for (const [key, value] of Object.entries(env)) {
156
- if (value !== undefined && process.env[key] !== value) {
157
- delta[key] = value;
158
- }
159
- }
160
- return delta;
161
- }
162
- }
@@ -1,83 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { createReadStream, createWriteStream, existsSync, mkdirSync, renameSync, rmSync } from 'node:fs';
3
- import { join } from 'node:path';
4
-
5
- /** A build of Node.js, downloaded and checked. */
6
- export interface NodeTarball {
7
- version: string;
8
- file: string;
9
- }
10
-
11
- /**
12
- * Node.js for hosts that have none, from nodejs.org (or a mirror with the same layout): the latest 22,
13
- * checked against the SHA-256 sums published beside it, kept on this machine for the next host.
14
- */
15
- export namespace NodeDist {
16
- export const DEFAULT_MIRROR = 'https://nodejs.org/dist';
17
- export const LINE = 'latest-v22.x';
18
-
19
- /** The file name and sum of `platform` (`linux-x64`...) in a SHASUMS256.txt. */
20
- export function find(sums: string, platform: string): { name: string; sha256: string; version: string } | undefined {
21
- for (const line of sums.split('\n')) {
22
- const match = /^([0-9a-f]{64})\s+(node-(v[\d.]+)-([\w-]+)\.tar\.gz)$/.exec(line.trim());
23
- if (match && match[4] === platform) {
24
- return { sha256: match[1], name: match[2], version: match[3] };
25
- }
26
- }
27
- return undefined;
28
- }
29
-
30
- export async function download(platform: string, dir: string, mirror = DEFAULT_MIRROR, onVersion?: (version: string) => void): Promise<NodeTarball> {
31
- const base = `${mirror.replace(/\/+$/, '')}/${LINE}`;
32
- const sums = await get(`${base}/SHASUMS256.txt`);
33
- const found = find(await sums.text(), platform);
34
- if (!found) {
35
- throw new Error(`Node.js has no build for ${platform} at ${base}.`);
36
- }
37
- onVersion?.(found.version);
38
- mkdirSync(dir, { recursive: true });
39
- const file = join(dir, found.name);
40
- if (existsSync(file) && (await sha256(file)) === found.sha256) {
41
- return { version: found.version, file };
42
- }
43
- const response = await get(`${base}/${found.name}`);
44
- const partial = `${file}.${process.pid}.part`;
45
- const hash = createHash('sha256');
46
- const out = createWriteStream(partial);
47
- try {
48
- for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
49
- hash.update(chunk);
50
- if (!out.write(chunk)) {
51
- await new Promise(resolve => out.once('drain', resolve));
52
- }
53
- }
54
- await new Promise<void>((resolve, reject) => out.end((error?: Error | null) => (error ? reject(error) : resolve())));
55
- if (hash.digest('hex') !== found.sha256) {
56
- throw new Error(`The download of ${found.name} does not match its SHA-256 sum.`);
57
- }
58
- renameSync(partial, file);
59
- } finally {
60
- out.destroy();
61
- rmSync(partial, { force: true });
62
- }
63
- return { version: found.version, file };
64
- }
65
-
66
- async function get(url: string): Promise<Response> {
67
- const response = await fetch(url);
68
- if (!response.ok || !response.body) {
69
- throw new Error(`Cannot download ${url}: HTTP ${response.status}.`);
70
- }
71
- return response;
72
- }
73
-
74
- function sha256(file: string): Promise<string> {
75
- return new Promise((resolve, reject) => {
76
- const hash = createHash('sha256');
77
- createReadStream(file)
78
- .on('data', data => hash.update(data))
79
- .on('end', () => resolve(hash.digest('hex')))
80
- .on('error', reject);
81
- });
82
- }
83
- }