| 1 | import { createHash } from "node:crypto"; |
| 2 | import { readFile, readdir, stat, writeFile } from "node:fs/promises"; |
| 3 | import { join, resolve } from "node:path"; |
| 4 | import { fileURLToPath } from "node:url"; |
| 5 | import { spawnSync } from "node:child_process"; |
| 6 | |
| 7 | const defaultDirectory = fileURLToPath(new URL("../../internal/workbench/web/", import.meta.url)); |
| 8 | export async function verifyBuild(directory = defaultDirectory) { |
| 9 | const files = {}; |
| 10 | async function inspect(relative = "") { |
| 11 | for (const entry of await readdir(join(directory, relative), { withFileTypes: true })) { |
| 12 | const name = [relative, entry.name].filter(Boolean).join("/"); |
| 13 | if (entry.isDirectory()) { await inspect(name); continue; } |
| 14 | if (name === "README" || name === "build-integrity.json") continue; |
| 15 | const bytes = await readFile(join(directory, name)); |
| 16 | if (bytes.length === 0) throw new Error(`Empty build resource: ${name}`); |
| 17 | if (/\.(?:js|css|html)$/.test(name)) { |
| 18 | if (bytes.includes(0)) throw new Error(`NUL bytes in build resource: ${name}`); |
| 19 | if (name.endsWith(".js")) { |
| 20 | const parsed = spawnSync(process.execPath, ["--check", "--input-type=module"], { input: bytes, encoding: "utf8" }); |
| 21 | if (parsed.error) throw parsed.error; |
| 22 | if (parsed.status !== 0) throw new Error(`Invalid JavaScript build resource: ${name}\n${parsed.stderr}`); |
| 23 | } |
| 24 | } |
| 25 | files[name] = createHash("sha256").update(bytes).digest("hex"); |
| 26 | } |
| 27 | } |
| 28 | await inspect(); |
| 29 | for (const entry of ["index.html", "mobile.html"]) { |
| 30 | const html = await readFile(join(directory, entry), "utf8"); |
| 31 | const scripts = [...html.matchAll(/<script\b[^>]*\bsrc=["']([^"']+)["']/gi)]; |
| 32 | if (!scripts.length) throw new Error(`Missing entry script: ${entry}`); |
| 33 | for (const match of html.matchAll(/<(?:script|link)\b[^>]*\b(?:src|href)=["']([^"']+)["']/gi)) { |
| 34 | const url = new URL(match[1], "http://cage.local/" + entry); |
| 35 | if (url.origin !== "http://cage.local") throw new Error(`External build resource: ${match[1]}`); |
| 36 | const resource = decodeURIComponent(url.pathname).slice(1); |
| 37 | if (!files[resource] || !(await stat(join(directory, resource))).isFile()) throw new Error(`Missing build resource: ${resource}`); |
| 38 | } |
| 39 | } |
| 40 | await writeFile(join(directory, "build-integrity.json"), JSON.stringify({ version: 1, files }, null, 2) + "\n"); |
| 41 | return Object.keys(files).length; |
| 42 | } |
| 43 | |
| 44 | if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { |
| 45 | const count = await verifyBuild(process.argv[2] ? resolve(process.argv[2]) : defaultDirectory); |
| 46 | console.log(`Verified ${count} frontend build resources.`); |
| 47 | } |