// THE CAST's FILE and its ONE WRITER (umtool-report-to-video/cast.mjs; umtool/docs/knobs.md, "The cast"). // // /.umtool/cast.json the characters, for every project // /.umtool/cast.undo.json the undo points: the file as it was before each write (the last 50) // /narration/characters.json THE PROJECT's OWN characters (cast.mjs PROJECT_CHARACTERS_FILE): the // /narration/characters.undo.json same writer, the same rules, its own undo points // // A version 1 cast (`voice` / `convert` at a character's top) is READ as version 2 (cast.mjs upgradeCast) and // written as version 2 by the first write after -- whose undo point is the version 1 text, so `undo` puts the old // file back as it was, and it reads the same. // // Every write is serialised in-process, re-reads the file inside the lock, checks the caller's token (the sha1 of // the file it read: a write over a newer file is refused), refuses a cast cast.mjs refuses (whole), keeps an undo // point and writes a temp file renamed over. A file that does not parse is never overwritten (a write refuses // until it is fixed); a reader treats it as no cast and says so in `error`. // // WHICH CAST A PROJECT READS: the reports root's when the project is under it; else the first `.umtool/cast.json` // up from the project's folder (a test's temp tree); else none. UMTOOL_CAST_FILE names one outright. // // Plain ESM: the CLI runs under bare node. import { createHash } from "node:crypto"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { CAST_FORMAT, CAST_VERSION, PROJECT_CHARACTERS_FILE, PROJECT_CHARACTERS_FORMAT, PROJECT_CHARACTERS_VERSION, characterView, emptyCast, emptyProjectCharacters, foldWritten, upgradeCharacter, validateCast, validateProjectCharacters, } from "umtool-report-to-video/cast"; import { REPORTS_ROOT } from "../paths.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CAST_UNDO_KEEP = 50; export class CastError extends Error { constructor(message, status = 400) { super(message); this.name = "CastError"; this.status = status; } } /** The cast file under a reports root (UMTOOL_CAST_FILE wins). */ export function castFile(reportsRoot = REPORTS_ROOT) { return process.env.UMTOOL_CAST_FILE || path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "cast.json"); } const undoFileOf = (file) => file.replace(/\.json$/, ".undo.json"); const inside = (dir, root) => dir === root || dir.startsWith(`${root}${path.sep}`); /** The cast file project folder `dir` reads (see the head), or null. */ export async function castFileFor(dir, reportsRoot = REPORTS_ROOT) { if (process.env.UMTOOL_CAST_FILE) return process.env.UMTOOL_CAST_FILE; const d = path.resolve(dir); const root = path.resolve(reportsRoot); if (inside(d, root)) return castFile(root); for (let cur = d; ; cur = path.dirname(cur)) { const f = path.join(cur, ".umtool", "cast.json"); if (await stat(f).then((s) => s.isFile(), () => false)) return f; if (path.dirname(cur) === cur) return null; } } const sha = (text) => createHash("sha1").update(text).digest("hex").slice(0, 16); /** The two files this store writes: what each is called, how it is refused, read and written. */ const CAST_KIND = Object.freeze({ what: "the cast", validate: validateCast, empty: emptyCast, doc: (characters) => ({ format: CAST_FORMAT, version: CAST_VERSION, characters }), }); // A project's file also holds its PROPOSED characters (`proposed`, cast.mjs proposalErrors: `umtool cast assign`), // written by this writer with the characters, and left out while there are none. const PROJECT_KIND = Object.freeze({ what: "the project's characters", validate: validateProjectCharacters, empty: emptyProjectCharacters, doc: (characters, extra = {}) => ({ format: PROJECT_CHARACTERS_FORMAT, version: PROJECT_CHARACTERS_VERSION, characters, ...(Array.isArray(extra?.proposed) && extra.proposed.length ? { proposed: extra.proposed } : {}) }), }); async function readKind(kind, file) { let text; try { text = await readFile(file, "utf8"); } catch (e) { if (e?.code === "ENOENT") return { cast: kind.empty(), token: null, file, exists: false, text: null }; return { cast: kind.empty(), token: null, file, exists: false, text: null, error: `${file} cannot be read: ${e?.message ?? e}` }; } let doc; try { doc = JSON.parse(text); } catch (e) { return { cast: kind.empty(), token: sha(text), file, exists: true, text, error: `${file} is not JSON: ${e instanceof Error ? e.message : e}` }; } const errors = kind.validate(doc, path.basename(file)); if (errors.length) return { cast: kind.empty(), token: sha(text), file, exists: true, text, error: `${path.basename(file)} is refused: ${errors.join("; ")}` }; // As a reader is handed it: each character version 2's shape, with the `voice` / `convert` its presets answer to. return { cast: { ...kind.doc(doc.characters.map(characterView), doc) }, token: sha(text), file, exists: true, text }; } /** * The cast as its file holds it: `{ cast, token, file, exists, error? }` -- `token` the sha1 of the text (null with * no file), `cast` as VERSION 2 whatever the file's, each character a VIEW (cast.mjs characterView). A file that does not parse or is refused * reads as the empty cast with `error`. */ export const readCastFile = (file) => readKind(CAST_KIND, file); /** A project's own characters file. */ export const projectCharactersFile = (dir) => path.join(/* turbopackIgnore: true */ dir, ...PROJECT_CHARACTERS_FILE.split("/")); /** * A project's OWN characters as its file holds them: `{ doc, token, file, exists, error? }` (readCastFile's shape, * the document under `doc`). No file: none. A file that does not parse or is refused reads as none, with `error`. */ export async function readProjectCharacters(dir) { const { cast, ...rest } = await readKind(PROJECT_KIND, projectCharactersFile(dir)); return { doc: cast, ...rest }; } /** The cast under a reports root. */ export const readCast = (reportsRoot = REPORTS_ROOT) => readCastFile(castFile(reportsRoot)); /** The cast project folder `dir` reads (the empty one when it reads none). */ export async function castForProject(dir, reportsRoot = REPORTS_ROOT) { const f = await castFileFor(dir, reportsRoot); if (!f) return { cast: emptyCast(), token: null, file: null, exists: false, text: null }; return readCastFile(f); } /** The undo points, oldest first: `{ at, what, text }` (`text` null: there was no file). */ export async function readCastUndo(file) { try { const j = JSON.parse(await readFile(undoFileOf(file), "utf8")); return Array.isArray(j?.points) ? j.points.filter((p) => p && typeof p.what === "string" && (typeof p.text === "string" || p.text === null)) : []; } catch { return []; } } async function writeAtomic(file, text) { await mkdir(path.dirname(file), { recursive: true }); const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } /** @type {Promise} */ let queue = Promise.resolve(); function withCastLock(fn) { const run = queue.then(fn, fn); queue = run.then(() => undefined, () => undefined); return run; } function writeKind(kind, file, mutate, { token = null, what = "an edit", manifests = [] } = {}) { return withCastLock(async () => { const read = await readKind(kind, file); if (read.error && read.exists) throw new CastError(`${read.error} -- fix the file first; nothing written`, 409); if (token !== null && token !== undefined && token !== read.token) throw new CastError(`${kind.what} changed since it was read (${token} -> ${read.token}): read it again`, 409); // The mutation is handed version 2's characters (no `voice` / `convert` beside the presets), and what is written // is version 2's shape: a `voice` / `convert` it sets the old way is the newer word unless it changed the preset // itself (cast.mjs foldWritten, against the character as it was handed). const chars = JSON.parse(JSON.stringify((read.cast.characters ?? []).map(upgradeCharacter))); const was = new Map(chars.map((c) => [c?.id, JSON.parse(JSON.stringify(c))])); // The rest of the document a mutation may change (a project's `proposed`), a copy. const extra = { proposed: JSON.parse(JSON.stringify(Array.isArray(read.cast.proposed) ? read.cast.proposed : [])) }; const result = mutate(chars, extra) ?? {}; const doc = kind.doc(chars.map((c) => foldWritten(c, was.get(c?.id) ?? null)), extra); const errors = kind.validate(doc, path.basename(file), { manifests }); if (errors.length) throw new CastError(`refused: ${errors.join("; ")}`); const points = [...(await readCastUndo(file)), { at: new Date().toISOString(), what, text: read.exists ? read.text : null }].slice(-CAST_UNDO_KEEP); await writeAtomic(undoFileOf(file), `${JSON.stringify({ file: path.basename(file), points }, null, 1)}\n`); const text = `${JSON.stringify(doc, null, 1)}\n`; await writeAtomic(file, text); return { ...result, cast: doc, token: sha(text), undo: points.length }; }); } function undoKind(kind, file, { token = null } = {}) { return withCastLock(async () => { const read = await readKind(kind, file); if (token !== null && token !== undefined && token !== read.token) throw new CastError(`${kind.what} changed since it was read: read it again`, 409); const points = await readCastUndo(file); const last = points.pop(); if (!last) throw new CastError(`nothing to undo on ${kind.what}`); if (last.text === null) await writeAtomic(file, `${JSON.stringify(kind.empty(), null, 1)}\n`); else await writeAtomic(file, last.text); await writeAtomic(undoFileOf(file), `${JSON.stringify({ file: path.basename(file), points }, null, 1)}\n`); const now = await readKind(kind, file); return { undone: last.what, at: last.at, left: points.length, cast: now.cast, token: now.token }; }); } /** * ONE WRITE of the cast: `mutate(characters)` (a copy, as version 2 holds them; it throws CastError to refuse) * returns what the caller wants back. Refused when the file changed since the caller's `token` (409), when it does * not parse, or when the result is refused (cast.mjs validateCast). Written as VERSION 2. Returns `{ ...result, * cast, token, undo: }`. * @param {string} file * @param {(chars: any[]) => any} mutate * @param {{ token?: string | null, what?: string }} [o] */ export const castWrite = (file, mutate, o) => writeKind(CAST_KIND, file, mutate, o); /** Put the cast back as it was before its last write (that write's undo point, taken off the list). */ export const undoCast = (file, o) => undoKind(CAST_KIND, file, o); /** * ONE WRITE of a project's own characters (`/narration/characters.json`): castWrite's rules -- a token, an undo * point, atomic, refused whole (cast.mjs validateProjectCharacters). `mutate(characters, { proposed })` may change * the PROPOSED characters too (the list in place). Returns `{ ...result, doc, token, undo }`. * @param {string} dir the project's folder * @param {(chars: any[], extra: { proposed: any[] }) => any} mutate * @param {{ token?: string | null, what?: string }} [o] */ export async function projectCharactersWrite(dir, mutate, o) { // The project's manifest: a shown name that is a real author's handle or name is refused (cast.mjs anonShownClashes). const manifest = await readFile(path.join(/* turbopackIgnore: true */ dir, "video.manifest.json"), "utf8").then(JSON.parse, () => null); const { cast, ...rest } = await writeKind(PROJECT_KIND, projectCharactersFile(dir), mutate, { ...o, ...(manifest ? { manifests: [manifest] } : {}) }); return { ...rest, doc: cast }; } /** A project's own characters as they were before their last write. */ export async function undoProjectCharacters(dir, o) { const { cast, ...rest } = await undoKind(PROJECT_KIND, projectCharactersFile(dir), o); return { ...rest, doc: cast }; }