import { createHash } from "node:crypto"; import { closeSync, constants, fstatSync, openSync, readFileSync, type Stats } from "node:fs"; import { type FileHandle, open } from "node:fs/promises"; import { extname } from "node:path"; const sha256 = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex"); const MAX_HASHED_BYTES = 16 * 1024 * 1024; const READ_PLAIN = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0); /** Pages, stylesheets, scripts and SVG of any size, and other plain files up to 16 MB, as `stat` reads them. */ export const hashable = (path: string, stat: Stats) => stat.isFile() && (stat.size <= MAX_HASHED_BYTES || isCodeFile(path)); /** The sha256 of a plain file's bytes; null for a link, a folder, a large file that names no others, or one * that cannot be read. */ export function contentHash(path: string): string | null { let fd: number; try { fd = openSync(path, READ_PLAIN); } catch { return null; } try { return hashable(path, fstatSync(fd)) ? sha256(readFileSync(fd)) : null; } catch { return null; } finally { closeSync(fd); } } export async function contentHashAsync(path: string): Promise { let handle: FileHandle; try { handle = await open(path, READ_PLAIN); } catch { return null; } try { return hashable(path, await handle.stat()) ? sha256(await handle.readFile()) : null; } catch { return null; } finally { await handle.close(); } } const CODE_FILE = new Set([".html", ".htm", ".xhtml", ".css", ".js", ".mjs", ".cjs", ".svg"]); /** Pages, stylesheets, scripts and SVG: the files that can name other files for a render or upload to load. */ export const isCodeFile = (path: string): boolean => CODE_FILE.has(extname(path).toLowerCase());