-
Notifications
You must be signed in to change notification settings - Fork 15
/
build
executable file
·169 lines (148 loc) · 5.83 KB
/
build
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
#!/usr/bin/env node
'use strict';
const child_process = require('child_process');
const fs = require('fs');
const path = require('path');
const esbuild = require('esbuild');
const minimist = require('minimist');
const tsup = require('tsup');
const argv = minimist(process.argv.slice(2), {default: {minify: false}});
const cwd = process.cwd();
const preamble = `window.pkmn=window.pkmn||{};window.pkmn.`;
const learnsets = `import * as LearnsetsJSON from './data/learnsets.json'; export {LearnsetsJSON};`;
const rewrite = async (result, name, pkg, suffix = '') => {
const files = (await result).outputFiles;
if (files.length !== 1) throw new Error(`Output unexpectedly has ${files.length} files`);
const minified = files[0];
const decoded = new TextDecoder().decode(minified.contents);
const start = `"use strict";var ${name}=`;
if (!decoded.startsWith(start)) {
throw new Error(`Output unexpectedly starts with: ${decoded.slice(0, 100)}`);
}
return fs.writeFileSync(minified.path,
`${preamble}${pkg}=${decoded.slice(start.length, -2)}${suffix};`);
};
const sh = (cmd, args) => child_process.execFileSync(cmd, args, {encoding: 'utf8', cwd});
const mkconfig = (tsconfig, format) => {
tsconfig.compilerOptions.noEmit = false;
tsconfig.compilerOptions.skipLibCheck = true;
tsconfig.compilerOptions.outDir = `build/${format}`;
tsconfig.compilerOptions.incremental = false;
tsconfig.compilerOptions.tsBuildInfoFile = null;
tsconfig.compilerOptions.module = format === 'cjs' ? 'CommonJS' : 'ESNext';
return tsconfig;
};
const tree = root => {
const leaves = [];
for (const child of fs.readdirSync(root)) {
if (['build', 'node_modules'].includes(child)) continue;
const p = path.join(root, child);
leaves.push(...(fs.lstatSync(p).isDirectory() ? tree(p) : [p]));
}
return leaves;
};
const cjs = path.join(cwd, 'tsconfig.cjs.json');
const esm = path.join(cwd, 'tsconfig.esm.json');
process.on('exit', () => {
try { fs.unlinkSync(cjs); } catch {}
try { fs.unlinkSync(esm); } catch {}
});
(async () => {
const pkg = path.basename(cwd);
// Oh boy, what fun! We need to use Typescript for this mess because things just won't bundle
if (!argv._.length) {
const time = process.hrtime.bigint();
const tsconfig = require(path.join(cwd, 'tsconfig.json'));
const running = cmd =>
console.log(`Running \x1b[96m${cmd}\x1b[0m for \x1b[34m@pkmn/${pkg}\x1b[0m...`);
fs.writeFileSync(cjs, JSON.stringify(mkconfig(tsconfig, 'cjs')));
running('tsc -p tsconfig.cjs.json');
sh('npx', ['tsc', '-p', 'tsconfig.cjs.json']);
if (!argv.cjs) {
fs.writeFileSync(esm, JSON.stringify(mkconfig(tsconfig, 'esm')));
running('tsc -p tsconfig.esm.json');
sh('npx', ['tsc', '-p', 'tsconfig.esm.json']);
console.log(`Cleaning up build output for \x1b[34m@pkmn/${pkg}\x1b[0m...`);
for (const file of tree(path.join(cwd, 'build', 'esm'))) {
if (file.endsWith('.d.ts')) {
fs.renameSync(file, `${file.slice(0, -3)}.mts`);
} else {
if (file.endsWith('.js')) {
const contents = fs.readFileSync(file, 'utf8');
if (!contents.endsWith('.js.map')) {
throw new Error(`Output unexpectedly ends with: ${contents.slice(-100)}`);
}
const relinked = `${contents.slice(0, -('.js.map'.length))}.mjs.map`;
const replaced = relinked.replaceAll(/from '(.*)';/g, (_, m) => {
if (!m.startsWith('.')) return `from '${m}';`;
const f = path.resolve(path.dirname(file), m);
if (fs.existsSync(`${f}.mjs`) || fs.existsSync(`${f}.js`)) {
return `from '${m}.mjs';`;
}
if (fs.existsSync(`${f}/index.mjs`) || fs.existsSync(`${f}/index.js`)) {
return `from '${m}/index.mjs';`;
}
throw new Error(`Cannot resolve import in ${file}: ${m}`);
});
fs.writeFileSync(`${file.slice(0, -3)}.mjs`, replaced);
fs.unlinkSync(file);
} if (file.endsWith('.js.map')) {
fs.renameSync(file, `${file.slice(0, -7)}.mjs.map`);
}
}
}
}
const millis = Math.round(Number((process.hrtime.bigint() - time) / BigInt(1e6)));
console.log(`\nFinished after \x1b[93m${millis}ms\x1b[0m`);
process.exit(0);
}
// We need to call esbuild/rollup through tsup to get declaration files
await tsup.build({
entry: argv._,
outDir: 'build',
format: ['cjs', 'esm'],
sourcemap: true,
splitting: true,
dts: true,
clean: true,
});
// Use esbuild directly for minified IIFE build to be able to rewrite
if (argv.minify) {
const globalName = `pkmn_${pkg}`;
let outfile = 'build/index.min.js';
console.log(`\nProducing \x1b[96m${outfile}\x1b[0m for \x1b[34m@pkmn/${pkg}\x1b[0m...`);
await rewrite(esbuild.build({
entryPoints: [argv._[0]],
bundle: true,
write: false,
external: pkg === 'dex' ? ['@pkmn/*', `./data/learnsets.json`] : ['@pkmn/*'],
// This required the build directory already exists which is why we wait for tsup
outfile,
format: 'iife',
minify: true,
globalName,
}), globalName, pkg);
if (pkg === 'dex') {
const tmp = path.join(cwd, 'learnsets.ts');
outfile = 'build/learnsets.min.js';
console.log(`Producing \x1b[96m${outfile}\x1b[0m for \x1b[34m@pkmn/${pkg}\x1b[0m...`);
try {
fs.writeFileSync(tmp, learnsets);
await rewrite(esbuild.build({
entryPoints: [tmp],
bundle: true,
write: false,
outfile,
format: 'iife',
minify: true,
globalName: 'pkmn_learnsets',
}), 'pkmn_learnsets', 'learnsets', '.LearnsetsJSON');
} finally {
try { fs.unlinkSync(tmp); } catch {}
}
}
}
})().catch(err => {
console.log(err);
process.exit(1);
});