// REPLACE OVER A VIDEO's READS (lane reads-find; operator ruling 3: an edit changes only what is SPOKEN, never what // is shown), in two scopes, each previewed before it is applied and neither synthesizing anything: // // These reads the spoken text of the matched reads rewritten, in ONE structural write (one undo point, // `auto-before-reads-replace`, always its own): a post's script (postNarrationIn, marked // for reading as Save script marks it), a screen line's "said as" (`screens[j].saidAs`, // created from the line as read when it has none -- the line as shown untouched), a card's // narration (cardNarrationIn). A parent, the quoted or a linked post has no spoken-only // words: listed, not changed ("said as shown: only Everywhere changes this"); a recorded // read is yours and is never replaced. // Everywhere, from now on a pronunciation entry (postSay.mjs updateLexicon, `umtool posts say add`'s writer): every // read of a post, present and future, says it that way. Whole words only (the lexicon's // rule), and never a card's narration (cards are not said through the lexicon). // // Either way the reads that changed show as stale (reads.mjs); a re-read is a press (readsQueue.mjs). // // Plain ESM: the CLI runs it under bare node. import { LEGACY_EDIT_TEXT, findPattern, matchesIn, projectReads, readsContext, replaceIn } from "./reads.mjs"; import { AUTO_SNAPSHOT_PREFIX, StructureRefused, cardNarrationIn, manifestToken, postItemIn, postNarrationIn, structuralEdit, undoStructural } from "./manifest.mjs"; import { screenLineSaid, screensOf } from "umtool-report-to-video/post-screens"; import { lexiconKey, normalizeLexicon } from "umtool-report-to-video/post-say"; import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { createHash } from "node:crypto"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; import { withNotesLock } from "../annotations/store.mjs"; export const REPLACE_OP = "reads-replace"; export const UNDO_LABEL = `${AUTO_SNAPSHOT_PREFIX}${REPLACE_OP}`; /** Said where Everywhere is offered with Whole word off. */ export const SAY_WHOLE_WORDS = "Everywhere, from now on matches whole words only (a pronunciation entry): turn Whole word on"; /** Said for a card a pronunciation entry does not reach. */ export const SAY_NOT_CARDS = "cards are not said through the lexicon: use These reads for a card"; export class ReplaceError extends Error { constructor(message) { super(message); this.name = "ReplaceError"; } } const clone = (v) => JSON.parse(JSON.stringify(v)); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); /** What each kind's replace does to a read whose spoken text is still its shown text. */ function createsNote(r) { if (!r.shownSpoken) return null; if (r.kind === "screen") return "creates its said-as (the line as shown is untouched)"; return "creates its script from the post's words (the post as shown is untouched)"; } /** The writes of a replace, in `m` (inside a write or on a copy): `lines` grouped by item. */ export function replaceReadsIn(m, lines) { const byItem = new Map(); for (const l of lines) byItem.set(l.item, [...(byItem.get(l.item) ?? []), l]); for (const [item, ls] of byItem) { const e = (m.timeline ?? []).find((x) => x?.id === item); if (!e) throw new ReplaceError(`no item ${item} in the cut`); const cardLine = ls.find((l) => l.kind === "card"); if (cardLine) { cardNarrationIn(m, item, { text: cardLine.after }); continue; } const scriptLine = ls.find((l) => l.kind === "post" || (l.kind === "thread" && l.role === "post")); if (scriptLine) postNarrationIn(m, item, { script: scriptLine.after }, { forReading: true }); const lineLines = ls.filter((l) => l.kind === "screen"); if (lineLines.length) { const next = clone(screensOf(e)); for (const l of lineLines) { const [, id, n] = /^screen:([a-z0-9-]+):(\d+)$/.exec(l.role) ?? []; const sc = next.find((x) => x.id === id); if (!sc) throw new ReplaceError(`${item} has no screen ${id}`); const sa = isObj(sc.saidAs) ? { ...sc.saidAs } : {}; // Back to the line as read: no said-as (its own words again); else its said-as. if (l.after.replace(/\s+/g, " ").trim() === screenLineSaid(sc, Number(n)).replace(/\s+/g, " ").trim()) delete sa[n]; else sa[n] = l.after; if (Object.keys(sa).length) sc.saidAs = sa; else delete sc.saidAs; } postItemIn(m, item, { screens: next }); } } return { items: [...byItem.keys()] }; } /** * THESE READS, PREVIEWED: `{ scope: "reads", find, to, lines: [{ id, kind, item, role, before, after, storedAt, * creates }], skipped: [{ id, why }], notes: { : [sentence…] }, refused: { : [error…] }, matches }`. * `only`: the read ids to change (the rest of the matches left as they are). */ export async function replacePlan(project, from, to, { matchCase = false, word = false, only = null, ctx = null, reportsRoot = undefined } = {}) { if (typeof from !== "string" || !from.trim()) throw new ReplaceError("replace takes the words to find"); if (typeof to !== "string") throw new ReplaceError("replace takes what to say instead"); const c = ctx ?? (await readsContext(project, reportsRoot ? { reportsRoot } : {})); const { rows } = await projectReads(project, { ctx: c }); const re = findPattern(from, { matchCase, word }); const keep = only ? new Set(only) : null; const lines = []; const skipped = []; let matches = 0; for (const r of rows) { const hits = matchesIn(r.spoken, re); if (!hits.length || (keep && !keep.has(r.id))) continue; matches += hits.length; if (!r.editable) { skipped.push({ id: r.id, why: r.why ?? "not rewritten here" }); continue; } lines.push({ id: r.id, kind: r.kind, item: r.item, role: r.role, before: r.spoken, after: replaceIn(r.spoken, re, to), storedAt: r.storedAt, creates: createsNote(r) }); } const notes = {}; const say = (item, s) => { notes[item] = [...(notes[item] ?? []), s]; }; const m = c.manifest; let review = null; for (const item of new Set(lines.map((l) => l.item))) { const e = m.timeline.find((x) => x?.id === item); const row = rows.find((r) => r.item === item); if (e?.type === "post" && e.narration?.approved && lines.some((l) => l.item === item && (l.kind === "post" || l.role === "post"))) say(item, "its approval goes, as a new script takes it away (Save script does the same)"); if (row?.legacy) say(item, LEGACY_EDIT_TEXT); if (e?.type === "card") { review ??= await (await import("umtool-report-to-video/narration-review")).readNarrationReview(project.dir).catch(() => null); if (review?.rows?.[item]?.verdict) say(item, `its narration review verdict (${review.rows[item].verdict}) was given on the old words`); } } // What the build would refuse, item by item, on a copy (a said-as saying what a screen masks, …). const refused = {}; for (const item of new Set(lines.map((l) => l.item))) { try { replaceReadsIn(clone(m), lines.filter((l) => l.item === item)); } catch (err) { refused[item] = err instanceof StructureRefused ? err.errors : [err instanceof Error ? err.message : String(err)]; } } return { scope: "reads", find: from, to, matchCase, word, lines, skipped, notes, refused, matches, ctx: c }; } /** The replaces made here, newest last: `/narration/reads/replaces.json` -- what an undo checks against. */ export const REPLACES_FILE = "narration/reads/replaces.json"; const replacesPath = (dir) => path.join(/* turbopackIgnore: true */ dir, ...REPLACES_FILE.split("/")); /** The draft as it is on disk, hashed: what a replace left, compared byte for byte (an undo restores bytes, not times). */ const draftSha = async (dir) => createHash("sha1").update(await readFile(path.join(/* turbopackIgnore: true */ dir, "video.manifest.json")).catch(() => Buffer.alloc(0))).digest("hex"); /** The records, oldest first: `{ scope: "reads", at, find, to, token, snapshot }` | `{ scope: "say", at, entry, was }`. */ export async function readReplaces(dir) { try { const j = JSON.parse(await readFile(replacesPath(dir), "utf8")); return Array.isArray(j?.records) ? j.records.filter(isObj) : []; } catch { return []; } } async function withReplaces(dir, fn) { const file = replacesPath(dir); await mkdir(path.dirname(file), { recursive: true }); return withNotesLock(file, async () => { const { records, result } = await fn(await readReplaces(dir)); const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify({ version: 1, records: records.slice(-20) }, null, 1)}\n`); await rename(tmp, file); return result; }); } /** * THESE READS, APPLIED: the plan's lines in one structural write (its own undo point), against the manifest's token * read BEFORE the plan (a write between the two is refused, never laid over). Refused whole when any item is refused * (the preview says which), or when nothing would change. The manifest's token after it is kept with the replace's * record, and the draft's bytes hashed: Undo the replace is offered only while the draft is still exactly what it left. Returns `{ plan, result }`. */ export async function applyReplace(project, from, to, o = {}) { const token = o.token ?? (await manifestToken(project.dir)); const plan = await replacePlan(project, from, to, o); if (Object.keys(plan.refused).length) throw new ReplaceError(`refused: ${Object.entries(plan.refused).map(([i, errs]) => `${i}: ${errs.join("; ")}`).join(" · ")} -- leave those reads out (--only) or say it another way`); if (!plan.lines.length) throw new ReplaceError(plan.matches ? `nothing to rewrite: every match is in a read These reads does not change (${plan.skipped.map((s) => s.id).join(", ")})` : `"${from}" is in no read's spoken text`); const { withEditNotes } = await import("./edit-guard.mjs"); const { result, editNotes } = await withEditNotes(project, async () => structuralEdit(project.dir, REPLACE_OP, token, (m) => replaceReadsIn(m, plan.lines), { snapshotEvery: 0 })); await o.onWritten?.(); // The draft hashed only while it is still the replace's own write (its token): a write landing in between (a queue // step in another process) is never hashed in -- the replace is then recorded as one Undo cannot take back. const still = (await manifestToken(project.dir)) === result.token; const sha = still ? await draftSha(project.dir) : null; await withReplaces(project.dir, (records) => ({ records: [...records, { scope: "reads", at: new Date().toISOString(), find: from, to, lines: plan.lines.map((l) => l.id), token: result.token ?? null, sha, snapshot: result.snapshot?.rel ?? null, ...(still ? {} : { undoable: false }) }], result: null })); return { plan, result, editNotes }; } /** * Whether the newest replace can be taken back now: `{ scope, available, why }` (null: none was made here). A replace * of These reads only while the draft's token is the one it left (nothing written since -- a re-read landing, a bench * edit) and its undo point is the newest; Everywhere only while the entry is still as it set it. */ export async function replaceUndoState(project) { const last = (await readReplaces(project.dir)).at(-1); if (!last) return null; if (last.scope === "say") { const { readLexicon } = await import("./postSay.mjs"); const now = (await readLexicon(project.dir)).find((x) => lexiconKey(x) === lexiconKey(last.entry)); return now && now.say === last.entry.say ? { scope: "say", available: true, why: null, entry: last.entry, was: last.was ?? null } : { scope: "say", available: false, why: `the entry for "${last.entry.word}" changed since (umtool posts say ${project.id} ls)`, entry: last.entry, was: last.was ?? null }; } if (last.undoable === false || !last.sha) return { scope: "reads", available: false, why: "the draft changed while the replace was written (another write landed): taking it back could take that back too -- undo from where each was made" }; if ((await draftSha(project.dir)) !== last.sha) return { scope: "reads", available: false, why: "the draft changed after the replace (a re-read landed, or another edit): taking the replace back now would take that back too -- undo those from where they were made" }; const { listSnapshots } = await import("./snapshots.mjs"); const top = (await listSnapshots(project.dir)).find((s) => !s.legacy && s.label?.startsWith(AUTO_SNAPSHOT_PREFIX)); if (!top || top.label !== UNDO_LABEL) return { scope: "reads", available: false, why: "its undo point is no longer the newest" }; if (last.snapshot && top.rel !== last.snapshot) return { scope: "reads", available: false, why: "its undo point is not the one it made (the newest is another replace's)" }; return { scope: "reads", available: true, why: null }; } /** Take back the newest replace of These reads: refused, in a sentence, unless replaceUndoState says it may be. */ export async function undoReplace(project, { token = null } = {}) { // The token the check is made against goes with the restore: a write between the two is refused, never undone. const checked = token ?? (await manifestToken(project.dir)); const st = await replaceUndoState(project); if (!st || st.scope !== "reads") throw new ReplaceError("nothing to undo: the newest replace made here is not one of These reads"); if (!st.available) throw new ReplaceError(`not undone: ${st.why}`); const { withEditNotes } = await import("./edit-guard.mjs"); const { result } = await withEditNotes(project, async () => undoStructural(project.dir, { token: checked })); await withReplaces(project.dir, (records) => ({ records: records.slice(0, -1), result: null })); return result; } /** * EVERYWHERE, FROM NOW ON, PREVIEWED: `{ scope: "say", entry, was, stale: [{ id, kind, item }], cards: [ids], * matches }` -- the entry it adds (or changes: `was` its spoken form before), every read it would make stale, and * the cards it does not reach. Refused with Whole word off. */ export async function sayOnlyPlan(project, from, to, { matchCase = false, word = true, ctx = null, reportsRoot = undefined } = {}) { if (!word) throw new ReplaceError(SAY_WHOLE_WORDS); if (typeof from !== "string" || !from.trim() || typeof to !== "string" || !to.trim()) throw new ReplaceError("Everywhere takes the words to find and how to say them"); const c = ctx ?? (await readsContext(project, reportsRoot ? { reportsRoot } : {})); const before = await projectReads(project, { ctx: c }); const entry = { word: from.replace(/\s+/g, " ").trim(), say: to.trim(), ...(matchCase ? { case: true } : {}) }; const had = c.lexicon.find((x) => lexiconKey(x) === lexiconKey(entry)) ?? null; const lexicon = normalizeLexicon([...c.lexicon.filter((x) => lexiconKey(x) !== lexiconKey(entry)), entry]); const after = await projectReads(project, { ctx: { ...c, lexicon, red: { ...(c.red ?? {}), say: lexicon } } }); const was = new Map(before.rows.map((r) => [r.id, r])); const newly = after.rows.filter((r) => (r.state === "stale" || r.state === "unpicked") && (r.because.includes("words") || r.because.includes("lexicon")) && !(was.get(r.id)?.because ?? []).some((b) => b === "words" || b === "lexicon")); const re = findPattern(from, { matchCase, word: true }); const cards = before.rows.filter((r) => r.kind === "card" && matchesIn(r.spoken, re).length).map((r) => r.id); const matches = before.rows.reduce((a, r) => a + matchesIn(r.spoken, re).length, 0); return { scope: "say", entry, was: had ? had.say : null, wasEntry: had ? { ...had } : null, stale: newly.map((r) => ({ id: r.id, kind: r.kind, item: r.item })), cards, matches, ctx: c }; } /** * EVERYWHERE, APPLIED: the entry through `posts say add`'s writer (an entry of the same word changes its spoken form). * What it replaced -- the whole entry, its note too -- is kept with the record, so its undo puts that back. * Returns `{ plan, result }`. */ export async function applySayOnly(project, from, to, o = {}) { const plan = await sayOnlyPlan(project, from, to, o); const { updateLexicon } = await import("./postSay.mjs"); const result = await updateLexicon(project.dir, { add: { word: plan.entry.word, say: plan.entry.say, case: plan.entry.case === true, item: null, note: o.note ?? null } }); await withReplaces(project.dir, (records) => ({ records: [...records, { scope: "say", at: new Date().toISOString(), entry: { word: result.entry.word, say: result.entry.say, ...(result.entry.case ? { case: true } : {}) }, was: plan.wasEntry }], result: null })); return { plan, result }; } /** * EVERYWHERE, TAKEN BACK: the entry it changed back to what it was (its spoken form, its note), or the entry it added * removed -- that one entry, by its identity (word, case, item), never another of the same word. Refused when the * entry changed since. */ export async function undoSayOnly(project) { const st = await replaceUndoState(project); if (!st || st.scope !== "say") throw new ReplaceError("nothing to take back: the newest replace made here is not an Everywhere"); if (!st.available) throw new ReplaceError(`not taken back: ${st.why}`); const { readLexicon, updateLexicon } = await import("./postSay.mjs"); let result; if (st.was) result = await updateLexicon(project.dir, { add: { word: st.was.word, say: st.was.say, case: st.was.case === true, item: st.was.item ?? null, note: st.was.note ?? null } }); else { const at = (await readLexicon(project.dir)).findIndex((x) => lexiconKey(x) === lexiconKey(st.entry)); result = await updateLexicon(project.dir, { remove: at }); } await withReplaces(project.dir, (records) => ({ records: records.slice(0, -1), result: null })); return { restored: st.was ?? null, removed: st.was ? null : st.entry, lexicon: result.lexicon }; }