// STORED TEXT, THE READ PATH IN PLAIN JS — for umtool's bare-node scripts // (report-to-video's cue source, the clip words, the ingredients rail), which // cannot import lib/storedText-server.ts. The same rules (lib/storedText.ts): // a declared file — the raw live chat, or a caption track // `transcript..vtt` — may be on disk as `.zst`, one zstd frame // whose header carries the content size; THE PLAIN FILE, WHEN PRESENT, IS THE // TRUTH; a matching listing is LOGICAL (the `.zst` reported under its plain // name, once). storedText.mjs-twin.test.ts holds this module and the TS one // equal (names, decode, head, sizes); change one, change the other. // SERVER-ONLY (node:fs, node:zlib). Read only: nothing here writes. import { open, readdir, readFile, stat } from "node:fs/promises"; import path from "node:path"; import zlib from "node:zlib"; import { assertZstdSupport } from "./zstdSupport.mjs"; // A bare-node script that may read a stored file refuses to start on a Node // without zstd (REVIEW-1 F3): asked when this module loads. assertZstdSupport("this script (a reader of stored text)"); export const STORED_TEXT_SUFFIX = ".zst"; const LIVE_CHAT = "transcript.live_chat.json"; const CAPTION_RE = /^transcript\.(?!tmp-\d+\.vtt$)[^.]+\.vtt$/; /** @param {string} name */ export function isStoredTextName(name) { return name === LIVE_CHAT || CAPTION_RE.test(name); } /** @param {string} name */ export function plainNameOf(name) { if (!name.endsWith(STORED_TEXT_SUFFIX)) return null; const plain = name.slice(0, -STORED_TEXT_SUFFIX.length); return isStoredTextName(plain) ? plain : null; } /** @param {Iterable} entries */ export function logicalEntries(entries) { const out = []; const seen = new Set(); for (const e of entries) { const n = plainNameOf(e) ?? e; if (seen.has(n)) continue; seen.add(n); out.push(n); } return out; } /** @param {string} dir */ export async function readdirLogical(dir) { return logicalEntries(await readdir(dir).catch(() => [])); } const ZSTD_MAGIC = 0xfd2fb528; /** The content size a zstd frame header declares, or null. @param {Uint8Array} head */ export function frameContentSize(head) { if (head.length < 5) return null; const dv = new DataView(head.buffer, head.byteOffset, head.byteLength); if (dv.getUint32(0, true) !== ZSTD_MAGIC) return null; const fhd = head[4]; const fcsFlag = fhd >> 6; const singleSegment = (fhd >> 5) & 1; const dictFlag = fhd & 3; if (fcsFlag === 0 && !singleSegment) return null; const off = 5 + (singleSegment ? 0 : 1) + [0, 1, 2, 4][dictFlag]; const fcsBytes = fcsFlag === 0 ? 1 : [1, 2, 4, 8][fcsFlag]; if (head.length < off + fcsBytes) return null; if (fcsBytes === 1) return head[off]; if (fcsBytes === 2) return dv.getUint16(off, true) + 256; if (fcsBytes === 4) return dv.getUint32(off, true); const n = dv.getUint32(off + 4, true) * 2 ** 32 + dv.getUint32(off, true); return Number.isSafeInteger(n) ? n : null; } function assertZstd() { if (typeof zlib.zstdDecompress !== "function" || typeof zlib.createZstdDecompress !== "function") { throw new Error(`stored text needs node:zlib zstd — Node >= 22.15 (this is ${process.version})`); } } const isEnoent = (err) => err?.code === "ENOENT" || err?.code === "ENOTDIR"; const enoent = (dir, name) => Object.assign(new Error(`ENOENT: no such file, '${path.join(dir, name)}' (nor its stored form)`), { code: "ENOENT" }); /** A stored file's bytes decoded, its checksum and length checked. @param {Buffer} bytes @param {string} label */ export async function decodeStoredBytes(bytes, label = "stored text") { assertZstd(); const want = frameContentSize(bytes.subarray(0, 18)); if (want === null) throw new Error(`${label}: not a whole stored-text frame (no content size in the frame header)`); const out = await new Promise((resolve, reject) => zlib.zstdDecompress(bytes, { maxOutputLength: Math.max(1, want + 1) }, (err, res) => (err ? reject(err) : resolve(res))), ).catch((err) => { throw new Error(`${label}: not a whole stored-text frame (${err.message})`); }); if (out.length !== want) throw new Error(`${label}: not a whole stored-text frame (decoded ${out.length} bytes, header says ${want})`); return out; } /** * The plain file's bytes when it opens; else (a declared name) the stored form * decoded; ENOENT when neither opens. * @param {string} dir @param {string} name @param {"utf8"} [encoding] */ export async function readStoredText(dir, name, encoding) { try { return encoding ? await readFile(path.join(dir, name), encoding) : await readFile(path.join(dir, name)); } catch (err) { if (!isEnoent(err) || !isStoredTextName(name)) throw err; } const storedPath = path.join(dir, name + STORED_TEXT_SUFFIX); let bytes; try { bytes = await readFile(storedPath); } catch (err) { if (isEnoent(err)) throw enoent(dir, name); throw err; } const out = await decodeStoredBytes(bytes, storedPath); return encoding ? out.toString(encoding) : out; } /** The first `bytes` bytes as the plain file has them (decoded from a stored form). */ export async function readStoredTextHead(dir, name, bytes) { try { const fh = await open(path.join(dir, name), "r"); try { const buf = Buffer.alloc(bytes); const { bytesRead } = await fh.read(buf, 0, bytes, 0); return buf.subarray(0, bytesRead); } finally { await fh.close(); } } catch (err) { if (!isEnoent(err) || !isStoredTextName(name)) throw err; } assertZstd(); const storedPath = path.join(dir, name + STORED_TEXT_SUFFIX); let fh; try { fh = await open(storedPath, "r"); } catch (err) { if (isEnoent(err)) throw enoent(dir, name); throw err; } const src = fh.createReadStream(); const dec = zlib.createZstdDecompress(); const out = []; let n = 0; try { await new Promise((resolve, reject) => { dec.on("data", (chunk) => { if (n >= bytes) return; out.push(chunk); n += chunk.length; if (n >= bytes) { src.unpipe(dec); src.destroy(); dec.destroy(); resolve(); } }); dec.on("end", resolve); dec.on("error", (err) => reject(new Error(`${storedPath}: not a whole stored-text frame (${err.message})`))); src.on("error", reject); src.pipe(dec); }); } finally { src.destroy(); await fh.close().catch(() => {}); } return Buffer.concat(out).subarray(0, bytes); } /** `stat` of the plain name, else of its stored form (which carries the plain file's times). */ export async function statStoredText(dir, name) { try { return { form: "plain", stats: await stat(path.join(dir, name)) }; } catch (err) { if (!isEnoent(err) || !isStoredTextName(name)) throw err; } try { return { form: "zst", stats: await stat(path.join(dir, name + STORED_TEXT_SUFFIX)) }; } catch (err) { if (isEnoent(err)) throw enoent(dir, name); throw err; } } /** The LOGICAL size: the plain file's, or the stored frame header's content size. */ export async function storedTextLogicalSize(dir, name) { const s = await statStoredText(dir, name); if (s.form === "plain") return s.stats.size; const file = path.join(dir, name + STORED_TEXT_SUFFIX); const fh = await open(file, "r"); try { const head = Buffer.alloc(18); const { bytesRead } = await fh.read(head, 0, 18, 0); const n = frameContentSize(head.subarray(0, bytesRead)); if (n === null) throw new Error(`${file}: not a whole stored-text frame (no content size in the frame header)`); return n; } finally { await fh.close(); } }