-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesbuild.mjs
207 lines (194 loc) · 5.81 KB
/
esbuild.mjs
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
import * as esbuild from "esbuild";
import * as child_process from "node:child_process";
import * as fs from "node:fs/promises";
import peggy from "peggy";
import * as readline from "node:readline";
import * as path from "node:path";
import peggyOptimizer from "@markw65/peggy-optimizer";
const cjsDir = "build";
const releaseBuild = process.argv.includes("--release");
const sourcemap = !releaseBuild;
let buildActive = 0;
function activate() {
if (!buildActive++) {
console.log(`${new Date().toLocaleString()} - Build active`);
}
}
function deactivate() {
setTimeout(() => {
if (!--buildActive) {
console.log(`${new Date().toLocaleString()} - Build inactive`);
}
}, 500);
}
function report(diagnostics, kind) {
diagnostics.forEach((diagnostic) => diagnostic.location.column++);
esbuild
.formatMessages(diagnostics, {
kind,
color: true,
terminalWidth: 100,
})
.then((messages) => messages.forEach((error) => console.log(error)));
}
const startEndPlugin = {
name: "startEnd",
setup(build) {
build.onStart(() => {
activate();
console.log(`${new Date().toLocaleString()} - ESBuild start`);
});
build.onEnd((result) => {
report(result.errors, "error");
report(result.warnings, "warning");
false &&
Object.entries(result.metafile.outputs).forEach(
([key, value]) =>
key.endsWith(".js") &&
console.log(`${key}: ${value.bytes >>> 10}kb`)
) &&
console.log("");
Object.entries(result.metafile?.outputs ?? {}).forEach(
([key, value]) =>
key.endsWith(".cjs") &&
value.bytes > 10000 &&
console.log(`${key}: ${value.bytes >>> 10}kb`)
);
console.log("");
console.log(`${new Date().toLocaleString()} - ESBuild end`);
deactivate();
});
},
};
const peggyPlugin = {
name: "peggy",
setup(build) {
build.onLoad({ filter: /\.peggy$/ }, async (args) => {
// Load the file from the file system
const source = await fs.readFile(args.path, "utf8");
const convertMessage = ({ message, location: loc }) => {
let location;
if (loc) {
const lineText = source.split(/\r\n|\r|\n/g)[loc.start.line - 1];
const lineEnd =
loc.start.line === loc.end.line ? loc.end.column : lineText.length;
location = {
file: args.path,
line: loc.start.line,
column: loc.start.column,
length: lineEnd - loc.start.column,
lineText,
};
}
return { text: message, location };
};
try {
const mapDir = path.resolve(build.initialOptions.outdir, "..");
const options = /** @type {const} */ {
cache: false,
format: "es",
grammarSource: args.path,
allowedStartRules: ["Start", "SingleExpression", "PersonalityStart"],
plugins: [peggyOptimizer],
};
if (build.initialOptions.sourcemap) {
const sourceAndMap = peggy
.generate(source, {
...options,
output: "source-and-map",
})
.toStringWithSourceMap({});
let contents = sourceAndMap.code;
const sourceMap = sourceAndMap.map.toJSON();
sourceMap.sources = sourceMap.sources.map((src) => {
return src === null ? null : path.relative(mapDir, src);
});
const map = `data:text/plain;base64,${Buffer.from(
JSON.stringify(sourceMap)
).toString("base64")}`;
contents += `\n//# sourceMappingURL=${map}`;
return { contents, loader: "js" };
} else {
return {
contents: peggy.generate(source, {
...options,
output: "source",
}),
};
}
} catch (e) {
return { errors: [convertMessage(e)] };
}
});
},
};
const cjsConfig = {
entryPoints: ["src/prettier-plugin-monkeyc.ts"],
bundle: true,
platform: "node",
outdir: `${cjsDir}`,
outExtension: { ".js": ".cjs" },
target: "node16.4",
external: ["prettier"],
format: "cjs",
plugins: [peggyPlugin, startEndPlugin],
sourcemap,
sourcesContent: false,
metafile: true,
minify: releaseBuild,
logLevel: "silent",
};
function spawnByLine(command, args, lineHandler, options) {
return new Promise((resolve, reject) => {
const proc = child_process.spawn(command, args, {
...(options || {}),
shell: false,
});
const rl = readline.createInterface({
input: proc.stdout,
});
const rle = readline.createInterface({
input: proc.stderr,
});
proc.on("error", reject);
proc.stderr.on("data", (data) => console.error(data.toString()));
rl.on("line", lineHandler);
rle.on("line", lineHandler);
proc.on("close", (code) => {
if (code === 0) resolve();
reject(code);
});
});
}
const npx = process.platform === "win32" ? "npx.cmd" : "npx";
const tscCommand = ["tsc", "--emitDeclarationOnly", "--outDir", "build/src"];
const logger = (line) => {
// tsc in watch mode does ESC-c to clear the screen
// eslint-disable-next-line no-control-regex
line = line.replace(/[\x1b]c/g, "");
if (
/Starting compilation in watch mode|File change detected\. Starting incremental compilation/.test(
line
)
) {
activate();
}
console.log(line);
if (/Found \d+ errors?\. Watching for file changes/.test(line)) {
deactivate();
}
};
if (process.argv.includes("--watch")) {
const ctx = await esbuild.context(cjsConfig);
await Promise.all([
ctx.watch(),
spawnByLine(npx, tscCommand.concat("--watch"), logger),
]);
} else {
await Promise.all([
esbuild.build(cjsConfig),
spawnByLine(npx, tscCommand, logger).then(() => {
console.log(`${new Date().toLocaleString()} - tsc end`);
}),
]);
}