64 lines
3.4 KiB
JavaScript
64 lines
3.4 KiB
JavaScript
import { build } from 'esbuild';
|
|
import { existsSync, readFileSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';
|
|
import { join, relative, resolve, sep } from 'node:path';
|
|
|
|
const walk = dir => readdirSync(dir, { withFileTypes: true }).flatMap(entry =>
|
|
entry.isDirectory() ? walk(join(dir, entry.name)) : [join(dir, entry.name)]);
|
|
|
|
// Version the entire application module graph, including lazy imports. Versioning
|
|
// only an HTML entry does not invalidate its unversioned dependencies in browsers.
|
|
export async function versionSiteAssets(root, buildId, pages, {
|
|
moduleDirectory = 'js', externalDirectories = [], externalUrls = {}, publicPath = '/',
|
|
} = {}) {
|
|
root = realpathSync(root);
|
|
const jsRoot = join(root, moduleDirectory);
|
|
const externalRoots = externalDirectories.map(directory => ({ directory, root: resolve(root, directory) + sep }));
|
|
const version = url => {
|
|
const parsed = new URL(url, 'https://build.invalid/');
|
|
parsed.searchParams.set('v', buildId);
|
|
return url.split(/[?#]/)[0] + parsed.search + parsed.hash;
|
|
};
|
|
const files = walk(jsRoot).filter(file => file.endsWith('.js'));
|
|
const result = await build({
|
|
entryPoints: files, outdir: jsRoot, outbase: jsRoot,
|
|
bundle: true, format: 'esm', write: false, treeShaking: false,
|
|
minify: false, charset: 'utf8', logLevel: 'silent',
|
|
plugins: [{ name: 'version-app-imports', setup(builder) {
|
|
builder.onResolve({ filter: /.*/ }, args => {
|
|
if (args.kind === 'entry-point') return;
|
|
const path = args.path.split(/[?#]/)[0];
|
|
if (path.startsWith('.') || path.startsWith('/')) {
|
|
if (path.startsWith('/') && !path.startsWith(publicPath)) return { path: args.path, external: true };
|
|
const target = path.startsWith('/') ? resolve(root, path.slice(publicPath.length)) : resolve(args.resolveDir, path);
|
|
// Independently deployed modules retain their own release and cache identity.
|
|
const independent = externalRoots.find(directory => target.startsWith(directory.root));
|
|
if (independent) {
|
|
const url = externalUrls[independent.directory];
|
|
return { path: url ? url.replace(/\/$/, '') + '/' + relative(independent.root, target).split(sep).join('/') + args.path.slice(path.length) : args.path, external: true };
|
|
}
|
|
const rel = relative(jsRoot, target);
|
|
if (!rel.startsWith('..' + sep) && !rel.startsWith(sep) && target.endsWith('.js')) {
|
|
if (!existsSync(target)) throw new Error(`Missing application module: ${args.path} in ${args.importer}`);
|
|
return { path: version(args.path), external: true };
|
|
}
|
|
}
|
|
// Keep import-map entries and vendor URLs identical: Three must remain
|
|
// a single shared instance across the viewers and their addons.
|
|
return { path: args.path, external: true };
|
|
});
|
|
} }],
|
|
});
|
|
for (const output of result.outputFiles) writeFileSync(output.path, output.contents);
|
|
for (const page of pages) {
|
|
const file = join(root, page);
|
|
const html = readFileSync(file, 'utf8').replace(
|
|
/(<(?:script|link)\b[^>]*?\b(?:src|href)\s*=\s*)(["'])([^"']+)\2/gi,
|
|
(_, prefix, quote, url) => {
|
|
const local = url.startsWith('/') ? (url.startsWith(publicPath) ? url.slice(publicPath.length) : '') : url;
|
|
return `${prefix}${quote}${/^(?:js\/[^?#]+\.js|css\/[^?#]+\.css)(?:[?#]|$)/i.test(local) ? version(url) : url}${quote}`;
|
|
},
|
|
);
|
|
writeFileSync(file, html);
|
|
}
|
|
}
|