Restore embedded placeholders in Markdown project exports

This commit is contained in:
muena
2026-10-15 09:01:44 +02:00
parent 925890a156
commit 8557a9b809
4 changed files with 88 additions and 19 deletions

View File

@@ -3,7 +3,7 @@ import { basename, dirname, join } from "node:path";
import type { PlaceholderMapping } from "../types";
import { canonicalPerson } from "./project-review";
import {
createRun, digest, isRestorableDocument, listRuns, loadProjectWhitelist, publishProjectCopies,
createRun, digest, isMarkdownFile, isRestorableDocument, listRuns, loadProjectWhitelist, publishProjectCopies,
replaceProjectFilesInPlace, resolveWithin, restorePath, restoreText,
saveProjectWhitelist, saveRun,
} from "./velum-project";
@@ -143,7 +143,8 @@ export async function reviseProjectRun(args: {
const output = file.kind === "document" && isRestorableDocument(file.output)
? await rewriteDocument(basename(file.output), data, plan.replacements)
: file.kind === "document" ? data
: Buffer.from(restoreText(data.toString("utf8"), textReplacements, previous.matchModes), "utf8");
: Buffer.from(restoreText(data.toString("utf8"), textReplacements, previous.matchModes,
isMarkdownFile(file.output)), "utf8");
await fs.writeFile(target, output, { flag: "wx", mode: 0o600 });
run.files.push({ source: file.output, output: outputPath, kind: file.kind });
}

View File

@@ -40,6 +40,7 @@ export type ProjectRun = {
const DOCUMENTS = new Set([".docx", ".xlsx", ".pptx", ".pdf"]);
const RESTORABLE_DOCUMENTS = new Set([".docx", ".xlsx", ".pptx"]);
const MARKDOWN_EXTENSIONS = new Set([".md", ".markdown", ".mdx"]);
const SECRET_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
const EXCLUDES = new Set([".git", "node_modules", "dist", "build", "out", ".next", ".nuxt",
".venv", "venv", "__pycache__", "target", "vendor", "coverage", ".cache", ".turbo",
@@ -264,7 +265,7 @@ export function replaceSpans(
return output;
}
function restorePattern(mapping: PlaceholderMapping, matchModes: ProjectRun["matchModes"], pathSegment = false): {
function restorePattern(mapping: PlaceholderMapping, matchModes: ProjectRun["matchModes"], allowEmbedded = false): {
pattern: RegExp; originalFor: (match: string) => string | undefined;
} | undefined {
const keys = Object.keys(mapping).sort((a, b) => b.length - a.length);
@@ -277,8 +278,8 @@ function restorePattern(mapping: PlaceholderMapping, matchModes: ProjectRun["mat
}
const parts = keys.map((key) => {
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return pathSegment || matchModes?.[key] === "anywhere"
? escaped : `(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`;
return allowEmbedded || matchModes?.[key] === "anywhere"
? `${escaped}(?!\\d)` : `(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`;
});
return {
pattern: new RegExp(parts.join("|"), "giu"),
@@ -291,8 +292,8 @@ function restorePattern(mapping: PlaceholderMapping, matchModes: ProjectRun["mat
}
export function restoreTextWithCount(source: string, mapping: PlaceholderMapping,
matchModes?: ProjectRun["matchModes"]): { text: string; replacements: number } {
const pattern = restorePattern(mapping, matchModes);
matchModes?: ProjectRun["matchModes"], allowEmbedded = false): { text: string; replacements: number } {
const pattern = restorePattern(mapping, matchModes, allowEmbedded);
let replacements = 0;
const text = pattern ? source.replace(pattern.pattern, (match) => {
const original = pattern.originalFor(match);
@@ -303,8 +304,39 @@ export function restoreTextWithCount(source: string, mapping: PlaceholderMapping
return { text, replacements };
}
export function restoreText(source: string, mapping: PlaceholderMapping, matchModes?: ProjectRun["matchModes"]): string {
return restoreTextWithCount(source, mapping, matchModes).text;
export function restoreText(source: string, mapping: PlaceholderMapping,
matchModes?: ProjectRun["matchModes"], allowEmbedded = false): string {
return restoreTextWithCount(source, mapping, matchModes, allowEmbedded).text;
}
/** Older snapshots can supply a missing key only when its meaning never changed. */
export function withUnambiguousHistoricalMappings(current: PlaceholderMapping,
earlier: PlaceholderMapping[]): PlaceholderMapping {
const result = { ...current };
const candidates = new Map<string, PlaceholderMapping[string] | null>();
for (const mapping of earlier) {
for (const [key, entry] of Object.entries(mapping)) {
if (Object.prototype.hasOwnProperty.call(current, key)) continue;
const previous = candidates.get(key);
if (previous === null) continue;
if (previous && (previous.original !== entry.original || previous.type !== entry.type)) {
candidates.set(key, null);
} else if (!previous) candidates.set(key, entry);
}
}
for (const [key, entry] of candidates) if (entry) result[key] = entry;
return result;
}
/** Report recognizable Velum IDs that remain after a Markdown restore. */
export function unresolvedPlaceholderIds(source: string, mappings: PlaceholderMapping[]): string[] {
const prefixes = new Set(mappings.flatMap((mapping) => Object.keys(mapping)
.map((key) => /^([\p{L}]+)_\d+$/u.exec(key)?.[1]).filter((value): value is string => Boolean(value))));
if (!prefixes.size) return [];
const alternatives = [...prefixes].sort((a, b) => b.length - a.length)
.map((prefix) => prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
const pattern = new RegExp(`(?<![\\p{L}\\p{N}])(?:${alternatives.join("|")})_\\d+(?!\\d)`, "giu");
return [...new Set(source.match(pattern) ?? [])];
}
export function restorePath(relPath: string, mapping: PlaceholderMapping, matchModes?: ProjectRun["matchModes"]): string {
@@ -470,6 +502,10 @@ export function isRestorableDocument(filename: string): boolean {
return RESTORABLE_DOCUMENTS.has(extname(filename).toLowerCase());
}
export function isMarkdownFile(filename: string): boolean {
return MARKDOWN_EXTENSIONS.has(extname(filename).toLowerCase());
}
export function resolveWithin(root: string, relPath: string): string {
const target = resolve(root, safeRelativePath(relPath));
if (!target.startsWith(resolve(root) + sep)) throw new Error("Ausgabepfad verlässt den Zielordner.");

View File

@@ -4,7 +4,7 @@ import { homedir } from "node:os";
import { basename, dirname, join } from "node:path";
import { useEffect, useState } from "react";
import { depseudonymizeDocument } from "./velum";
import { canonicalProjectPath, listAllRuns, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles } from "./lib/velum-project";
import { canonicalProjectPath, isMarkdownFile, listAllRuns, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, withUnambiguousHistoricalMappings } from "./lib/velum-project";
import type { ProjectFile, ProjectRun } from "./lib/velum-project";
import { canonicalPerson, mergePeople } from "./lib/project-review";
import { planProjectRevision, reviseProjectRun } from "./lib/project-revision";
@@ -132,7 +132,7 @@ function RevisionReview(props: { saved: SavedRun; onSaved: () => Promise<void> }
</List>;
}
function FilePicker(props: { run: ProjectRun; directory: string; historical?: boolean }) {
function FilePicker(props: { run: ProjectRun; directory: string; historical?: boolean; earlierRuns: ProjectRun[] }) {
const [files, setFiles] = useState<ProjectFile[]>([]);
const [sourceRoot, setSourceRoot] = useState("");
const [selected, setSelected] = useState<Set<string>>(new Set());
@@ -173,10 +173,12 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
const parent = join(homedir(), "Downloads", "Velum");
let targetRoot: string | undefined;
try {
if (!Object.keys(props.run.mapping).length) throw new Error("Dieser Projektstand hat keine Übersetzungstabelle.");
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<string>();
const planned = files.filter((item) => selected.has(item.relPath)).map((file) => ({
file, restoredName: restorePath(file.relPath, props.run.mapping, props.run.matchModes),
file, restoredName: restorePath(file.relPath, mapping, props.run.matchModes),
}));
const renamedFiles = planned.filter(({ file, restoredName }) => restoredName !== file.relPath).length;
let contentReplacements = 0;
@@ -193,9 +195,14 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
const data = await fs.readFile(source);
let result: Buffer;
if (file.kind === "document") {
result = await depseudonymizeDocument(basename(file.relPath), data, props.run.mapping);
result = await depseudonymizeDocument(basename(file.relPath), data, mapping);
} else {
const restored = restoreTextWithCount(data.toString("utf8"), props.run.mapping, props.run.matchModes);
const markdown = isMarkdownFile(file.relPath);
const restored = restoreTextWithCount(data.toString("utf8"), 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.`);
}
contentReplacements += restored.replacements;
result = Buffer.from(restored.text, "utf8");
}
@@ -256,12 +263,13 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) {
return <List navigationTitle={`${props.projectName}: frühere Stände`}
searchBarPlaceholder="Stand suchen">
<List.Section title="Frühere Stände · nur für Klartext-Export">
{props.entries.map(({ run, directory }) => <List.Item key={run.id} icon={Icon.Clock}
{props.entries.map(({ run, directory }, index) => <List.Item key={run.id} icon={Icon.Clock}
title={new Date(run.createdAt).toLocaleString("de-AT")}
subtitle={`${run.files.length} Dateien`}
actions={<ActionPanel>
<Action title="Gespeicherten Stand wiederherstellen" icon={Icon.Download}
onAction={() => push(<FilePicker run={run} directory={directory} historical />)} />
onAction={() => push(<FilePicker run={run} directory={directory} historical
earlierRuns={props.entries.slice(index + 1).map((entry) => entry.run)} />)} />
<Action.Push title="Übersetzungstabelle anzeigen" icon={Icon.List}
target={<TranslationTable title={`${props.projectName} · ${new Date(run.createdAt).toLocaleString("de-AT")}`}
mapping={run.mapping} />} />
@@ -269,7 +277,8 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) {
onAction={() => showInFinder(runCopiesPath(run, directory))} />
<Action.CopyToClipboard title="Speicherpfad kopieren" content={runCopiesPath(run, directory)} />
{run.copyPath && <Action title="Aktuelle Dateien dieses Kopienordners wiederherstellen" icon={Icon.Download}
onAction={() => push(<FilePicker run={run} directory={directory} />)} />}
onAction={() => push(<FilePicker run={run} directory={directory}
earlierRuns={props.entries.slice(index + 1).map((entry) => entry.run)} />)} />}
</ActionPanel>} />)}
</List.Section>
</List>;
@@ -300,7 +309,8 @@ export default function Command() {
...(entries.length > 1 ? [{ text: `${entries.length} Stände` }] : [])]}
actions={<ActionPanel>
<Action title="Projektdateien als Klartext wiederherstellen" icon={Icon.Download}
onAction={() => push(<FilePicker run={run} directory={directory} />)} />
onAction={() => push(<FilePicker run={run} directory={directory}
earlierRuns={entries.slice(1).map((entry) => entry.run)} />)} />
<Action.Push title="Übersetzungstabelle anzeigen" icon={Icon.List}
target={<TranslationTable title={run.projectName} mapping={run.mapping} />} />
<Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder}