-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess.ts
139 lines (116 loc) · 2.77 KB
/
process.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import { watch, WatchOptions } from "./deps.ts";
type OutputChannel = "stdout" | "stderr";
type CustomEventListener = (event: CustomEvent) => void | Promise<void>;
type ProcessParams = {
name: string;
cmd: string;
};
const { run, toAsyncIterator } = Deno;
class Process extends EventTarget {
readonly name: string;
readonly cmd: string;
public process: Deno.Process | undefined;
constructor({ name, cmd }: ProcessParams) {
super();
this.name = name;
this.cmd = cmd;
}
start() {
this.process = run({
args: this.cmd.split(/\s+/g),
stdout: "piped",
stderr: "piped"
});
this.publishOutput("stdout");
this.publishOutput("stderr");
return this;
}
async complete() {
return this.process?.status();
}
kill() {
if (!this.process) return;
this.process.kill(1);
}
on(type: OutputChannel, handler: CustomEventListener) {
super.addEventListener(type, handler as EventListener);
return this;
}
off(type: OutputChannel, handler: CustomEventListener) {
super.removeEventListener(type, handler as EventListener);
return this;
}
watch(options?: Partial<WatchOptions>) {
watch({
...(options ?? {}),
handle: (e: any) => {
this.kill();
options?.handle?.(e);
this.start();
}
});
return this;
}
private async publishOutput(channel: OutputChannel): Promise<void> {
if (!this.process) return;
for await (const message of toAsyncIterator(this.process[channel]!)) {
this.dispatchEvent(
new CustomEvent(channel, {
detail: message
})
);
}
}
}
class Plex {
private processes: Set<Process>;
constructor(processes: Process[]) {
this.processes = new Set(processes);
}
listen(
handler: CustomEventListener,
channels: OutputChannel[] = ["stdout", "stderr"]
) {
for (const p of this.processes) {
channels.forEach(channel => {
p.on(channel, handler);
p.on(channel, handler);
});
}
return this;
}
ignore(
handler: CustomEventListener,
channels: OutputChannel[] = ["stdout", "stderr"]
) {
for (const p of this.processes) {
channels.forEach(channel => {
p.off(channel, handler);
p.off(channel, handler);
});
}
return this;
}
start() {
this.processes.forEach(p => p.start());
return this;
}
kill() {
this.processes.forEach(p => p.kill());
}
watch(options?: Partial<WatchOptions>) {
watch({
...(options ?? {}),
handle: (e: any) => {
this.kill();
options?.handle?.(e);
this.start();
}
});
return this;
}
complete() {
return Promise.all([...this.processes].map(p => p.complete()));
}
}
export { Plex, Process, ProcessParams };