Debian Codegraph @

build.js

raw
1 #!/usr/bin/env node
2
3 import child_process from 'node:child_process';
4 import fs from 'node:fs';
5 import { createRequire } from 'node:module';
6 import os from 'node:os';
7 import path from 'node:path';
8 import process from 'node:process';
9
10 import { getFiles, getTestFiles, all_subdirs } from './files.js';
11
12 const production = process.env.NODE_ENV === 'production';
13 const useWasm = os.arch() != 'x64';
14
15 // ensure node_modules is present and up to date
16 child_process.spawnSync('tools/node-modules', ['make_package_lock_json'], { stdio: 'inherit' });
17
18 // List of directories to use when resolving import statements
19 const nodePaths = ['pkg/lib'];
20
21 // context options for distributed pages in dist/
22 const pkgOptions = {
23 ...!production ? { sourcemap: "linked" } : {},
24 bundle: true,
25 external: ['*.woff', '*.woff2', '*.jpg', '*.svg', '../../assets*'], // Allow external font files which live in ../../static/fonts
26 legalComments: 'external', // Move all legal comments to a .LEGAL.txt file
27 loader: {
28 ".js": "jsx",
29 ".py": "text",
30 ".sh": "text",
31 },
32 metafile: true,
33 minify: production,
34 nodePaths,
35 outbase: './pkg',
36 outdir: "./dist",
37 target: ['es2021'],
38 };
39
40 // context options for qunit tests in qunit/
41 const qunitOptions = {
42 sourcemap: "linked",
43 bundle: true,
44 minify: false,
45 nodePaths,
46 outbase: './pkg',
47 outdir: "./qunit",
48 loader: {
49 ".sh": "text",
50 },
51 };
52
53 const parser = (await import('argparse')).default.ArgumentParser();
54 parser.add_argument('-r', '--rsync', { help: "rsync bundles to ssh target after build", metavar: "HOST" });
55 parser.add_argument('-w', '--watch', { action: 'store_true', help: "Enable watch mode" });
56 parser.add_argument('onlydir', { nargs: '?', help: "The pkg/<DIRECTORY> to build (eg. base1, shell, ...)", metavar: "DIRECTORY" });
57 const args = parser.parse_args();
58
59 if (args.onlydir?.includes('/'))
60 parser.error("Directory must not contain '/'");
61
62 if (useWasm && args.watch)
63 parser.error("watch mode is not supported with esbuild-wasm");
64
65 if (args.onlydir)
66 process.env.ONLYDIR = args.onlydir;
67 if (args.rsync)
68 process.env.RSYNC = args.rsync;
69
70 // keep cockpit.js as global external, except on base1 (as that's what exports it), and kdump (for testing that bundling works)
71 const cockpitJSResolvePlugin = {
72 name: 'cockpit-js-resolve',
73 setup(build) {
74 build.onResolve({ filter: /^cockpit$/ }, args => {
75 if (args.resolveDir.endsWith('/base1') || args.resolveDir.endsWith('/kdump'))
76 return null;
77 return { path: args.path, namespace: 'external-global' };
78 });
79
80 build.onLoad({ filter: /.*/, namespace: 'external-global' },
81 args => ({ contents: `module.exports = ${args.path}` }));
82 },
83 };
84
85 // similar to fs.watch(), but recursively watches all subdirectories
86 function watch_dirs(dir, on_change) {
87 const callback = (ev, dir, fname) => {
88 // only listen for "change" events, as renames are noisy
89 if (ev !== "change")
90 return;
91 on_change(path.join(dir, fname));
92 };
93
94 fs.watch(dir, {}, (ev, path) => callback(ev, dir, path));
95
96 // watch all subdirectories in dir
97 const d = fs.opendirSync(dir);
98 let dirent;
99 while ((dirent = d.readSync()) !== null) {
100 if (dirent.isDirectory())
101 watch_dirs(path.join(dir, dirent.name), on_change);
102 }
103 d.closeSync();
104 }
105
106 async function build() {
107 // dynamic imports which need node_modules
108 const esbuild = await (async () => {
109 try {
110 // Try node_modules first for installs with devDependencies
111 return (await import(useWasm ? 'esbuild-wasm' : 'esbuild')).default;
112 } catch (e) {
113 if (e.code !== 'ERR_MODULE_NOT_FOUND')
114 throw e;
115
116 // Fall back to distro package (e.g. Debian's /usr/lib/*/nodejs/esbuild)
117 // Use createRequire to leverage Node's module resolution which searches system paths
118 // Use require.resolve to find esbuild in system paths, then import it
119 const require = createRequire(import.meta.url);
120 return (await import(require.resolve('esbuild'))).default;
121 }
122 })();
123
124 // Check if qunit is available
125 const qunitAvailable = await (async () => {
126 try {
127 await import('qunit');
128 return true;
129 } catch (e) {
130 if (e.code === 'ERR_MODULE_NOT_FOUND') {
131 console.log('qunit not found, skipping test builds');
132 return false;
133 }
134 throw e;
135 }
136 })();
137
138 const sassPlugin = (await import('esbuild-sass-plugin')).sassPlugin;
139
140 const cleanPlugin = (await import('./pkg/lib/esbuild-cleanup-plugin.js')).cleanPlugin;
141 const cockpitCompressPlugin = (await import('./pkg/lib/esbuild-compress-plugin.js')).cockpitCompressPlugin;
142 const cockpitPoEsbuildPlugin = (await import('./pkg/lib/cockpit-po-plugin.js')).cockpitPoEsbuildPlugin;
143 const cockpitRsyncEsbuildPlugin = (await import('./pkg/lib/cockpit-rsync-plugin.js')).cockpitRsyncEsbuildPlugin;
144 const cockpitTestHtmlPlugin = (await import('./pkg/lib/esbuild-test-html-plugin.js')).cockpitTestHtmlPlugin;
145 const cockpitRemoveRHIconsPlugin = (await import('./pkg/lib/cockpit-remove-rhicons-plugin.js')).cockpitRemoveRHIconsPlugin;
146
147 const { entryPoints, assetFiles, redhat_fonts } = getFiles(args.onlydir);
148 const tests = getTestFiles();
149 const testEntryPoints = tests.map(test => "pkg/" + test);
150
151 const pkgFirstPlugins = [
152 cleanPlugin({ subdir: args.onlydir }),
153 ];
154
155 const pkgPlugins = [
156 cockpitJSResolvePlugin,
157 sassPlugin({
158 loadPaths: [...nodePaths, 'node_modules'],
159 filter: /\.scss/,
160 quietDeps: true,
161 silenceDeprecations: [
162 "if-function" // https://github.com/patternfly/patternfly/issues/8077
163 ]
164 })
165 ];
166
167 const getTime = () => new Date().toTimeString().split(' ')[0];
168
169 const pkgLastPlugins = [
170 cockpitPoEsbuildPlugin({
171 subdirs: args.onlydir ? [args.onlydir] : all_subdirs,
172 // login page does not have cockpit.js, but reads window.cockpit_po
173 wrapper: subdir => subdir == "static" ? "window.cockpit_po = PO_DATA;" : undefined,
174 }),
175
176 // copy the static asset files determined in ./files.js
177 {
178 name: 'copy-assets',
179 setup(build) {
180 build.onEnd(() => {
181 for (const file of [...assetFiles, ...redhat_fonts]) {
182 const destDir = path.join('./dist', file.to);
183 fs.mkdirSync(destDir, { recursive: true });
184 fs.copyFileSync(file.from, path.join(destDir, path.basename(file.from)));
185 }
186 });
187 }
188 },
189
190 // HACK: filter out RH icons until they become default
191 // Reduces PF icon byte size by >50% per icon
192 cockpitRemoveRHIconsPlugin(),
193
194 // cockpit-ws cannot currently serve compressed login page
195 ...production ? [cockpitCompressPlugin({ subdir: args.onlydir, exclude: /\/static/ })] : [],
196
197 {
198 name: 'notify-end',
199 setup(build) {
200 build.onEnd(() => console.log(`${getTime()}: Build finished`));
201 }
202 },
203
204 ...(args.rsync || process.env.RSYNC)
205 ? [cockpitRsyncEsbuildPlugin({ source: "dist/" + (args.onlydir || '') })]
206 : [],
207 ];
208
209 if (useWasm) {
210 // build each entry point individually, as otherwise it runs out of memory
211 // See https://github.com/evanw/esbuild/issues/3006
212 const numEntries = entryPoints.length;
213 for (const [index, entryPoint] of entryPoints.entries()) {
214 console.log("building", entryPoint);
215 const context = await esbuild.context({
216 ...pkgOptions,
217 entryPoints: [entryPoint],
218 plugins: [
219 ...(index === 0 ? pkgFirstPlugins : []),
220 ...pkgPlugins,
221 ...(index === numEntries - 1 ? pkgLastPlugins : []),
222 ],
223 });
224
225 await context.rebuild();
226 context.dispose();
227 }
228
229 // build all tests in one go, they are small enough
230 if (qunitAvailable) {
231 console.log("building qunit tests");
232 const context = await esbuild.context({
233 ...qunitOptions,
234 entryPoints: testEntryPoints,
235 plugins: [
236 cockpitTestHtmlPlugin({ testFiles: tests }),
237 ],
238 });
239
240 await context.rebuild();
241 context.dispose();
242 }
243 } else {
244 // with native esbuild, build everything in one go, that's fastest
245 const pkgContext = await esbuild.context({
246 ...pkgOptions,
247 entryPoints,
248 plugins: [...pkgFirstPlugins, ...pkgPlugins, ...pkgLastPlugins],
249 });
250
251 const qunitContext = qunitAvailable
252 ? await esbuild.context({
253 ...qunitOptions,
254 entryPoints: testEntryPoints,
255 plugins: [
256 cockpitTestHtmlPlugin({ testFiles: tests }),
257 ],
258 })
259 : null;
260
261 try {
262 const results = await Promise.all([pkgContext.rebuild(), qunitContext?.rebuild()]);
263 // skip metafile and runtime module calculation in watch and onlydir modes
264 if (!args.watch && !args.onlydir) {
265 fs.writeFileSync('metafile.json', JSON.stringify(results[0].metafile));
266
267 // Extract bundled npm packages for dependency tracking
268 const bundledPackages = new Set();
269 for (const inputPath of Object.keys(results[0].metafile.inputs)) {
270 // Match paths like node_modules/package-name/ or node_modules/@scope/package-name/
271 const match = inputPath.match(/^node_modules\/(@[^/]+\/[^/]+|[^/]+)\//);
272 if (match)
273 bundledPackages.add(match[1]);
274 }
275
276 // Look up versions from package-lock.json and output simple format
277 const packageLock = JSON.parse(fs.readFileSync('package-lock.json', 'utf8'));
278 const deps = [];
279 for (const pkgName of Array.from(bundledPackages).sort()) {
280 const lockKey = `node_modules/${pkgName}`;
281 const pkgInfo = packageLock.packages?.[lockKey];
282 if (pkgInfo?.version)
283 deps.push(`${pkgName} ${pkgInfo.version}`);
284 else
285 console.error(`Warning: Could not find version for ${pkgName}`);
286 }
287 fs.writeFileSync('runtime-npm-modules.txt', deps.join('\n') + '\n');
288 }
289 } catch (e) {
290 const msg = String(e);
291 if (!msg.includes("Build failed"))
292 console.error("build.js:", msg);
293 if (!args.watch)
294 process.exit(1);
295 // ignore errors in watch mode
296 }
297
298 if (args.watch) {
299 const on_change = async path => {
300 console.log("change detected:", path);
301 await Promise.all([pkgContext.cancel(), qunitContext?.cancel()]);
302 try {
303 await Promise.all([pkgContext.rebuild(), qunitContext?.rebuild()]);
304 } catch (e) {} // ignore in watch mode
305 };
306
307 watch_dirs('pkg', on_change);
308 // wait forever until Control-C
309 await new Promise(() => {});
310 }
311
312 pkgContext.dispose();
313 qunitContext?.dispose();
314 }
315 }
316
317 build();