-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
build.ts
235 lines (219 loc) · 5.98 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import * as fsp from 'fs/promises';
import * as path from 'path';
import { build, BuildOptions, BuildResult, context, Metafile, Plugin } from "esbuild";
import ImportGlobPlugin from 'esbuild-plugin-import-glob';
import { program } from 'commander';
import archiver from 'archiver';
import type { ModInfo } from './src/vscode/ModPackageProvider';
import readdirGlob from 'readdir-glob';
function FactorioModPlugin():Plugin {
return {
name: 'factoriomod',
setup(build) {
build.onResolve({ filter: /^factoriomod:/ }, args=>{
if (args.resolveDir === '') {
return; // Ignore unresolvable paths
}
const apath = args.path.substring("factoriomod:".length);
return {
path: path.isAbsolute(apath) ? apath : path.join(args.resolveDir, apath),
namespace: 'factoriomod',
};
});
build.onLoad({ filter: /.*/, namespace: 'factoriomod' }, async (args)=>{
const packagejsonPath = path.join(process.argv[1], "../package.json");
const version = JSON.parse(await fsp.readFile(packagejsonPath, "utf8")).version;
const archive = archiver('zip', { zlib: { level: 9 }});
const templatePath = path.join(args.path, "info.template.json");
const info = <ModInfo>JSON.parse(await fsp.readFile(templatePath, "utf8"));
info.version = version;
await fsp.writeFile(path.join(args.path, "info.json"), JSON.stringify(info));
const files:string[] = [packagejsonPath, templatePath];
//@ts-expect-error cjs vs esm gone wrong here?
const globber = readdirGlob(args.path, {pattern: '**', nodir: true, ignore: ["*.template.json"]});
globber.on('match', (match:{ relative:string; absolute:string })=>{
files.push(match.absolute);
archive.file(match.absolute, { name: match.relative, prefix: `${info.name}_${info.version}` });
});
await new Promise<void>((resolve, reject)=>{
globber.on('end', ()=>{
resolve();
});
globber.on('error', (err:unknown)=>{
reject(err);
});
});
await archive.finalize();
const zip = archive.read();
return {
contents: zip,
loader: 'binary',
watchDirs: [ args.path ],
watchFiles: files,
};
});
},
};
}
// this is just a hack to resolve imports for the main `fmtk` to its bundled self
function ResolveFMTKPlugin():Plugin {
return {
name: 'resolveFMTK',
setup(build) {
build.onResolve({ filter: /^(\.\.\/)+fmtk$/ }, args=>{
return {
path: "./fmtk.js",
external: true,
namespace: 'fmtk',
};
});
},
};
}
class Watcher {
private activeBuilds = 0;
onStart() {
if (this.activeBuilds++ === 0) {
console.log("[watch] build started");
}
}
onEnd(result:BuildResult) {
result.errors.forEach((error)=>{
console.error(`> ${error.location?.file}:${error.location?.line}:${error.location?.column}: error: ${error.text}`);
});
if (--this.activeBuilds === 0) {
console.log("[watch] build finished");
}
}
plugin():Plugin {
const _this = this;
return {
name: 'watcher',
setup(build) {
build.onStart(()=>{ return _this.onStart(); });
build.onEnd((result)=>{ return _this.onEnd(result); });
},
};
}
}
const commonConfig:BuildOptions = {
tsconfig: "./tsconfig.json",
bundle: true,
outdir: "dist",
sourcemap: true,
sourcesContent: false,
platform: "node",
format: "cjs",
// `module` first for jsonc-parser
mainFields: ['module', 'main'],
loader: {
".html": "text",
".lua": "text",
".ttf": "copy",
},
plugins: [
],
};
const configs:BuildOptions[] = [
{
...commonConfig,
entryPoints: {
"fmtk": "./src/fmtk.ts",
},
plugins: [
ImportGlobPlugin(),
FactorioModPlugin(),
],
},
{
...commonConfig,
entryPoints: {
"fmtk-cli": "./src/cli/main.ts",
},
plugins: [
ResolveFMTKPlugin(),
],
},
{
...commonConfig,
entryPoints: {
"fmtk-vscode": "./src/vscode/extension.ts",
},
external: [
"vscode"
],
plugins: [
ResolveFMTKPlugin(),
],
},
{
...commonConfig,
platform: "browser",
format: "esm",
entryPoints: {
Flamegraph: "./src/Profile/Flamegraph.ts",
ModSettingsWebview: "./src/ModSettings/ModSettingsWebview.ts",
ScriptDatWebview: "./src/ScriptDat/ScriptDatWebview.ts",
},
external: [
"vscode-webview",
],
},
];
program
.option("--watch")
.option("--meta")
.option("--minify")
.action(async (options:{watch?:boolean; meta?:boolean; minify?:boolean})=>{
if (options.watch) {
const watcher = new Watcher();
configs.forEach(config=>config.plugins!.push(watcher.plugin()));
}
const optionsConfig:BuildOptions = {
metafile: options.meta,
minify: options.minify,
};
if (options.watch) {
const contexts = await Promise.all(
configs.map(config=>context({
...config,
...optionsConfig,
})));
await Promise.all(contexts.map(c=>c.watch()));
} else {
const result = await Promise.all(configs.map(config=>build({
...config,
...optionsConfig,
})));
if (options.meta) {
const metas = result.map(result=>result.metafile).filter(m=>!!m);
const merged:Metafile = {
inputs: {},
outputs: {},
};
for (const meta of metas) {
for (const key in meta.inputs) {
if (Object.prototype.hasOwnProperty.call(meta.inputs, key)) {
const input = meta.inputs[key];
if (merged.inputs[key]) {
merged.inputs[key].imports = merged.inputs[key].imports.concat(input.imports);
} else {
merged.inputs[key] = input;
}
}
}
for (const key in meta.outputs) {
if (Object.prototype.hasOwnProperty.call(meta.outputs, key)) {
const output = meta.outputs[key];
if (merged.outputs[key]) {
throw new Error("Duplicate Outputs");
} else {
merged.outputs[key] = output;
}
}
}
}
await fsp.writeFile(`./out/meta.json`, JSON.stringify(merged));
}
}
}).parseAsync();