From 4801908fafa0d494b37d307618bd0598ece4e1f2 Mon Sep 17 00:00:00 2001 From: muena Date: Thu, 15 Oct 2026 09:24:26 +0200 Subject: [PATCH] fix: guide project mapping recovery and allow manual table entries --- src/lib/velum-project.ts | 85 ++++++++++++++++- src/restore-project-files.tsx | 164 ++++++++++++++++++++++++++------ src/show-translation-tables.tsx | 86 ++++++++++++++--- tests/velum-project.test.ts | 48 ++++++++++ 4 files changed, 337 insertions(+), 46 deletions(-) diff --git a/src/lib/velum-project.ts b/src/lib/velum-project.ts index 1b79d6e..dd71c85 100644 --- a/src/lib/velum-project.ts +++ b/src/lib/velum-project.ts @@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto"; import { constants as fsConstants, promises as fs } from "node:fs"; import { basename, dirname, extname, join, relative, resolve, sep } from "node:path"; import { environment } from "@raycast/api"; -import type { EntityType, PlaceholderMapping } from "../types"; +import type { EntityType, MappingEntry, PlaceholderMapping } from "../types"; import { whitelistKey } from "./project-whitelist"; import type { ProjectWhitelistEntry } from "./project-whitelist"; import { restoreOriginalCase } from "./restore-case"; @@ -382,6 +382,78 @@ export async function saveRun(directory: string, run: ProjectRun): Promise await fs.rename(tmp, dest); } +export function prepareManualMappingEntry(current: PlaceholderMapping, earlier: PlaceholderMapping[], + input: { original: string; type: string; placeholder?: string }): { placeholder: string; entry: MappingEntry } { + const original = input.original.trim(); + const type = input.type.trim().toUpperCase(); + if (!original) throw new Error("Bitte einen Klartext-Begriff eingeben."); + if (!/^[A-ZÄÖÜ][A-ZÄÖÜ0-9_]*$/u.test(type)) throw new Error("Ungültige Kategorie."); + if (Object.values(current).some((entry) => entry.type === type + && entry.original.toLocaleLowerCase("de") === original.toLocaleLowerCase("de"))) { + throw new Error("Dieser Begriff ist in der Kategorie bereits vorhanden."); + } + const known = [current, ...earlier]; + const keys = known.flatMap((mapping) => Object.keys(mapping)); + const placeholderPattern = new RegExp(`^${type}_(\\d+)$`, "u"); + const placeholder = input.placeholder?.trim().toUpperCase() || (() => { + const max = keys.reduce((currentMax, key) => Math.max(currentMax, + Number(placeholderPattern.exec(key)?.[1] ?? 0)), 0); + return `${type}_${String(max + 1).padStart(2, "0")}`; + })(); + if (!placeholderPattern.test(placeholder)) { + throw new Error("Platzhalter muss zur Kategorie passen, z. B. PERSON_61."); + } + if (Object.keys(current).some((key) => key.toUpperCase() === placeholder)) { + throw new Error("Dieser Platzhalter ist im aktuellen Stand bereits belegt."); + } + for (const mapping of earlier) for (const [key, entry] of Object.entries(mapping)) { + if (key.toUpperCase() === placeholder && (entry.type !== type || entry.original !== original)) { + throw new Error("Dieser Platzhalter hatte früher eine andere Bedeutung. Bitte die betroffene Datei einzeln zuordnen."); + } + } + return { placeholder, entry: { original, type } }; +} + +/** Save a mapping correction as a new immutable project stand without rewriting project files. */ +export async function addProjectMappingEntry(projectPath: string, + input: { original: string; type: string; placeholder?: string }, support = environment.supportPath): Promise { + const entries = await listRuns(projectPath, support); + const latest = entries[0]; + if (!latest) throw new Error("Für dieses Projekt gibt es noch keinen gespeicherten Stand."); + const { placeholder, entry } = prepareManualMappingEntry(latest.run.mapping, + entries.slice(1).map((saved) => saved.run.mapping), input); + const created = await createRun(projectPath, support); + const { run, directory } = created; + run.createdAt = new Date(Math.max(Date.now(), Date.parse(latest.run.createdAt) + 1)).toISOString(); + run.origin = latest.run.origin; + run.revisedFrom = latest.run.id; + run.mapping = { ...latest.run.mapping, [placeholder]: entry }; + run.matchModes = { ...latest.run.matchModes }; + run.files = latest.run.files.map((file) => ({ ...file })); + run.inPlace = latest.run.inPlace; + run.sourceInPlace = latest.run.sourceInPlace; + run.commentAuthorCoverage = latest.run.commentAuthorCoverage; + run.reviewAuthorCoverage = latest.run.reviewAuthorCoverage; + run.copyPath = latest.run.copyPath; + try { + for (const file of run.files) { + const source = resolveWithin(join(latest.directory, "files"), file.output); + const target = resolveWithin(join(directory, "files"), file.output); + await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 }); + await fs.copyFile(source, target, fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE); + await fs.chmod(target, 0o600); + } + if ((await listRuns(projectPath, support))[0]?.run.id !== latest.run.id) { + throw new Error("Es gibt bereits einen neueren Projektstand. Bitte die Liste aktualisieren."); + } + await saveRun(directory, run); + } catch (error) { + await fs.rm(directory, { recursive: true, force: true }); + throw error; + } + return run; +} + export function runCopiesPath(run: ProjectRun, directory: string): string { return run.copyPath ?? join(directory, "files"); } @@ -469,6 +541,17 @@ export async function matchesPreviousOutput(directory: string, relPath: string, } } +/** Only an identical saved file can disambiguate a placeholder reused across runs. */ +export async function mappingForMatchingSnapshots(relPath: string, currentHash: string, + earlier: Array<{ run: ProjectRun; directory: string }>): Promise { + const matching = await Promise.all(earlier.filter(({ run }) => + run.files.some((file) => file.output === relPath)) + .map(async ({ run, directory }) => await matchesPreviousOutput(directory, relPath, currentHash) + ? run.mapping : undefined)); + return withUnambiguousHistoricalMappings({}, + matching.filter((mapping): mapping is PlaceholderMapping => Boolean(mapping))); +} + export async function listAllRuns(support = environment.supportPath): Promise> { diff --git a/src/restore-project-files.tsx b/src/restore-project-files.tsx index d327a87..0bdcb35 100644 --- a/src/restore-project-files.tsx +++ b/src/restore-project-files.tsx @@ -1,16 +1,57 @@ -import { Action, ActionPanel, Alert, confirmAlert, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api"; +import { Action, ActionPanel, Alert, confirmAlert, Form, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api"; import { promises as fs } from "node:fs"; import { homedir } from "node:os"; import { basename, dirname, join } from "node:path"; import { useEffect, useState } from "react"; import { depseudonymizeDocument } from "./velum"; -import { canonicalProjectPath, isMarkdownFile, listAllRuns, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, withUnambiguousHistoricalMappings } from "./lib/velum-project"; +import { addProjectMappingEntry, canonicalProjectPath, digest, isMarkdownFile, listAllRuns, mappingForMatchingSnapshots, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, withUnambiguousHistoricalMappings } from "./lib/velum-project"; import type { ProjectFile, ProjectRun } from "./lib/velum-project"; +import type { MappingEntry, PlaceholderMapping } from "./types"; import { canonicalPerson, mergePeople } from "./lib/project-review"; import { planProjectRevision, reviseProjectRun } from "./lib/project-revision"; import { TranslationTable } from "./show-translation-tables"; type SavedRun = { run: ProjectRun; directory: string }; +type RestoreDecision = MappingEntry | null; + +class UnresolvedRestoreError extends Error { + constructor(readonly file: string, readonly ids: string[]) { + super(`${file}: ${ids.length} Platzhalter benötigen eine Zuordnung.`); + } +} + +function RestoreDecisionForm(props: { file: string; id: string; candidates: MappingEntry[]; + onSave: (decision: RestoreDecision) => void }) { + const { pop } = useNavigation(); + async function save(values: { choice: string; original: string }) { + const original = values.original.trim(); + const candidate = values.choice.startsWith("candidate:") + ? props.candidates[Number(values.choice.slice("candidate:".length))] : undefined; + if (original) props.onSave({ original, type: candidate?.type ?? props.id.replace(/_\d+$/, "") }); + else if (candidate) props.onSave(candidate); + else if (values.choice === "keep") props.onSave(null); + else { + await showToast({ style: Toast.Style.Failure, title: "Bitte einen Klartext wählen oder bewusst unverändert lassen" }); + return; + } + pop(); + } + return
}> + 1 + ? "Dieser Platzhalter hat in gespeicherten Projektständen unterschiedliche Bedeutungen. Wähle die passende Zuordnung für diese Datei." + : props.candidates.length === 1 + ? "Ein früherer Projektstand enthält diesen Eintrag. Prüfe, ob er zu dieser Datei gehört." + : "Für diesen Platzhalter gibt es in den gespeicherten Projektständen keine Zuordnung. Trage den Klartext ein oder bestätige, dass er absichtlich stehen bleiben soll."} /> + + + {props.candidates.map((entry, index) => )} + + + + ; +} function RevisionReview(props: { saved: SavedRun; onSaved: () => Promise }) { const { pop } = useNavigation(); @@ -132,12 +173,30 @@ function RevisionReview(props: { saved: SavedRun; onSaved: () => Promise } ; } -function FilePicker(props: { run: ProjectRun; directory: string; historical?: boolean; earlierRuns: ProjectRun[] }) { +function FilePicker(props: { run: ProjectRun; directory: string; historical?: boolean; earlierRuns: SavedRun[] }) { + const { push } = useNavigation(); const [files, setFiles] = useState([]); const [sourceRoot, setSourceRoot] = useState(""); const [selected, setSelected] = useState>(new Set()); const [skipped, setSkipped] = useState(0); const [busy, setBusy] = useState(false); + const [unresolved, setUnresolved] = useState>([]); + const [decisions, setDecisions] = useState>>({}); + const mappings = [props.run.mapping, ...props.earlierRuns.map((entry) => entry.run.mapping)]; + const baseMapping = withUnambiguousHistoricalMappings(props.run.mapping, mappings.slice(1)); + const candidatesFor = (id: string): MappingEntry[] => { + const unique = new Map(); + for (const mapping of mappings) for (const [key, entry] of Object.entries(mapping)) { + if (key.toUpperCase() === id.toUpperCase()) unique.set(`${entry.type}\0${entry.original}`, entry); + } + return [...unique.values()]; + }; + function saveDecision(file: string, id: string, decision: RestoreDecision) { + setDecisions((current) => ({ ...current, + [file]: { ...current[file], [id.toUpperCase()]: decision }, + })); + setUnresolved((current) => current.filter((item) => item.file !== file || item.id !== id)); + } useEffect(() => { let active = true; async function load() { @@ -173,64 +232,91 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo const parent = join(homedir(), "Downloads", "Velum"); let targetRoot: string | undefined; try { - const mappings = [props.run.mapping, ...props.earlierRuns.map((run) => run.mapping)]; - const mapping = withUnambiguousHistoricalMappings(props.run.mapping, mappings.slice(1)); - if (!Object.keys(mapping).length) throw new Error("Dieser Projektstand hat keine Übersetzungstabelle."); - const names = new Set(); - const planned = files.filter((item) => selected.has(item.relPath)).map((file) => ({ - file, restoredName: restorePath(file.relPath, mapping, props.run.matchModes), - })); - const renamedFiles = planned.filter(({ file, restoredName }) => restoredName !== file.relPath).length; - let contentReplacements = 0; - for (const { restoredName } of planned) { - if (names.has(restoredName)) throw new Error(`Mehrdeutiger Ausgabename: ${restoredName}`); - names.add(restoredName); + if (!Object.keys(baseMapping).length && !Object.keys(decisions).length) { + throw new Error("Dieser Projektstand hat keine Übersetzungstabelle."); } + const names = new Set(); + const planned = files.filter((item) => selected.has(item.relPath)); + let renamedFiles = 0; + let contentReplacements = 0; await fs.mkdir(parent, { recursive: true, mode: 0o700 }); targetRoot = await fs.mkdtemp(join(parent, `${basename(props.run.projectName)}-${stamp}-`)); - for (const { file, restoredName } of planned) { + for (const file of planned) { const source = resolveWithin(sourceRoot, file.relPath); - const target = resolveWithin(targetRoot, restoredName); if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Datei: ${file.relPath}`); const data = await fs.readFile(source); + const mapping: PlaceholderMapping = { ...baseMapping }; + const manual = decisions[file.relPath] ?? {}; + for (const [id, entry] of Object.entries(manual)) if (entry) mapping[id] = entry; + let restoredName = restorePath(file.relPath, mapping, props.run.matchModes); let result: Buffer; if (file.kind === "document") { result = await depseudonymizeDocument(basename(file.relPath), data, mapping); } else { const markdown = isMarkdownFile(file.relPath); - const restored = restoreTextWithCount(data.toString("utf8"), mapping, props.run.matchModes, markdown); + const text = data.toString("utf8"); + let restored = restoreTextWithCount(text, mapping, props.run.matchModes, markdown); if (markdown) { - const unresolved = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings); - if (unresolved.length) throw new Error(`${file.relPath}: Platzhalter ohne eindeutige Zuordnung: ${unresolved.slice(0, 5).join(", ")}${unresolved.length > 5 ? " …" : ""}. Bitte Projektstand prüfen.`); + let missing = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings) + .filter((id) => manual[id.toUpperCase()] !== null); + if (missing.length) { + const exactMapping = await mappingForMatchingSnapshots(file.relPath, digest(data), props.earlierRuns); + for (const id of missing) { + const match = Object.entries(exactMapping).find(([key]) => key.toUpperCase() === id.toUpperCase()); + if (match && !Object.keys(mapping).some((key) => key.toUpperCase() === id.toUpperCase())) { + mapping[match[0]] = match[1]; + } + } + restoredName = restorePath(file.relPath, mapping, props.run.matchModes); + restored = restoreTextWithCount(text, mapping, props.run.matchModes, true); + missing = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings) + .filter((id) => manual[id.toUpperCase()] !== null); + } + if (missing.length) throw new UnresolvedRestoreError(file.relPath, missing); } contentReplacements += restored.replacements; result = Buffer.from(restored.text, "utf8"); } + if (names.has(restoredName)) throw new Error(`Mehrdeutiger Ausgabename: ${restoredName}`); + names.add(restoredName); + if (restoredName !== file.relPath) renamedFiles++; + const target = resolveWithin(targetRoot, restoredName); await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 }); await fs.writeFile(target, result, { flag: "wx", mode: 0o600 }); } - if (!renamedFiles && !contentReplacements && planned.every(({ file }) => file.kind === "text")) { + if (!renamedFiles && !contentReplacements && planned.every((file) => file.kind === "text") + && !planned.some((file) => Object.values(decisions[file.relPath] ?? {}).includes(null))) { throw new Error("Keine passenden Velum-Platzhalter in den ausgewählten Textdateien oder Dateinamen gefunden. Bitte Quelle und Projektstand prüfen."); } + setUnresolved([]); toast.style = Toast.Style.Success; toast.title = `${selected.size} Klartext-Dateien in Downloads`; + const deliberatelyKept = planned.reduce((count, file) => count + + Object.values(decisions[file.relPath] ?? {}).filter((entry) => entry === null).length, 0); toast.message = `${contentReplacements} Textersetzungen · ${renamedFiles} Dateinamen geändert` - + (planned.some(({ file }) => file.kind === "document") ? " · Office-Inhalte nicht gezählt" : ""); + + (deliberatelyKept ? ` · ${deliberatelyKept} Platzhalter bewusst belassen` : "") + + (planned.some((file) => file.kind === "document") ? " · Office-Inhalte nicht gezählt" : ""); await showInFinder(targetRoot).catch(() => undefined); } catch (error) { if (targetRoot) await fs.rm(targetRoot, { recursive: true, force: true }); + if (error instanceof UnresolvedRestoreError) setUnresolved(error.ids.map((id) => ({ file: error.file, id }))); toast.style = Toast.Style.Failure; - toast.title = "Klartext-Export fehlgeschlagen"; - toast.message = (error as Error).message; + toast.title = error instanceof UnresolvedRestoreError ? "Platzhalter zuordnen" : "Klartext-Export fehlgeschlagen"; + toast.message = error instanceof UnresolvedRestoreError + ? `${error.file}: ${error.ids.join(", ")}. Bitte die Einträge unten klären und den Export erneut starten.` + : (error as Error).message; } finally { setBusy(false); } } const textFiles = files.filter((file) => file.kind === "text"); const complexFiles = files.filter((file) => file.kind === "document"); const sourceLabel = props.historical ? "Gespeicherter Projektstand" : props.run.inPlace || props.run.sourceInPlace ? "Aktueller Projektordner" : "Pseudonymisierte Kopien"; - const renderFile = (file: ProjectFile) => { + const displayMapping: PlaceholderMapping = { ...baseMapping }; + for (const [id, entry] of Object.entries(decisions[file.relPath] ?? {})) if (entry) displayMapping[id] = entry; + return toggle(file.relPath)} /> @@ -239,6 +325,7 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo setSelected(new Set(files.map((item) => item.relPath)))} /> setSelected(new Set())} /> } />; + }; return @@ -249,6 +336,18 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo showInFinder(sourceRoot)} />} /> + {unresolved.some((item) => selected.has(item.file)) && + {unresolved.filter((item) => selected.has(item.file)).map(({ file, id }) => { + const candidates = candidatesFor(id); + return 1 ? `${candidates.length} verschiedene alte Zuordnungen` + : candidates.length ? "Gespeicherter Eintrag – bitte prüfen" : "Kein gespeicherter Eintrag" }]} + actions={ push( saveDecision(file, id, decision)} />)} />} />; + })} + } {textFiles.map(renderFile)} @@ -269,7 +368,7 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) { actions={ push( entry.run)} />)} /> + earlierRuns={props.entries.slice(index + 1)} />)} /> } /> @@ -278,7 +377,7 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) { {run.copyPath && push( entry.run)} />)} />} + earlierRuns={props.entries.slice(index + 1)} />)} />} } />)} ; @@ -334,9 +433,14 @@ export default function Command() { actions={ push( entry.run)} />)} /> + earlierRuns={entries.slice(1)} />)} /> } /> + target={ { + const updated = await addProjectMappingEntry(run.projectPath, input); + await refresh(); + return updated.mapping; + }} />} /> showInFinder(runCopiesPath(run, directory))} /> diff --git a/src/show-translation-tables.tsx b/src/show-translation-tables.tsx index b44a627..adc45cd 100644 --- a/src/show-translation-tables.tsx +++ b/src/show-translation-tables.tsx @@ -2,14 +2,16 @@ import { Action, ActionPanel, Detail, + Form, Icon, List, showToast, Toast, + useNavigation, } from "@raycast/api"; -import { useEffect, useState } from "react"; -import { canonicalProjectPath, listAllRuns } from "./lib/velum-project"; -import { listSessions } from "./sessions"; +import { useCallback, useEffect, useState } from "react"; +import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry } from "./lib/velum-project"; +import { getSession, listSessions, updateSessionMapping } from "./sessions"; import type { PlaceholderMapping } from "./types"; import { markdownCodeBlock } from "./ui"; @@ -20,15 +22,48 @@ type TableSource = { mapping: PlaceholderMapping; }; +type ManualEntry = { original: string; type: string; placeholder?: string }; + +function AddMappingForm(props: { onAdd: (input: ManualEntry) => Promise; + onSaved: (mapping: PlaceholderMapping) => void }) { + const { pop } = useNavigation(); + const [busy, setBusy] = useState(false); + async function save(values: { original: string; type: string; placeholder: string }) { + setBusy(true); + try { + const type = values.type.trim() || /^([A-ZÄÖÜ][A-ZÄÖÜ0-9_]*)_\d+$/iu.exec(values.placeholder.trim())?.[1] || "BEGRIFF"; + const mapping = await props.onAdd({ ...values, type }); + props.onSaved(mapping); + await showToast({ style: Toast.Style.Success, title: "Zuordnung gespeichert" }); + pop(); + } catch (error) { + await showToast({ style: Toast.Style.Failure, title: "Zuordnung nicht gespeichert", + message: (error as Error).message }); + } finally { setBusy(false); } + } + return
}> + + + + + ; +} + export function TranslationTable({ title, mapping, + onAdd, }: { title: string; mapping: PlaceholderMapping; + onAdd?: (input: ManualEntry) => Promise; }) { + const { push } = useNavigation(); + const [visibleMapping, setVisibleMapping] = useState(mapping); + useEffect(() => setVisibleMapping(mapping), [mapping]); const groups = new Map>(); - for (const entry of Object.entries(mapping).sort(([a], [b]) => + for (const entry of Object.entries(visibleMapping).sort(([a], [b]) => a.localeCompare(b), )) { const type = entry[1].type || "Sonstige"; @@ -46,6 +81,12 @@ export function TranslationTable({ title="Keine Zuordnungen" description="Für diesen Stand sind noch keine Übersetzungen gespeichert." /> + {onAdd && + push()} />
} /> + } {[...groups] .sort(([a], [b]) => a.localeCompare(b)) .map(([type, entries]) => ( @@ -122,8 +163,8 @@ export default function Command() { const [sessions, setSessions] = useState([]); const [busy, setBusy] = useState(true); - useEffect(() => { - Promise.all([listAllRuns(), listSessions()]) + const refresh = useCallback(async () => { + await Promise.all([listAllRuns(), listSessions()]) .then(([runs, savedSessions]) => { const latest = new Map(); for (const { run } of runs) { @@ -147,16 +188,13 @@ export default function Command() { mapping: session.mapping, })), ); - }) - .catch((error: Error) => - showToast({ - style: Toast.Style.Failure, - title: "Übersetzungstabellen nicht lesbar", - message: error.message, - }), - ) - .finally(() => setBusy(false)); + }); }, []); + useEffect(() => { + refresh().catch((error: Error) => showToast({ style: Toast.Style.Failure, + title: "Übersetzungstabellen nicht lesbar", message: error.message })) + .finally(() => setBusy(false)); + }, [refresh]); return ( { + const run = await addProjectMappingEntry(source.id, input); + await refresh(); + return run.mapping; + }} /> } /> @@ -211,6 +254,19 @@ export default function Command() { { + const session = await getSession(source.id); + if (!session) throw new Error("Sitzung nicht gefunden."); + const normalized = Object.fromEntries(Object.entries(session.mapping) + .map(([key, entry]) => [key.replace(/^<|>$/g, ""), entry])); + const { placeholder, entry } = prepareManualMappingEntry(normalized, [], input); + const bracketed = Object.keys(session.mapping).some((key) => key.startsWith("<")); + const key = bracketed ? `<${placeholder}>` : placeholder; + const updated = await updateSessionMapping(session.id, + { ...session.mapping, [key]: entry }, session.entityTypes); + await refresh(); + return updated.mapping; + }} /> } /> diff --git a/tests/velum-project.test.ts b/tests/velum-project.test.ts index b6c59d0..de20b71 100644 --- a/tests/velum-project.test.ts +++ b/tests/velum-project.test.ts @@ -201,6 +201,54 @@ describe("Velum-Projektstände", () => { expect(project.isMarkdownFile("Notizen.MD")).toBe(true); }); + it("löst eine wiederverwendete ID nur über eine identische gespeicherte Datei auf", async () => { + const root = await fs.mkdtemp(join(tmpdir(), "velum-exact-snapshot-")); + roots.push(root); + const first = await project.createRun(join(root, "Quelle"), root); + const second = await project.createRun(join(root, "Quelle"), root); + const relPath = "Fragenliste.md"; + first.run.files = [{ source: relPath, output: relPath, kind: "text" }]; + second.run.files = [{ source: relPath, output: relPath, kind: "text" }]; + first.run.mapping = { PERSON_61: { original: "Alex Beispiel", type: "PERSON" } }; + second.run.mapping = { PERSON_61: { original: "Mara Muster", type: "PERSON" } }; + const source = Buffer.from("Kommentar PERSON_61"); + await fs.writeFile(join(first.directory, "files", relPath), source); + await fs.writeFile(join(second.directory, "files", relPath), "anderer Inhalt"); + const exact = await project.mappingForMatchingSnapshots(relPath, project.digest(source), [first, second]); + expect(exact.PERSON_61?.original).toBe("Alex Beispiel"); + const unknown = await project.mappingForMatchingSnapshots(relPath, project.digest(Buffer.from("neu")), [first, second]); + expect(unknown.PERSON_61).toBeUndefined(); + }); + + it("ergänzt einen fehlenden Platzhalter in einem neuen Projektstand ohne alte Daten zu ändern", async () => { + const root = await fs.mkdtemp(join(tmpdir(), "velum-manual-mapping-")); + roots.push(root); + const source = join(root, "Quelle"); + await fs.mkdir(source); + const saved = await project.createRun(source, root); + saved.run.mapping = { PERSON_01: { original: "Alex Beispiel", type: "PERSON" } }; + saved.run.files = [{ source: "Notiz.md", output: "Notiz.md", kind: "text" }]; + await fs.writeFile(join(saved.directory, "files", "Notiz.md"), "PERSON_61"); + await project.saveRun(saved.directory, saved.run); + const updated = await project.addProjectMappingEntry(source, + { placeholder: "PERSON_61", original: "Mara Muster", type: "PERSON" }, root); + expect(updated.mapping.PERSON_61?.original).toBe("Mara Muster"); + expect((await project.listRuns(source, root))[0].run.id).toBe(updated.id); + expect(await fs.readFile(join(saved.directory, "files", "Notiz.md"), "utf8")).toBe("PERSON_61"); + expect((await project.listRuns(source, root))[1].run.mapping.PERSON_61).toBeUndefined(); + expect(await fs.readFile(join(project.projectDataRoot(source, root), "runs", updated.id, "files", "Notiz.md"), "utf8")) + .toBe("PERSON_61"); + expect(project.prepareManualMappingEntry(updated.mapping, [], + { original: "Weiterer Begriff", type: "PERSON" }).placeholder).toBe("PERSON_62"); + }); + + it("verhindert eine neue projektweite Zuordnung für eine früher anders belegte ID", () => { + expect(() => project.prepareManualMappingEntry({}, [ + { PERSON_61: { original: "Alex Beispiel", type: "PERSON" } }, + ], { placeholder: "PERSON_61", original: "Mara Muster", type: "PERSON" })) + .toThrow("andere Bedeutung"); + }); + it("übernimmt API-Trefferpositionen auch nach einem Emoji korrekt", () => { const text = "😀 Max"; const spans = project.toUtf16Offsets(text, [{ id: "max", start: 2, end: 5, placeholder: "PERSON_01" }]);