Files
velum-raycast/src/lib/xlsx-restoration.ts

275 lines
15 KiB
TypeScript

import { createReadStream, closeSync, openSync, writeSync, promises as fs } from "node:fs";
import { join, posix } from "node:path";
import { tmpdir } from "node:os";
import { TextDecoder } from "node:util";
import { Unzip, UnzipInflate, Zip, ZipDeflate } from "fflate";
import { SaxesParser, type SaxesTagNS } from "saxes";
import type { PlaceholderMapping } from "../types";
const EMPTY = new Uint8Array(0);
const SPREADSHEET = new Set([
"http://schemas.openxmlformats.org/spreadsheetml/2006/main",
"http://purl.oclc.org/ooxml/spreadsheetml/main",
]);
const DRAWING = new Set([
"http://schemas.openxmlformats.org/drawingml/2006/main",
"http://purl.oclc.org/ooxml/drawingml/main",
]);
const WORD = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
const isTextRun = (node: SaxesTagNS) => node.local === "t" && (SPREADSHEET.has(node.uri) || DRAWING.has(node.uri) || node.uri === WORD);
const isTextUnit = (node: SaxesTagNS) => SPREADSHEET.has(node.uri) && ["si", "is"].includes(node.local)
|| node.local === "p" && (DRAWING.has(node.uri) || node.uri === WORD);
const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, index) => {
let value = index;
for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ (value & 1 ? 0xedb88320 : 0);
return value >>> 0;
});
function crcUpdate(crc: number, data: Uint8Array): number {
for (const value of data) crc = (crc >>> 8) ^ CRC_TABLE[(crc ^ value) & 255];
return crc;
}
type ZipPart = { size: number; crc: number };
/** Inspect the small central directory; never load a worksheet or the whole ZIP. */
async function zipIndex(path: string): Promise<Map<string, ZipPart>> {
const file = await fs.open(path, "r");
try {
const { size } = await file.stat();
const tail = Buffer.alloc(Math.min(size, 65_557));
await file.read(tail, 0, tail.length, size - tail.length);
let end = -1;
for (let i = tail.length - 22; i >= 0; i--) {
if (tail.readUInt32LE(i) === 0x06054b50 && i + 22 + tail.readUInt16LE(i + 20) === tail.length) { end = i; break; }
}
if (end < 0) throw new Error("Excel-Datei ist kein vollständiges ZIP-Archiv.");
const entries = tail.readUInt16LE(end + 10);
const length = tail.readUInt32LE(end + 12), offset = tail.readUInt32LE(end + 16);
if (tail.readUInt16LE(end + 4) || tail.readUInt16LE(end + 6) || entries !== tail.readUInt16LE(end + 8)
|| entries === 0xffff || offset === 0xffffffff || length > 16 * 1024 * 1024 || offset + length > size - tail.length + end) {
throw new Error("Nicht unterstütztes Excel-ZIP-Archiv (mehrteilig, ZIP64 oder zu großes Inhaltsverzeichnis).");
}
const directory = Buffer.alloc(length);
if ((await file.read(directory, 0, length, offset)).bytesRead !== length) throw new Error("Unvollständiges ZIP-Inhaltsverzeichnis.");
const parts = new Map<string, ZipPart>();
let cursor = 0, total = 0;
for (let index = 0; index < entries; index++) {
if (cursor + 46 > length || directory.readUInt32LE(cursor) !== 0x02014b50) throw new Error("Ungültiges ZIP-Inhaltsverzeichnis.");
const flags = directory.readUInt16LE(cursor + 8), method = directory.readUInt16LE(cursor + 10);
const nameLength = directory.readUInt16LE(cursor + 28);
const next = cursor + 46 + nameLength + directory.readUInt16LE(cursor + 30) + directory.readUInt16LE(cursor + 32);
if (next > length || flags & 1 || ![0, 8].includes(method)) throw new Error("Verschlüsselte oder nicht unterstützte Excel-Datei.");
const rawName = directory.subarray(cursor + 46, cursor + 46 + nameLength);
if (!(flags & 0x800) && rawName.some((value) => value > 127)) throw new Error("Nicht unterstützte ZIP-Dateinamencodierung.");
const name = new TextDecoder("utf-8", { fatal: true }).decode(rawName);
if (parts.has(name) || name.startsWith("/") || name.includes("\\")
|| posix.normalize(name) !== name || name.split("/").includes("..")) throw new Error("Ungültiger oder doppelter Excel-Paketbestandteil.");
const part = { size: directory.readUInt32LE(cursor + 24), crc: directory.readUInt32LE(cursor + 16) };
total += part.size;
if (part.size === 0xffffffff || total > 2 * 1024 * 1024 * 1024) throw new Error("Entpackte Excel-Datei überschreitet 2 GiB.");
parts.set(name, part);
cursor = next;
}
if (cursor !== length || !parts.has("xl/workbook.xml") || !parts.has("[Content_Types].xml")) throw new Error("Datei ist kein unterstütztes Excel-Workbook.");
return parts;
} finally { await file.close(); }
}
function escapeXml(value: string, attribute = false): string {
let result = value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r/g, "&#13;");
if (attribute) result = result.replace(/"/g, "&quot;").replace(/\t/g, "&#9;").replace(/\n/g, "&#10;");
return result;
}
function restorationPattern(mapping: PlaceholderMapping) {
const originals = new Map<string, string>();
for (const [key, entry] of Object.entries(mapping)) {
for (const char of entry.original) {
const code = char.codePointAt(0)!;
if ((code < 32 && ![9, 10, 13].includes(code)) || (code >= 0xd800 && code <= 0xdfff) || code === 0xfffe || code === 0xffff) {
throw new Error("Zuordnung enthält Zeichen, die in Excel-XML nicht erlaubt sind.");
}
}
originals.set(key, entry.original);
}
const keys = [...originals.keys()].filter((key) => key && !/^[A-Z][A-Z0-9]*_\d+$/.test(key)).sort((a, b) => b.length - a.length);
const alternatives = keys.map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
alternatives.push("[A-Z][A-Z0-9]*_\\d+");
const pattern = originals.size ? new RegExp(`(?<![\\p{L}\\p{N}_])(?:${alternatives.join("|")})(?![\\p{L}\\p{N}_])`, "gu") : undefined;
return { originals, pattern };
}
type Token = { markup: string } | { text: string; run: boolean };
/** Buffer one rich-text cell or drawing paragraph, never a table or worksheet. */
function xmlRestorer(mapping: ReturnType<typeof restorationPattern>, emit: (text: string) => void, workbook: boolean) {
let replacements = 0;
const restore = (text: string) => mapping.pattern ? text.replace(mapping.pattern, (match) => {
const original = mapping.originals.get(match);
if (original === undefined) return match;
replacements++;
return original;
}) : text;
const parser = new SaxesParser({ xmlns: true });
const stack: SaxesTagNS[] = [];
let cell: { depth: number; tokens: Token[]; length: number } | undefined;
let pending = "";
const append = (token: Token) => {
if (!cell) { emit("markup" in token ? token.markup : escapeXml(restore(token.text))); return; }
cell.length += "markup" in token ? token.markup.length : token.text.length;
if (cell.length > 4 * 1024 * 1024) throw new Error("Eine einzelne Excel-Zelle überschreitet 4 MiB XML.");
cell.tokens.push(token);
};
const flushText = () => {
if (!pending) return;
const node = stack.at(-1);
append({ text: pending, run: Boolean(node && isTextRun(node)) });
pending = "";
};
const flushCell = () => {
const tokens = cell!.tokens;
const runs = tokens.filter((token): token is Extract<Token, { text: string }> => "text" in token && token.run);
const joined = runs.map((run) => run.text).join("");
const matches = mapping.pattern ? [...joined.matchAll(mapping.pattern)].filter((match) => mapping.originals.has(match[0])) : [];
replacements += matches.length;
let offset = 0, next = 0;
for (const run of runs) {
const start = offset, end = start + run.text.length;
let cursor = 0, output = "";
while (next < matches.length && matches[next].index + matches[next][0].length <= start) next++;
for (let i = next; i < matches.length && matches[i].index < end; i++) {
const match = matches[i], stop = match.index + match[0].length;
output += run.text.slice(cursor, Math.max(cursor, match.index - start));
if (match.index >= start) output += mapping.originals.get(match[0])!;
cursor = Math.min(run.text.length, stop - start);
}
run.text = output + run.text.slice(cursor);
offset = end;
}
for (const token of tokens) emit("markup" in token ? token.markup : escapeXml(token.run ? token.text : restore(token.text)));
cell = undefined;
};
parser.on("xmldecl", (declaration) => {
if (declaration.version !== "1.0") throw new Error("Nur XML 1.0 wird in Excel-Dateien unterstützt.");
});
parser.on("doctype", () => { throw new Error("DTD/Entities werden in Excel-Dateien nicht unterstützt."); });
parser.on("opentag", (node) => {
flushText();
if (!stack.length && workbook && (!SPREADSHEET.has(node.uri) || node.local !== "workbook")) throw new Error("Ungültiger Excel-Workbook-Bestandteil.");
stack.push(node);
if (!cell && isTextUnit(node)) cell = { depth: stack.length, tokens: [], length: 0 };
const attributes = Object.values(node.attributes).map((attr) => ` ${attr.name}="${escapeXml(restore(attr.value), true)}"`).join("");
const preserve = SPREADSHEET.has(node.uri) && node.local === "t" && !node.attributes["xml:space"] ? ' xml:space="preserve"' : "";
append({ markup: `<${node.name}${attributes}${preserve}>` });
});
parser.on("closetag", (node) => {
flushText();
append({ markup: `</${node.name}>` });
if (cell?.depth === stack.length) flushCell();
stack.pop();
});
const text = (value: string) => {
pending += value;
if (pending.length > 4 * 1024 * 1024) throw new Error("Ein Excel-Textknoten überschreitet 4 MiB.");
};
parser.on("text", text);
parser.on("cdata", text);
parser.on("comment", (value) => { flushText(); append({ markup: `<!--${value}-->` }); });
parser.on("processinginstruction", (value) => { flushText(); append({ markup: `<?${value.target}${value.body ? " " + value.body : ""}?>` }); });
emit('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>');
return { push: (text: string) => parser.write(text), end: () => { parser.close(); flushText(); return replacements; } };
}
/** Restore an XLSX directly from disk to a new private file, with bounded XML memory. */
export async function restoreXlsxFile(source: string, target: string, mapping: PlaceholderMapping,
onProgress: (percent: number) => void = () => undefined): Promise<{ replacements: number }> {
const before = await fs.stat(source);
const index = await zipIndex(source);
const matcher = restorationPattern(mapping);
const descriptor = openSync(target, "wx", 0o600);
let complete = false, zipComplete = false, replacements = 0, processed = 0, progress = -1;
const seen = new Set<string>(), finished = new Set<string>();
const total = [...index.values()].reduce((sum, part) => sum + part.size, 0);
const zip = new Zip((error, data, final) => {
if (error) throw error;
let offset = 0;
while (offset < data.length) offset += writeSync(descriptor, data, offset, data.length - offset);
if (final) zipComplete = true;
});
try {
const unzip = new Unzip((file) => {
const expected = index.get(file.name);
if (!expected || seen.has(file.name)) throw new Error("Excel-ZIP-Inhaltsverzeichnis stimmt nicht mit den Paketdaten überein.");
seen.add(file.name);
const output = new ZipDeflate(file.name, { level: 4 });
zip.add(output);
let crc = 0xffffffff, size = 0;
let fragments: string[] = [], length = 0;
const flush = () => {
if (!length) return;
output.push(Buffer.from(fragments.join(""), "utf8"));
fragments = []; length = 0;
};
const xml = /\.(xml|rels)$/i.test(file.name) ? xmlRestorer(matcher, (value) => {
fragments.push(value); length += value.length;
if (length >= 64 * 1024) flush();
}, file.name === "xl/workbook.xml") : undefined;
let decoder: TextDecoder | undefined, header = Buffer.alloc(0);
const decode = (data: Uint8Array, final: boolean) => {
if (!decoder) {
header = Buffer.concat([header, data]);
if (header.length < 4 && !final) return;
const encoding = header[0] === 0xff && header[1] === 0xfe || header[0] === 0x3c && header[1] === 0 ? "utf-16le"
: header[0] === 0xfe && header[1] === 0xff || header[0] === 0 && header[1] === 0x3c ? "utf-16be" : "utf-8";
decoder = new TextDecoder(encoding, { fatal: true });
data = header; header = Buffer.alloc(0);
}
xml!.push(decoder.decode(data, { stream: !final }));
};
file.ondata = (error, data, final) => {
if (error) throw error;
size += data.length;
if (size > expected.size) throw new Error("Excel-Paketbestandteil überschreitet seine angegebene Größe.");
crc = crcUpdate(crc, data);
for (let offset = 0; offset < data.length; offset += 64 * 1024) {
const part = data.subarray(offset, offset + 64 * 1024);
if (xml) decode(part, false); else output.push(part);
}
processed += data.length;
const percent = Math.floor(processed * 100 / Math.max(total, 1));
if (percent !== progress) { progress = percent; onProgress(percent); }
if (final) {
if (size !== expected.size || ((crc ^ 0xffffffff) >>> 0) !== expected.crc) throw new Error("Excel-Paketbestandteil ist beschädigt (Größe/CRC).");
if (xml) { decode(EMPTY, true); replacements += xml.end(); flush(); }
output.push(EMPTY, true);
finished.add(file.name);
}
};
file.start();
});
unzip.register(UnzipInflate);
for await (const data of createReadStream(source, { highWaterMark: 16 * 1024 })) unzip.push(data, false);
unzip.push(EMPTY, true);
if (finished.size !== index.size) throw new Error("Excel-ZIP-Archiv ist unvollständig.");
zip.end();
if (!zipComplete) throw new Error("Excel-Ausgabedatei wurde nicht vollständig geschrieben.");
const after = await fs.stat(source);
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino) throw new Error("Excel-Datei wurde während der Wiederherstellung geändert.");
complete = true;
return { replacements };
} finally {
zip.terminate();
closeSync(descriptor);
if (!complete) await fs.rm(target, { force: true });
}
}
/** Compatibility for callers already holding an Office document in memory. */
export async function restoreXlsxBuffer(data: Buffer, mapping: PlaceholderMapping): Promise<Buffer> {
const directory = await fs.mkdtemp(join(tmpdir(), "velum-xlsx-restore-"));
try {
const source = join(directory, "source.xlsx"), target = join(directory, "restored.xlsx");
await fs.writeFile(source, data, { mode: 0o600 });
await restoreXlsxFile(source, target, mapping);
return await fs.readFile(target);
} finally { await fs.rm(directory, { recursive: true, force: true }); }
}