forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
85 lines (75 loc) · 2.25 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { SpawnOptions, spawn } from 'node:child_process';
import { AddressInfo, createConnection, createServer } from 'node:net';
import { Observable, mergeMap, retryWhen, throwError, timer } from 'rxjs';
import treeKill from 'tree-kill';
export function getAvailablePort(): Promise<number> {
return new Promise((resolve, reject) => {
const server = createServer();
server
.unref()
.on('error', reject)
.listen(0, () => {
const { port } = server.address() as AddressInfo;
server.close(() => resolve(port));
});
});
}
export function spawnAsObservable(
command: string,
args: string[] = [],
options: SpawnOptions = {},
): Observable<{ stdout?: string; stderr?: string }> {
return new Observable((obs) => {
const proc = spawn(command, args, options);
if (proc.stdout) {
proc.stdout.on('data', (data) => obs.next({ stdout: data.toString() }));
}
if (proc.stderr) {
proc.stderr.on('data', (data) => obs.next({ stderr: data.toString() }));
}
proc
.on('error', (err) => obs.error(err))
.on('close', (code) => {
if (code !== 0) {
obs.error(new Error(`${command} exited with ${code} code.`));
}
obs.complete();
});
return () => {
if (!proc.killed && proc.pid) {
treeKill(proc.pid, 'SIGTERM');
}
};
});
}
export function waitUntilServerIsListening(port: number, host?: string): Observable<undefined> {
const allowedErrorCodes = ['ECONNREFUSED', 'ECONNRESET'];
return new Observable<undefined>((obs) => {
const client = createConnection({ host, port }, () => {
obs.next(undefined);
obs.complete();
}).on('error', (err) => obs.error(err));
return () => {
if (!client.destroyed) {
client.destroy();
}
};
}).pipe(
retryWhen((err) =>
err.pipe(
mergeMap((error, attempts) => {
return attempts > 10 || !allowedErrorCodes.includes(error.code)
? throwError(error)
: timer(100 * (attempts * 1));
}),
),
),
);
}