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.");