120 lines
6.9 KiB
TypeScript
120 lines
6.9 KiB
TypeScript
import { afterEach, expect, it } from "bun:test";
|
|
import { promises as fs } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { randomBytes } from "node:crypto";
|
|
import { zipSync, unzipSync, strToU8, strFromU8 } from "fflate";
|
|
import { SaxesParser } from "saxes";
|
|
import { restoreXlsxFile } from "../src/lib/xlsx-restoration";
|
|
|
|
const S = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
|
|
const roots: string[] = [];
|
|
afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });
|
|
async function fixture(parts: Record<string, Uint8Array> = {}) {
|
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-xlsx-restore-")); roots.push(root);
|
|
const source = join(root, "source.xlsx"), target = join(root, "restored.xlsx");
|
|
await fs.writeFile(source, zipSync({
|
|
"[Content_Types].xml": strToU8('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>'),
|
|
"xl/workbook.xml": strToU8(`<workbook xmlns="${S}"><sheets><sheet name="PERSON_01" sheetId="1"/></sheets></workbook>`),
|
|
...parts,
|
|
}, { level: 0 }));
|
|
return { source, target };
|
|
}
|
|
function xmlTexts(xml: string): string[] {
|
|
const values: string[] = [];
|
|
const parser = new SaxesParser();
|
|
parser.on("text", (text) => values.push(text));
|
|
parser.write(xml).close();
|
|
return values;
|
|
}
|
|
|
|
it("restores placeholders across rich-text runs while preserving XML escaping and boundaries", async () => {
|
|
const { source, target } = await fixture({
|
|
"xl/sharedStrings.xml": strToU8(`<sst xmlns="${S}" count="2" uniqueCount="2"><si><r><t>PER</t></r><r><rPr><b/></rPr><t>SON_01</t></r></si><si><t>PERSON_010 PERSON_01 xPERSON_01 ÄPERSON_01 UNKNOWN_99</t></si></sst>`),
|
|
"xl/media/image1.png": Uint8Array.from([0, 42, 255]),
|
|
});
|
|
const before = await fs.readFile(source);
|
|
const result = await restoreXlsxFile(source, target, {
|
|
PERSON_01: { original: 'A & B <Müller> "😀"', type: "PERSON" },
|
|
PERSON_010: { original: "Anna", type: "PERSON" },
|
|
});
|
|
const parts = unzipSync(await fs.readFile(target));
|
|
expect(xmlTexts(strFromU8(parts["xl/sharedStrings.xml"]))).toEqual([
|
|
'A & B <Müller> "😀"', 'Anna A & B <Müller> "😀" xPERSON_01 ÄPERSON_01 UNKNOWN_99',
|
|
]);
|
|
expect(strFromU8(parts["xl/sharedStrings.xml"])).toContain("<b></b>");
|
|
expect(parts["xl/media/image1.png"]).toEqual(Uint8Array.from([0, 42, 255]));
|
|
expect(strFromU8(parts["xl/workbook.xml"])).toContain('name="A & B <Müller> "😀""');
|
|
expect(result.replacements).toBe(4);
|
|
expect(await fs.readFile(source)).toEqual(before);
|
|
expect((await fs.stat(target)).mode & 0o777).toBe(0o600);
|
|
});
|
|
|
|
it("restores inline strings, formulas, comments, links and UTF-16 XML without changing numbers", async () => {
|
|
const xml = `<?xml version="1.0" encoding="UTF-16"?><worksheet xmlns="${S}"><sheetData><row><c r="A1" t="inlineStr"><is><t>PERSON_01</t></is></c><c r="B1"><f>"PERSON_01"</f><v>42</v></c></row></sheetData></worksheet>`;
|
|
const { source, target } = await fixture({
|
|
"xl/worksheets/sheet1.xml": Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(xml, "utf16le")]),
|
|
"xl/comments/comment1.xml": strToU8(`<comments xmlns="${S}"><authors><author>PERSON_01</author></authors></comments>`),
|
|
"xl/_rels/workbook.xml.rels": strToU8('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="r1" Target="https://example.test/PERSON_01" TargetMode="External"/></Relationships>'),
|
|
});
|
|
await restoreXlsxFile(source, target, { PERSON_01: { original: "Anna Berger", type: "PERSON" } });
|
|
const parts = unzipSync(await fs.readFile(target));
|
|
expect(xmlTexts(strFromU8(parts["xl/worksheets/sheet1.xml"]))).toEqual(["Anna Berger", '"Anna Berger"', "42"]);
|
|
expect(xmlTexts(strFromU8(parts["xl/comments/comment1.xml"]))).toEqual(["Anna Berger"]);
|
|
expect(strFromU8(parts["xl/_rels/workbook.xml.rels"])).toContain('Target="https://example.test/Anna Berger"');
|
|
});
|
|
|
|
it("supports compressed workbooks above the API's 20 MiB upload limit", async () => {
|
|
const binary = randomBytes(21 * 1024 * 1024);
|
|
const { source, target } = await fixture({
|
|
"xl/media/opaque.bin": binary,
|
|
"xl/sharedStrings.xml": strToU8(`<sst xmlns="${S}">` + '<si><t>PERSON_6001</t></si>'.repeat(170_000) + '</sst>'),
|
|
});
|
|
const mapping = Object.fromEntries(Array.from({ length: 6001 }, (_, i) => [`PERSON_${String(i + 1).padStart(2, "0")}`, { original: `Name ${i + 1}`, type: "PERSON" }]));
|
|
const result = await restoreXlsxFile(source, target, mapping);
|
|
expect((await fs.stat(source)).size).toBeGreaterThan(20 * 1024 * 1024);
|
|
expect(result.replacements).toBe(170_001);
|
|
const parts = unzipSync(await fs.readFile(target));
|
|
expect(parts["xl/media/opaque.bin"]).toEqual(new Uint8Array(binary));
|
|
const restored = strFromU8(parts["xl/sharedStrings.xml"]);
|
|
expect(restored.match(/Name 6001/g)).toHaveLength(170_000);
|
|
expect(restored).not.toContain("PERSON_6001");
|
|
}, 60_000);
|
|
|
|
it("removes incomplete outputs on malformed XML, DTDs and damaged ZIP payloads", async () => {
|
|
for (const xml of ['<bad>', '<!DOCTYPE sst [<!ENTITY x "test">]><sst>&x;</sst>']) {
|
|
const { source, target } = await fixture({ "xl/sharedStrings.xml": strToU8(xml) });
|
|
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow();
|
|
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
|
}
|
|
const { source, target } = await fixture({ "xl/data.bin": strToU8("UNIQUE_PAYLOAD") });
|
|
const data = await fs.readFile(source);
|
|
data[data.indexOf("UNIQUE_PAYLOAD")] ^= 1;
|
|
await fs.writeFile(source, data);
|
|
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow("CRC");
|
|
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
|
});
|
|
|
|
it("does not overwrite an existing target or accept a truncated archive", async () => {
|
|
const { source, target } = await fixture();
|
|
await fs.writeFile(target, "keep this file");
|
|
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow();
|
|
expect(await fs.readFile(target, "utf8")).toBe("keep this file");
|
|
await fs.rm(target);
|
|
const data = await fs.readFile(source);
|
|
await fs.writeFile(source, data.subarray(0, data.length - 30));
|
|
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow("ZIP");
|
|
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
|
});
|
|
|
|
|
|
it("restores split placeholders in DrawingML text boxes and keeps run formatting", async () => {
|
|
const { source, target } = await fixture({
|
|
"xl/drawings/drawing1.xml": strToU8('<a:shape xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:p><a:r><a:rPr b="1"/><a:t>PER</a:t></a:r><a:r><a:t>SON_01</a:t></a:r></a:p></a:shape>'),
|
|
});
|
|
await restoreXlsxFile(source, target, { PERSON_01: { original: "Anna Berger", type: "PERSON" } });
|
|
const drawing = strFromU8(unzipSync(await fs.readFile(target))["xl/drawings/drawing1.xml"]);
|
|
expect(xmlTexts(drawing)).toEqual(["Anna Berger"]);
|
|
expect(drawing).toContain('b="1"');
|
|
});
|