Search / scripts /build /build_static_assets.mjs
vomebook
Prune redundant Reader and search code and release assets
bef5045
Raw History Blame Contribute Delete
6.55 kB
import { createHash } from "node:crypto";
import { existsSync, readdirSync, renameSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { dirname, extname, join, relative } from "node:path";
import { createRequire } from "node:module";
import { stripBundledScripts } from "./compose_app.mjs";
const resources = createRequire(import.meta.url)(join(process.cwd(), "static/reader-resources.js"));
const outputDir = process.env.STATIC_OUTPUT_DIR || "/out";
const replacements = new Map();
const bundleOnlyFiles = new Set(resources.bundleOnlyFiles);
const currentVendorAssets = new Set(Object.values(resources.vendors).map(vendor => "/static/" + vendor.path));
function rewrite(text, filename) {
text = text.replace(/(["'])(\.\.?\/[^"'\s]+)\1/g, (match, quote, url) => {
const target = join(dirname(filename), url);
const versioned = replacements.get(`/static/${target}`);
if (!versioned) return match;
let pinned = relative(dirname(filename), versioned.slice("/static/".length));
if (!pinned.startsWith(".")) pinned = "./" + pinned;
return quote + pinned + quote;
});
text = text.replace(/VoiceOfMLReaderResources\.engineAssets\(([\w$]+),\s*"(\/static\/)"\)/g,
// DjVu selection belongs to the browser, never the build host. Its vendor
// URLs are release-pinned; the other formats still need graph hash rewrites.
(_, extension, base) => `(["djvu","djv"].includes(${extension})?VoiceOfMLReaderResources.djvuSelectedAssets(${JSON.stringify(base)}):` + JSON.stringify(Object.fromEntries(["pdf", "md", "markdown", "html", "htm"].map(ext => [ext, resources.engineAssets(ext, base)]))) + `[${extension}]||[])`);
text = text.replace(/VoiceOfMLReaderResources\.(shellAssets|runtimePaths)\("(\/static\/)"\)/g,
(_, method, base) => JSON.stringify(resources[method](base).filter(url => !bundleOnlyFiles.has(url.slice(base.length)))));
for (const [original, versioned] of replacements) text = text.split(original).join(versioned);
return text;
}
// The image stages static/ wholesale; omit source copies already in the entry bundles.
for (const filename of bundleOnlyFiles) rmSync(join(outputDir, filename));
for (const filename of resources.releaseFiles("hf")) {
const source = join(outputDir, filename);
const text = readFileSync(source, "utf8");
for (const match of text.matchAll(/(?:\/static\/|\.\/)vendor\/([A-Za-z0-9._-]+\.[0-9a-f]{12}\.(?:js|mjs|css))/g))
currentVendorAssets.add("/static/vendor/" + match[1]);
const content = rewrite(text, filename);
writeFileSync(source, content);
const hash = createHash("sha256").update(content).digest("hex").slice(0, 12);
const extension = extname(filename);
const stem = filename.slice(0, -extension.length);
const versioned = `${stem}.${hash}${extension}`;
renameSync(source, join(outputDir, versioned));
replacements.set(`/static/${filename}`, `/static/${versioned}`);
replacements.set(`./${filename}`, `./${versioned}`);
}
for (const filename of ["index.html", "reader.html", "sw.js"]) {
const path = join(outputDir, filename);
let content = readFileSync(path, "utf8");
if (filename === "index.html") content = stripBundledScripts(content);
content = rewrite(content, filename);
if (filename === "sw.js") {
content = content.replace(/CURRENT_HASHED_ASSETS\s*=\s*\[\]/,
"CURRENT_HASHED_ASSETS=" + JSON.stringify([...replacements.values()].filter(url => url.startsWith("/")).concat([...currentVendorAssets], resources.djvuDecoderAssets("/static/"), resources.ruffleAssets("/static/"))));
content = content.replace(/\bREADER_SHELL_INTEGRITY\s*=\s*(["'])development\1/, () => {
const digest = createHash("sha256").update(readFileSync(join(outputDir, "reader.html"))).digest("base64");
return `READER_SHELL_INTEGRITY="sha256-${digest}"`;
});
const pdfSupport = Object.fromEntries(["cmaps", "standard_fonts", "wasm"].flatMap(dir => {
const parent = `vendor/${dir}`;
return !existsSync(join(outputDir, parent)) ? [] : readdirSync(join(outputDir, parent), { withFileTypes: true })
.filter(entry => entry.isFile()).map(({ name }) => `${parent}/${name}`).sort()
.map(path => [`/static/${path}`, "sha256-" + createHash("sha256")
.update(readFileSync(join(outputDir, path))).digest("base64")]);
}));
content = content.replace(/\bPDF_SUPPORT_INTEGRITY\s*=\s*\{\}/,
`PDF_SUPPORT_INTEGRITY=${JSON.stringify(pdfSupport)}`);
}
writeFileSync(path, content);
}
// Hash the rewritten graph and shells, with the version still a fixed marker
// (including the resulting digest itself would make the hash self-referential).
// Docker's subsequent SW minification preserves this stamped literal.
const workerPath = join(outputDir, "sw.js");
const worker = readFileSync(workerPath, "utf8");
const versionMarker = /\bCACHE_VERSION\s*=\s*(["'])development\1/g;
if ([...worker.matchAll(versionMarker)].length !== 1) {
throw new Error("sw.js must contain exactly one CACHE_VERSION = 'development' marker");
}
const cacheHash = createHash("sha256");
const generation = process.env.STATIC_SEARCH_DATA_GENERATION;
if (generation !== undefined) {
if (!/^[a-f0-9]{64}$/.test(generation)) throw new Error("Invalid verified search data generation");
cacheHash.update(`verified-space-generation:${generation}\n`);
}
function hashFile(filename) {
const content = readFileSync(join(outputDir, filename));
cacheHash.update(JSON.stringify([filename, content.length]) + "\n").update(content);
}
for (const filename of ["sw.js", "index.html", "reader.html"]) hashFile(filename);
// Bootstrap data and icons are not content-addressed. Runtime data may be
// supplied later in the image, so these inputs are optional in /out.
for (const filename of ["manifest.json", "data/generation-manifest.json", "data/reader_assets.json.gz",
"data/initial/manifest.json", "data/initial/global.json", "data/sidebar/manifest.json", "data/sidebar/global.json"]) {
if (existsSync(join(outputDir, filename))) hashFile(filename);
}
function hashIcons(directory) {
if (!existsSync(join(outputDir, directory))) return;
for (const entry of readdirSync(join(outputDir, directory), { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
const filename = directory + "/" + entry.name;
if (entry.isDirectory()) hashIcons(filename);
else if (entry.isFile()) hashFile(filename);
}
}
hashIcons("icons");
writeFileSync(workerPath, worker.replace(versionMarker, "CACHE_VERSION=" + JSON.stringify(cacheHash.digest("hex"))));