Files
pixel.horse/build-client.mjs
T

459 lines
14 KiB
JavaScript

import fs from 'fs';
import path from 'path';
import http from 'http';
import { spawn } from 'child_process';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
import * as esbuild from 'esbuild';
import * as sass from 'sass-embedded';
import swc from '@swc/core';
import remapping from '@jridgewell/remapping';
import pugTemplate from './tools/pug-template.cjs';
const root = path.dirname(fileURLToPath(import.meta.url));
const argv = new Set(process.argv.slice(2));
const argValue = name => process.argv.slice(2).find(a => a.startsWith(`--${name}=`))?.split('=')[1];
const dev = argv.has('--dev');
const jit = dev && !argv.has('--aot');
if (!jit && !global.angularPugHook) {
console.error('AOT build requires: node --require ./tools/angular-pug-hook.cjs build-client.mjs (or npm run client)');
process.exit(1);
}
const { createCompilerPlugin, SourceFileCache, getSupportedBrowsers, transformSupportedBrowsersToTargets } =
jit ? {} : await import('@angular/build/private');
const DEV_PORT = 8091;
const sassDeprecations = ['import', 'global-builtin', 'color-functions', 'if-function', 'slash-div'];
const bundles = [
{ name: 'bootstrap', tsconfig: 'tsconfig-aot.json', outDir: 'assets', tools: false, sourcemap: true },
{ name: 'bootstrap-admin', tsconfig: 'tsconfig-aot-admin.json', outDir: 'assets-admin', tools: true },
{ name: 'bootstrap-tools', tsconfig: 'tsconfig-aot-tools.json', outDir: 'assets', tools: true },
];
function selectBundles() {
const bundle = argValue('bundle');
if (bundle) {
const found = bundles.filter(b => b.name === bundle);
if (!found.length) {
throw new Error(`Unknown bundle: ${bundle}`);
}
return found;
}
else if (argv.has('--tools') || argv.has('--beta')) {
return bundles;
}
else if (argv.has('--main') || argv.has('--analyze')) {
return [bundles[0]];
}
else if (argv.has('--admin')) {
return [bundles[1]];
}
else {
return bundles;
}
}
function getAnalytics() {
const config = JSON.parse(fs.readFileSync(path.join(root, 'config.json'), 'utf8'));
return config.analytics ? `
(function(i, s, o, g, r, a, m) {i['GoogleAnalyticsObject']=r; i[r]=i[r]||function() {
(i[r].q=i[r].q||[]).push(arguments) }, i[r].l=1*new Date(); a=s.createElement(o),
m=s.getElementsByTagName(o)[0]; a.async=1; a.src=g; m.parentNode.insertBefore(a, m)
}) (window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', '${config.analytics.trackingID}', 'auto');
ga('send', 'pageview');
` : '';
}
const lodashPlugin = {
name: 'lodash',
setup(build) {
build.onResolve({ filter: /^lodash$/ }, args => /[\\/]node_modules[\\/]/.test(args.importer) ?
undefined : { path: path.join(root, 'src', 'ts', 'lodash.ts') });
},
};
function createOptions({ entryPoints, tsconfig, defines, sourcemap, cacheName, banner }) {
const cssTarget = transformSupportedBrowsersToTargets(getSupportedBrowsers(root, { warn: message => console.warn(message) }));
const sourceFileCache = new SourceFileCache(path.join(root, '.cache', 'angular', cacheName));
const optimize = !dev;
const angularPlugin = createCompilerPlugin({
tsconfig: path.join(root, tsconfig),
sourcemap: !!sourcemap,
jit: false,
advancedOptimizations: optimize,
thirdPartySourcemaps: false,
incremental: dev,
sourceFileCache,
loadResultCache: sourceFileCache.loadResultCache,
browserOnlyBuild: true,
}, {
workspaceRoot: root,
optimization: optimize,
inlineFonts: false,
sourcemap: false,
outputNames: { bundles: '[name]', media: 'media/[name]' },
includePaths: [path.join(root, 'src', 'styles')],
sass: { silenceDeprecations: sassDeprecations },
target: cssTarget,
inlineStyleLanguage: 'scss',
cacheOptions: {
enabled: true,
basePath: path.join(root, '.cache', 'angular'),
path: path.join(root, '.cache', 'angular', cacheName, 'styles'),
},
});
const options = {
absWorkingDir: root,
entryPoints,
outdir: path.join(root, 'dist', 'client'),
bundle: true,
format: 'iife',
platform: 'browser',
target: 'es2022',
write: false,
metafile: true,
sourcemap: sourcemap ? 'external' : false,
sourcesContent: true,
minify: false,
legalComments: dev ? 'none' : 'eof',
mainFields: ['es2020', 'es2015', 'browser', 'module', 'main'],
conditions: ['es2020', 'es2015', 'module'],
resolveExtensions: ['.ts', '.tsx', '.mjs', '.js', '.cjs'],
tsconfigRaw: {},
define: {
...Object.fromEntries(Object.entries(defines).map(([key, value]) => [key, JSON.stringify(value)])),
global: 'globalThis',
},
banner: banner ? { js: banner } : undefined,
logLevel: 'warning',
plugins: [lodashPlugin, angularPlugin],
};
return { options, sourceFileCache };
}
const minifyOptions = {
ecma: 5,
compress: { ecma: 5, arrows: false },
mangle: {
props: { regex: '^__', reserved: ['__default', '__symbol__'] },
},
format: { comments: false },
extractComments: 'some',
};
async function minify(name, code, map) {
if (argv.has('--debug')) {
const result = await esbuild.transform(code, { minify: true, target: 'es2022', sourcemap: !!map, legalComments: 'external' });
return { code: result.code, map: map && remapping([result.map, map], () => null).toString(), comments: result.legalComments };
}
const result = await swc.minify(code, { ...minifyOptions, sourceMap: !!map });
return {
code: result.code,
map: map && remapping([result.map, map], () => null).toString(),
comments: result.extractedComments?.join('\n'),
};
}
async function buildProd(bundle) {
const start = Date.now();
const defines = {
DEVELOPMENT: false,
TOOLS: bundle.tools,
SERVER: false,
BETA: argv.has('--beta'),
TIMING: argv.has('--timing'),
TESTS: false,
ngDevMode: false,
ngJitMode: false,
ngI18nClosureMode: false,
};
const banner = bundle.name === 'bootstrap' && !argv.has('--analyze') ? getAnalytics() : '';
const { options } = createOptions({
entryPoints: { [bundle.name]: `src/ts/${bundle.name}.ts` },
tsconfig: bundle.tsconfig,
defines,
sourcemap: bundle.sourcemap,
cacheName: bundle.name,
banner,
});
const result = await esbuild.build(options);
const js = result.outputFiles.find(f => f.path.endsWith(`${bundle.name}.js`));
const map = result.outputFiles.find(f => f.path.endsWith(`${bundle.name}.js.map`));
const minified = await minify(bundle.name, js.text.replace(/\n\/\/# sourceMappingURL=.*\n?$/, '\n'), map?.text);
const hash = crypto.createHash('md5').update(minified.code).digest('hex').slice(0, 10);
const fileName = `${bundle.name}-${hash}.js`;
const outDir = path.join(root, 'dist', 'browser', bundle.outDir, 'scripts');
fs.mkdirSync(outDir, { recursive: true });
if (minified.map) {
fs.writeFileSync(path.join(outDir, `${fileName}.map`), minified.map);
fs.writeFileSync(path.join(outDir, fileName), `${minified.code}\n//# sourceMappingURL=${fileName}.map`);
}
else {
fs.writeFileSync(path.join(outDir, fileName), minified.code);
}
if (minified.comments) {
fs.writeFileSync(path.join(outDir, `${fileName}.LICENSE.txt`), minified.comments);
}
if (argv.has('--analyze')) {
fs.writeFileSync(path.join(root, 'dist', `${bundle.name}-meta.json`), JSON.stringify(result.metafile));
console.log(await esbuild.analyzeMetafile(result.metafile));
}
const size = (Buffer.byteLength(minified.code) / 1024).toFixed(0);
console.log(`[${bundle.name}] ${path.relative(root, path.join(outDir, fileName))} ${size} KiB in ${((Date.now() - start) / 1000).toFixed(1)}s`);
}
function createJitPlugin() {
const cache = new Map();
const styleCache = new Map();
const plugin = {
name: 'angular-jit',
setup(build) {
build.onLoad({ filter: /\.ts$/ }, async ({ path: file }) => {
if (!cache.has(file)) {
cache.set(file, (async () => {
const imports = [];
const resource = (name, url) => {
const relative = /^\.{0,2}\//.test(url) ? url : `./${url}`;
imports.push(`import __${name}${imports.length} from '${relative}';`);
return `__${name}${imports.length - 1}`;
};
const source = (await fs.promises.readFile(file, 'utf8'))
.replace(/templateUrl:\s*'([^']+)'/g, (_, url) => `template: ${resource('template', url)}`)
.replace(/styleUrls:\s*\[\s*'([^']+)'\s*\]/g, (_, url) => `styles: [${resource('style', url)}]`);
const { code } = await swc.transform(imports.join('') + source, {
filename: file,
sourceMaps: 'inline',
jsc: {
parser: { syntax: 'typescript', decorators: true },
transform: { legacyDecorator: true, decoratorMetadata: true, useDefineForClassFields: true },
target: 'es2022',
},
module: { type: 'commonjs' },
});
return { contents: code, loader: 'js' };
})());
}
try {
return await cache.get(file);
}
catch (e) {
cache.delete(file);
throw e;
}
});
build.onLoad({ filter: /\.pug$/ }, ({ path: file }) => ({ contents: pugTemplate.compilePugTemplate(file), loader: 'text' }));
build.onLoad({ filter: /\.scss$/ }, async ({ path: file }) => {
if (!styleCache.has(file)) {
styleCache.set(file, sass.compileAsync(file, {
loadPaths: [path.join(root, 'src', 'styles')],
quietDeps: true,
silenceDeprecations: sassDeprecations,
}).then(result => ({ contents: result.css, loader: 'text' })));
}
try {
return await styleCache.get(file);
}
catch (e) {
styleCache.delete(file);
throw e;
}
});
},
};
const invalidate = files => {
files.forEach(file => cache.delete(file));
if (files.some(file => file.endsWith('.scss'))) {
styleCache.clear();
}
};
return { plugin, invalidate };
}
function createJitOptions(defines, banner) {
const jit = createJitPlugin();
const options = {
absWorkingDir: root,
entryPoints: Object.fromEntries(bundles.map(b => [b.name, `src/ts/${b.name}.ts`])),
bundle: true,
format: 'iife',
platform: 'browser',
target: 'es2022',
write: false,
mainFields: ['es2020', 'es2015', 'browser', 'module', 'main'],
conditions: ['es2020', 'es2015', 'module'],
resolveExtensions: ['.ts', '.tsx', '.mjs', '.js', '.cjs'],
tsconfigRaw: {},
define: {
...Object.fromEntries(Object.entries(defines).map(([key, value]) => [key, JSON.stringify(value)])),
global: 'globalThis',
},
banner: { js: banner },
logLevel: 'warning',
inject: [fileURLToPath(import.meta.resolve('@angular/compiler'))],
plugins: [lodashPlugin, jit.plugin],
};
return { options, invalidate: jit.invalidate };
}
function startTypeCheck() {
const tsc = spawn(process.execPath, [
path.join(root, 'node_modules', 'typescript-7', 'bin', 'tsc'),
'-p', 'tsconfig-aot-dev.json', '--noEmit', '--watch', '--preserveWatchOutput', '--pretty',
], { cwd: root, stdio: 'inherit' });
const kill = () => tsc.kill();
process.on('exit', kill);
['SIGINT', 'SIGTERM'].forEach(signal => process.on(signal, () => process.exit()));
}
const reloadBanner = `(() => {
const src = document.currentScript && document.currentScript.src;
if (src && typeof EventSource !== 'undefined') {
new EventSource(new URL('/reload', src)).onmessage = () => location.reload();
}
})();`;
async function runDev() {
const devDir = path.join(root, '.cache', 'dev-client');
const defines = { DEVELOPMENT: true, TOOLS: true, SERVER: false, BETA: true, TIMING: true, TESTS: false };
let options;
let invalidate;
if (!jit) {
let sourceFileCache;
({ options, sourceFileCache } = createOptions({
entryPoints: Object.fromEntries(bundles.map(b => [b.name, `src/ts/${b.name}.ts`])),
tsconfig: 'tsconfig-aot-dev.json',
defines,
sourcemap: true,
cacheName: 'dev',
banner: reloadBanner,
}));
invalidate = files => sourceFileCache.invalidate(files);
}
else {
({ options, invalidate } = createJitOptions(defines, reloadBanner));
startTypeCheck();
}
options.outdir = path.join(devDir, 'assets', 'scripts');
options.sourcemap = 'linked';
const files = new Map();
const reloadClients = new Set();
const context = await esbuild.context(options);
let building = Promise.resolve();
const rebuild = (changed = []) => {
building = building.then(async () => {
const start = Date.now();
if (changed.length) {
invalidate(changed);
}
try {
const result = await context.rebuild();
files.clear();
result.outputFiles.forEach(f => files.set(`/${path.relative(devDir, f.path).replace(/\\/g, '/')}`, f.contents));
console.log(`[client] built in ${((Date.now() - start) / 1000).toFixed(1)}s`);
reloadClients.forEach(res => res.write('data: reload\n\n'));
}
catch {
console.log(`[client] build failed in ${((Date.now() - start) / 1000).toFixed(1)}s, waiting for changes`);
}
});
return building;
};
await rebuild();
let pending = new Set();
let timeout;
const onChange = dir => (_event, fileName) => {
if (!fileName || /(^|[\\/])\./.test(fileName)) {
return;
}
pending.add(path.join(dir, fileName));
clearTimeout(timeout);
timeout = setTimeout(() => {
const changed = [...pending];
pending = new Set();
rebuild(changed);
}, 50);
};
for (const dir of [path.join(root, 'src', 'ts'), path.join(root, 'src', 'styles')]) {
fs.watch(dir, { recursive: true }, onChange(dir));
}
const types = { '.js': 'application/javascript', '.map': 'application/json', '.css': 'text/css' };
http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost').pathname;
const headers = { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache' };
if (url === '/reload') {
res.writeHead(200, { ...headers, 'Content-Type': 'text/event-stream' });
res.write('\n');
reloadClients.add(res);
req.on('close', () => reloadClients.delete(res));
return;
}
await building;
const contents = files.get(url);
if (contents) {
res.writeHead(200, { ...headers, 'Content-Type': types[path.extname(url)] || 'application/octet-stream' });
res.end(contents);
}
else {
res.writeHead(404, headers);
res.end();
}
}).listen(DEV_PORT, '0.0.0.0', () => console.log(`[client] dev server on http://localhost:${DEV_PORT}/assets/scripts/`));
}
if (dev) {
await runDev();
}
else {
const start = Date.now();
try {
await Promise.all(selectBundles().map(buildProd));
console.log(`[client] done in ${((Date.now() - start) / 1000).toFixed(1)}s`);
process.exit(0);
}
catch (e) {
if (!e.errors) {
console.error(e);
}
process.exit(1);
}
}