forked from QwikDev/qwik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubmodule-optimizer.ts
195 lines (174 loc) · 5.76 KB
/
submodule-optimizer.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
import { build, BuildOptions } from 'esbuild';
import {
access,
BuildConfig,
getBanner,
injectGlobalThisPoly,
nodeTarget,
readFile,
target,
watcher,
writeFile,
} from './util';
import { join } from 'path';
import { minify } from 'terser';
import { platformArchTriples } from '@napi-rs/triples';
import { readPackageJson } from './package-json';
import { watch } from 'rollup';
import { constants } from 'fs';
import { inlineQwikScriptsEsBuild } from './submodule-qwikloader';
/**
* Builds @builder.io/optimizer
*/
export async function submoduleOptimizer(config: BuildConfig) {
const submodule = 'optimizer';
await generatePlatformBindingsData(config);
async function buildOptimizer() {
const opts: BuildOptions = {
entryPoints: [join(config.srcDir, submodule, 'src', 'index.ts')],
entryNames: 'optimizer',
outdir: config.distPkgDir,
bundle: true,
sourcemap: false,
target,
external: [
/* no nodejs built-in externals allowed! */
],
incremental: config.watch,
};
const qwikloaderScripts = await inlineQwikScriptsEsBuild(config);
const esmBuild = build({
...opts,
format: 'esm',
banner: { js: getBanner('@builder.io/qwik/optimizer', config.distVersion) },
outExtension: { '.js': '.mjs' },
define: {
'globalThis.IS_CJS': 'false',
'globalThis.IS_ESM': 'true',
'globalThis.QWIK_VERSION': JSON.stringify(config.distVersion),
...qwikloaderScripts,
},
watch: watcher(config, submodule),
});
const cjsBanner = [
injectGlobalThisPoly(),
`globalThis.qwikOptimizer = (function (module) {`,
].join('\n');
const cjsBuild = build({
...opts,
format: 'cjs',
banner: { js: cjsBanner },
footer: {
js: `return module.exports; })(typeof module === 'object' && module.exports ? module : { exports: {} });`,
},
outExtension: { '.js': '.cjs' },
define: {
'globalThis.IS_CJS': 'true',
'globalThis.IS_ESM': 'false',
'globalThis.QWIK_VERSION': JSON.stringify(config.distVersion),
...qwikloaderScripts,
},
watch: watcher(config),
platform: 'node',
target: nodeTarget,
});
const [esm, cjs] = await Promise.all([esmBuild, cjsBuild]);
if (!config.dev) {
const esmDist = join(config.distPkgDir, 'optimizer.mjs');
const cjsDist = join(config.distPkgDir, 'optimizer.cjs');
await Promise.all(
[esmDist, cjsDist].map(async (p) => {
const src = await readFile(p, 'utf-8');
const result = await minify(src, {
compress: {
booleans: false,
collapse_vars: false,
comparisons: false,
drop_debugger: false,
expression: false,
keep_classnames: true,
inline: false,
if_return: false,
join_vars: false,
loops: false,
passes: 1,
reduce_funcs: false,
reduce_vars: false,
sequences: false,
switches: false,
},
format: {
comments: false,
braces: true,
beautify: true,
indent_level: 2,
preamble: getBanner('@builder.io/qwik/optimizer', config.distVersion),
},
mangle: false,
});
await writeFile(p, result.code!);
})
);
}
console.log('🐹', submodule);
if (config.watch) {
const watcher = watch({ input: join(config.distPkgDir, 'prefetch.debug.js') });
watcher.on('change', () => {
esm.stop!();
cjs.stop!();
watcher.close();
setTimeout(buildOptimizer);
});
}
}
await Promise.all([buildOptimizer()]);
}
async function generatePlatformBindingsData(config: BuildConfig) {
// generate the platform binding information for only what qwik provides
// allows us to avoid using a file system in the optimizer, take a look at:
// - node_modules/@node-rs/helper/lib/loader.js
// - node_modules/@napi-rs/triples/index.js
const pkg = await readPackageJson(join(config.packagesDir, 'qwik'));
const bindingFiles = pkg
.files!.filter((f) => f.startsWith('bindings/'))
.map((f) => f.replace('bindings/', ''));
const qwikArchTriples: typeof platformArchTriples = {};
for (const platformName in platformArchTriples) {
const platform = platformArchTriples[platformName];
for (const archName in platform) {
const triples = platform[archName];
for (const triple of triples) {
const qwikArchABI = `qwik.${triple.platformArchABI}.node`;
if (bindingFiles.includes(qwikArchABI)) {
const qwikTriple = {
platform: triple.platform,
arch: triple.arch,
abi: triple.abi,
platformArchABI: qwikArchABI,
};
qwikArchTriples[platformName] = qwikArchTriples[platformName] || {};
qwikArchTriples[platformName][archName] = qwikArchTriples[platformName][archName] || [];
qwikArchTriples[platformName][archName].push(qwikTriple as any);
}
}
}
}
const c: string[] = [];
c.push(`// AUTO-GENERATED IN OPTIMIZER BUILD SCRIPT`);
c.push(`// created from data provided by @napi-rs/triples`);
c.push(``);
c.push(`// prettier-ignore`);
c.push(`export const QWIK_BINDING_MAP = ${JSON.stringify(qwikArchTriples, null, 2)};`);
const code = c.join('\n') + '\n';
const platformBindingPath = join(config.srcDir, 'optimizer', 'src', 'qwik-binding-map.ts');
let isWritable;
try {
await access(platformBindingPath, constants.W_OK);
isWritable = true;
} catch (e) {
isWritable = false;
}
if (isWritable) {
await writeFile(platformBindingPath, code);
}
}