import { type BigIntStats, closeSync, constants, type Dirent, fstatSync, lstatSync, openSync, promises as fsp, readdirSync, readFileSync, readSync, type Stats, statSync, } from "node:fs"; import { realpath, realpathOff } from "@hyperframes/core/safe-path"; import { contentHash, contentHashAsync } from "./contentHashing.js"; // A walk over a project folder written once as a generator of disk reads, so a render runs it with sync reads and // Studio with async ones that leave its event loop free. const NO_FOLLOW = constants.O_NOFOLLOW ?? 0; const NON_BLOCK = constants.O_NONBLOCK ?? 0; export interface PlainTail { text: string; whole: boolean; } const sameFile = (a: Stats, b: Stats) => a.isFile() && b.isFile() && a.ino === b.ino && a.dev === b.dev; /** The last `maxBytes` of a plain file, and whether that is all of it; null for a link, a device, or a missing file. * The file is opened first and read only when `lstat` then finds the same plain file at the path. */ export function plainTailSync(path: string, maxBytes: number): PlainTail | null { let fd: number; try { fd = openSync(path, constants.O_RDONLY | NO_FOLLOW | NON_BLOCK); } catch { return null; } try { const stats = fstatSync(fd); if (!sameFile(stats, lstatSync(path))) return null; const length = Math.min(stats.size, maxBytes); const buffer = Buffer.alloc(length); readSync(fd, buffer, 0, length, stats.size - length); return { text: buffer.toString("utf8"), whole: length === stats.size }; } catch { return null; } finally { closeSync(fd); } } async function plainTailOff(path: string, maxBytes: number): Promise { const file = await fsp.open(path, constants.O_RDONLY | NO_FOLLOW | NON_BLOCK).catch(() => null); if (!file) return null; try { const stats = await file.stat(); if (!sameFile(stats, await fsp.lstat(path))) return null; const length = Math.min(stats.size, maxBytes); const buffer = Buffer.alloc(length); await file.read(buffer, 0, length, stats.size - length); return { text: buffer.toString("utf8"), whole: length === stats.size }; } catch { return null; } finally { await file.close(); } } function headSync(path: string, bytes: number): Buffer | null { let fd: number | undefined; try { fd = openSync(path, "r"); const head = Buffer.alloc(bytes); return head.subarray(0, readSync(fd, head, 0, bytes, 0)); } catch { return null; } finally { if (fd !== undefined) closeSync(fd); } } async function headOff(path: string, bytes: number): Promise { const file = await fsp.open(path, "r").catch(() => null); if (!file) return null; try { const head = Buffer.alloc(bytes); return head.subarray(0, (await file.read(head, 0, bytes, 0)).bytesRead); } catch { return null; } finally { await file.close(); } } interface StampedText { stamp: string; read: () => string; } const stampOf = (stat: BigIntStats) => `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`; function stampedSync(path: string): StampedText { const fd = openSync(path, "r"); try { const stamp = stampOf(fstatSync(fd, { bigint: true })); const text = readFileSync(fd, "utf-8"); return { stamp, read: () => text }; } finally { closeSync(fd); } } async function stampedOff(path: string): Promise { const file = await fsp.open(path, "r"); try { const stamp = stampOf(await file.stat({ bigint: true })); const text = await file.readFile("utf-8"); return { stamp, read: () => text }; } finally { await file.close(); } } /** Each read a walk asks for, with the sync form a render runs and the async form Studio runs. */ const READS = { lstat: { sync: (path: string): Stats => lstatSync(path), off: (path: string): Promise => fsp.lstat(path), }, lstatBig: { sync: (path: string): BigIntStats => lstatSync(path, { bigint: true }), off: (path: string): Promise => fsp.lstat(path, { bigint: true }), }, stat: { sync: (path: string): Stats => statSync(path), off: (path: string): Promise => fsp.stat(path), }, statBig: { sync: (path: string): BigIntStats => statSync(path, { bigint: true }), off: (path: string): Promise => fsp.stat(path, { bigint: true }), }, readdir: { sync: (path: string): Dirent[] => readdirSync(path, { withFileTypes: true }), off: (path: string): Promise => fsp.readdir(path, { withFileTypes: true }), }, readText: { sync: (path: string): string => readFileSync(path, "utf-8"), off: (path: string): Promise => fsp.readFile(path, "utf-8"), }, realpath: { sync: realpath, off: realpathOff }, plainTail: { sync: plainTailSync, off: plainTailOff }, head: { sync: headSync, off: headOff }, stamped: { sync: stampedSync, off: stampedOff }, contentHash: { sync: contentHash, off: contentHashAsync }, }; type Reads = typeof READS; type ReadName = keyof Reads; type Answer = ReturnType; export type Step = { [N in ReadName]: { read: N; args: Parameters } }[ReadName]; export type Steps = Generator; /** One disk read in a walk; it throws as the read does. */ export function* step( read: N, ...args: Parameters ): Steps> { return (yield { read, args } as Step) as Answer; } type Outcome = { ok: true; value: unknown } | { ok: false; error: unknown }; function advance(steps: Steps, outcome: Outcome) { return outcome.ok ? steps.next(outcome.value) : steps.throw(outcome.error); } export function runSteps(steps: Steps): T { for (let next = steps.next(); ; ) { if (next.done) return next.value; const { read, args } = next.value; let outcome: Outcome; try { outcome = { ok: true, value: (READS[read].sync as (...a: unknown[]) => unknown)(...args) }; } catch (error) { outcome = { ok: false, error }; } next = advance(steps, outcome); } } export async function runStepsOff(steps: Steps): Promise { for (let next = steps.next(); ; ) { if (next.done) return next.value; const { read, args } = next.value; let outcome: Outcome; try { const off = READS[read].off as (...a: unknown[]) => unknown; outcome = { ok: true, value: await off(...args) }; } catch (error) { outcome = { ok: false, error }; } next = advance(steps, outcome); } } /** `lstat`'s answer, or undefined when nothing is at the path, as `lstatSync(path, { throwIfNoEntry: false })`. */ export function* lstatIfAny(path: string): Steps { try { return yield* step("lstat", path); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; } }