-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.ts
209 lines (189 loc) · 6.09 KB
/
build.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import colors from "@colors/colors";
import { ChildProcess, fork } from "child_process";
import * as fsp from "fs/promises";
import { glob } from "glob";
import { Path } from "path-scurry";
import { exit } from "process";
import { parseArgs } from "util";
import { Job, globBundleFiles, transpile } from "./build-worker.js";
async function main() {
const { values, positionals } = parseArgs({
strict: false,
options: {
workers: { type: "string", short: "w", default: "0" },
},
});
const workers = parseInt(values.workers as string);
const transpiler = workers > 0 ? new MultiProcessTranspiler(workers) : new SingleProcessTranspiler();
const [mode] = positionals;
switch (mode ?? "build") {
// Watch mode transpiles files when they get changed.
case "watch":
await watch(transpiler);
break;
// Build mode transpiles everything and then exits.
case "build":
default:
await build(transpiler);
break;
}
return 0;
}
async function watch(transpiler: Transpiler) {
const queue = new WatchQueue(transpiler);
// Transpile everything when a common library or type definition changes.
for (const bundle of await globBundleFiles()) {
(async () => {
const watcher = fsp.watch(bundle.fullpath());
for await (const _ of watcher) {
queue.all();
}
})();
}
// Transpile each entry point individually.
for (const entry of await globEntryPoints()) {
(async () => {
const watcher = fsp.watch(entry.fullpath());
for await (const _ of watcher) {
queue.file(entry);
}
})();
}
await waitForever();
}
class WatchQueue {
private readonly minIntervalMs = 2 * 1000;
private lastAll: number | undefined = undefined;
private lastByFile: { [key: string]: number } = {};
private readonly transpiler: Transpiler;
constructor(transpiler: Transpiler) {
this.transpiler = transpiler;
}
async all() {
const now = nowTime();
if (this.allStale()) {
console.log("Transpiling all ...");
this.lastAll = now;
await build(this.transpiler);
}
}
async file(file: Path) {
const now = nowTime();
const key = file.fullpath();
const lastThis = this.lastByFile[key];
if (this.allStale() && (lastThis === undefined || now - lastThis > this.minIntervalMs)) {
console.log(`Transpiling ${file.relative()} ...`);
this.lastByFile[key] = now;
reportTimedResult(file, await this.transpiler.timedTranspileMs(file));
}
}
private allStale() {
return this.lastAll === undefined || nowTime() - this.lastAll > this.minIntervalMs;
}
}
interface Transpiler {
timedTranspileMs(entryFile: Path): Promise<number>;
}
/**
* Just calls the transpiler--no fancy workers. Includes a mutex so transpile
* times are reported correctly.
*/
class SingleProcessTranspiler implements Transpiler {
private mutex = false;
private waitingForMutex: (() => void)[] = [];
async timedTranspileMs(entryFile: Path) {
await this.getMutex();
const startMs = nowTime();
await transpile({
entryPathFromSrc: entryFile.relative(),
});
const endMs = nowTime();
this.releaseMutex();
return endMs - startMs;
}
private async getMutex() {
if (!this.mutex) {
this.mutex = true;
} else {
return await new Promise<void>(resolve => {
this.waitingForMutex.push(resolve);
});
}
}
private releaseMutex() {
const next = this.waitingForMutex.pop();
if (next !== undefined) {
next();
} else {
this.mutex = false;
}
}
}
/**
* Spawns other Node processes running build-worker.ts and uses them as a worker
* pool.
*/
class MultiProcessTranspiler implements Transpiler {
private workersToSpawn: number;
private waitingForWorker: ((worker: ChildProcess) => void)[] = [];
private spareWorkers: ChildProcess[] = [];
constructor(maxWorkers: number) {
this.workersToSpawn = maxWorkers;
}
async timedTranspileMs(entryFile: Path) {
const worker = await this.getWorker();
worker.send({
entryPathFromSrc: entryFile.relative(),
} as Job);
const startMs = nowTime();
await new Promise<void>(resolve => {
worker.on("message", resolve);
});
const endMs = nowTime();
this.returnWorker(worker);
return endMs - startMs;
}
private async getWorker() {
const spareWorker = this.spareWorkers.pop();
if (spareWorker !== undefined) {
return spareWorker;
} else if (this.workersToSpawn > 0) {
this.workersToSpawn--;
return fork("./build-worker.js", { stdio: ["ipc", "inherit", "inherit"] });
} else {
return await new Promise<ChildProcess>(resolve => {
this.waitingForWorker.push(resolve);
});
}
}
private returnWorker(worker: ChildProcess) {
worker.removeAllListeners("message");
const next = this.waitingForWorker.pop();
if (next !== undefined) {
next(worker);
} else {
this.spareWorkers.push(worker);
}
}
}
async function build(transpiler: Transpiler) {
const entryPoints = await globEntryPoints();
await Promise.all(
entryPoints.map(async entry => {
reportTimedResult(entry, await transpiler.timedTranspileMs(entry));
})
);
}
async function globEntryPoints() {
return await glob("mod/**/*.ts", { cwd: "./src", withFileTypes: true });
}
function reportTimedResult(file: Path, ms: number) {
console.log(`${colors.gray(file.relative())} ${ms}ms`);
}
function nowTime() {
return new Date().getTime();
}
async function waitForever() {
return new Promise((_resolve, _reject) => {});
}
exit(await main());