diff --git a/lib/chat-attachments.test.mjs b/lib/chat-attachments.test.mjs
index 645fe5018..039941255 100644
--- a/lib/chat-attachments.test.mjs
+++ b/lib/chat-attachments.test.mjs
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
+import { deflateRawSync, deflateSync } from "node:zlib";
async function loadSubject() {
return import("./chat-attachments.ts");
@@ -9,6 +10,263 @@ function textFile(name, type = "") {
return { name, type };
}
+function mockFile(name, type, buffer) {
+ return {
+ name,
+ type,
+ text: async () => new TextDecoder("utf-8").decode(buffer),
+ arrayBuffer: async () => buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength),
+ };
+}
+
+function createZip(entries) {
+ function crc32(buf) {
+ let crc = ~0;
+ for (let i = 0; i < buf.length; i++) {
+ crc ^= buf[i];
+ for (let j = 0; j < 8; j++) {
+ crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
+ }
+ }
+ return ~crc >>> 0;
+ }
+
+ const localHeaders = [];
+ const cdHeaders = [];
+ let offset = 0;
+
+ for (const entry of entries) {
+ const nameBuf = Buffer.from(entry.name, "utf-8");
+ const dataBuf = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data, "utf-8");
+ const crc = crc32(dataBuf);
+ const uncompressedSize = dataBuf.length;
+
+ let method = 8;
+ let compressedBuf = deflateRawSync(dataBuf);
+ if (entry.store) {
+ method = 0;
+ compressedBuf = dataBuf;
+ }
+ const compressedSize = compressedBuf.length;
+
+ const localHeader = Buffer.alloc(30 + nameBuf.length + compressedBuf.length);
+ localHeader.writeUInt32LE(0x04034b50, 0);
+ localHeader.writeUInt16LE(20, 4);
+ localHeader.writeUInt16LE(0, 6);
+ localHeader.writeUInt16LE(method, 8);
+ localHeader.writeUInt16LE(0, 10);
+ localHeader.writeUInt16LE(0, 12);
+ localHeader.writeUInt32LE(crc, 14);
+ localHeader.writeUInt32LE(compressedSize, 18);
+ localHeader.writeUInt32LE(uncompressedSize, 22);
+ localHeader.writeUInt16LE(nameBuf.length, 26);
+ localHeader.writeUInt16LE(0, 28);
+ nameBuf.copy(localHeader, 30);
+ compressedBuf.copy(localHeader, 30 + nameBuf.length);
+
+ localHeaders.push(localHeader);
+
+ const cdHeader = Buffer.alloc(46 + nameBuf.length);
+ cdHeader.writeUInt32LE(0x02014b50, 0);
+ cdHeader.writeUInt16LE(20, 4);
+ cdHeader.writeUInt16LE(20, 6);
+ cdHeader.writeUInt16LE(0, 8);
+ cdHeader.writeUInt16LE(method, 10);
+ cdHeader.writeUInt16LE(0, 12);
+ cdHeader.writeUInt16LE(0, 14);
+ cdHeader.writeUInt32LE(crc, 16);
+ cdHeader.writeUInt32LE(compressedSize, 20);
+ cdHeader.writeUInt32LE(uncompressedSize, 24);
+ cdHeader.writeUInt16LE(nameBuf.length, 28);
+ cdHeader.writeUInt16LE(0, 30);
+ cdHeader.writeUInt16LE(0, 32);
+ cdHeader.writeUInt16LE(0, 34);
+ cdHeader.writeUInt16LE(0, 36);
+ cdHeader.writeUInt32LE(0, 38);
+ cdHeader.writeUInt32LE(offset, 42);
+ nameBuf.copy(cdHeader, 46);
+
+ cdHeaders.push(cdHeader);
+ offset += localHeader.length;
+ }
+
+ const cdOffset = offset;
+ const cdSize = cdHeaders.reduce((sum, h) => sum + h.length, 0);
+
+ const eocd = Buffer.alloc(22);
+ eocd.writeUInt32LE(0x06054b50, 0);
+ eocd.writeUInt16LE(0, 4);
+ eocd.writeUInt16LE(0, 6);
+ eocd.writeUInt16LE(entries.length, 8);
+ eocd.writeUInt16LE(entries.length, 10);
+ eocd.writeUInt32LE(cdSize, 12);
+ eocd.writeUInt32LE(cdOffset, 16);
+ eocd.writeUInt16LE(0, 20);
+
+ return Buffer.concat([...localHeaders, ...cdHeaders, eocd]);
+}
+
+function createPdf({ text = "", withToUnicode = false, useFlate = true, withLargeImageBeforeText = false } = {}) {
+ const chunks = [];
+ chunks.push(Buffer.from("%PDF-1.4\n%\xE2\xE3\xCF\xD3\n", "binary"));
+
+ const offsets = [];
+
+ function addObj(num, headerStr, streamBuf = null) {
+ offsets[num] = Buffer.concat(chunks).length;
+ chunks.push(Buffer.from(`${num} 0 obj\n${headerStr}\n`, "binary"));
+ if (streamBuf) {
+ chunks.push(Buffer.from("stream\n", "binary"));
+ chunks.push(streamBuf);
+ chunks.push(Buffer.from("\nendstream\n", "binary"));
+ }
+ chunks.push(Buffer.from("endobj\n", "binary"));
+ }
+
+ addObj(1, `<< /Type /Catalog /Pages 2 0 R >>`);
+ addObj(2, `<< /Type /Pages /Kids [3 0 R] /Count 1 >>`);
+
+ if (withLargeImageBeforeText) {
+ // 18 MiB of zeros compresses to ~18 KB; if inflated, it would blow past the 16 MiB text budget.
+ const bigImageRaw = deflateSync(Buffer.alloc(18 * 1024 * 1024));
+ addObj(7, `<< /Type /XObject /Subtype /Image /Width 2000 /Height 3000 /BitsPerComponent 8 /Filter /FlateDecode /Length ${bigImageRaw.length} >>`, bigImageRaw);
+ addObj(8, `<< /Length1 ${18 * 1024 * 1024} /Filter /FlateDecode /Length ${bigImageRaw.length} >>`, bigImageRaw);
+ }
+
+ let fontObj = `<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>`;
+ if (withToUnicode) {
+ fontObj = `<< /Type /Font /Subtype /Type0 /BaseFont /TestFont /Encoding /Identity-H /ToUnicode 5 0 R >>`;
+ }
+ addObj(4, fontObj);
+ if (withToUnicode) {
+ const cmapStream = `/CIDInit /ProcSet findresource begin
+12 dict begin
+begincmap
+/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def
+/CMapName /Custom-ToUnicode def
+/CMapType 2 def
+1 begincodespacerange
+<0000>
+endcodespacerange
+1 beginbfchar
+<0001> <4f60>
+<0002> <597d>
+endbfchar
+endcmap
+CMapName currentdict /CMap defineresource pop
+end
+end`;
+ const cmapBuf = Buffer.from(cmapStream, "utf-8");
+ const cmapDeflated = useFlate ? deflateSync(cmapBuf) : cmapBuf;
+ const filter = useFlate ? `/Filter /FlateDecode ` : "";
+ addObj(5, `<< /Length ${cmapDeflated.length} ${filter}>>`, cmapDeflated);
+ } else {
+ addObj(5, `<< >>`);
+ }
+
+ addObj(3, `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >> /Contents 6 0 R >>`);
+
+ const contentText = text ? `BT\n/F1 12 Tf\n10 700 Td\n${text}\nET` : "";
+ const contentBuf = Buffer.from(contentText, "utf-8");
+ const compressedContent = useFlate && contentBuf.length > 0 ? deflateSync(contentBuf) : contentBuf;
+ const filter = useFlate && contentBuf.length > 0 ? `/Filter /FlateDecode ` : "";
+ addObj(6, `<< /Length ${compressedContent.length} ${filter}>>`, compressedContent);
+
+ const startXref = Buffer.concat(chunks).length;
+ let xref = `xref\n0 7\n0000000000 65535 f \n`;
+ for (let i = 1; i <= 6; i++) {
+ xref += String(offsets[i]).padStart(10, "0") + " 00000 n \n";
+ }
+ xref += `trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n${startXref}\n%%EOF\n`;
+ chunks.push(Buffer.from(xref, "binary"));
+
+ return Buffer.concat(chunks);
+}
+
+function createOleDoc(text) {
+ const sectorSize = 512;
+ const header = Buffer.alloc(512);
+ header.set([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1], 0);
+ header.writeUInt16LE(0xFFFE, 28);
+ header.writeUInt16LE(9, 30);
+ header.writeUInt16LE(6, 32);
+ header.writeUInt32LE(1, 44);
+ header.writeInt32LE(1, 48);
+ header.writeUInt32LE(0x1000, 56);
+ header.writeInt32LE(-2, 60);
+ header.writeUInt32LE(0, 64);
+ header.writeInt32LE(-2, 68);
+ header.writeUInt32LE(0, 72);
+ header.writeInt32LE(0, 76);
+ for (let i = 1; i < 109; i++) {
+ header.writeInt32LE(-1, 76 + i * 4);
+ }
+
+ const textBuf = Buffer.from(text, "utf16le");
+ const wordDocSize = 512 + textBuf.length;
+ const wordDocBuf = Buffer.alloc(Math.ceil(wordDocSize / sectorSize) * sectorSize);
+ wordDocBuf.writeUInt16LE(0xA5EC, 0);
+ wordDocBuf.writeUInt16LE(0x0200, 0x000A);
+ textBuf.copy(wordDocBuf, 0x200);
+
+ const pcdBuf = Buffer.alloc(8);
+ pcdBuf.writeUInt32LE(0x0200, 2);
+
+ const clxPart = Buffer.alloc(1 + 4 + 4 * 2 + 8);
+ clxPart[0] = 2;
+ const pcdtSize = 4 * 2 + 8;
+ clxPart.writeUInt32LE(pcdtSize, 1);
+ clxPart.writeUInt32LE(0, 5);
+ clxPart.writeUInt32LE(text.length, 9);
+ pcdBuf.copy(clxPart, 13);
+
+ const tableSize = clxPart.length;
+ const tableBuf = Buffer.alloc(Math.ceil(tableSize / sectorSize) * sectorSize);
+ clxPart.copy(tableBuf, 0);
+
+ wordDocBuf.writeUInt32LE(0, 0x01A2);
+ wordDocBuf.writeUInt32LE(clxPart.length, 0x01A6);
+
+ const dirBuf = Buffer.alloc(sectorSize);
+ function writeDirEntry(offset, name, type, startSect, size, childId = -1, leftId = -1, rightId = -1) {
+ const nameBuf = Buffer.from(name, "utf16le");
+ nameBuf.copy(dirBuf, offset);
+ dirBuf.writeUInt16LE(nameBuf.length + 2, offset + 64);
+ dirBuf.writeUInt8(type, offset + 66);
+ dirBuf.writeUInt8(1, offset + 67);
+ dirBuf.writeInt32LE(leftId, offset + 68);
+ dirBuf.writeInt32LE(rightId, offset + 72);
+ dirBuf.writeInt32LE(childId, offset + 76);
+ dirBuf.writeInt32LE(startSect, offset + 116);
+ dirBuf.writeUInt32LE(size, offset + 120);
+ }
+
+ writeDirEntry(0, "Root Entry", 5, -2, 0, 1);
+ const wordDocSectCount = wordDocBuf.length / sectorSize;
+ const tableSectCount = tableBuf.length / sectorSize;
+ const wordDocStartSect = 2;
+ const tableStartSect = wordDocStartSect + wordDocSectCount;
+
+ writeDirEntry(128, "WordDocument", 2, wordDocStartSect, wordDocBuf.length, -1, -1, 2);
+ writeDirEntry(256, "1Table", 2, tableStartSect, tableBuf.length, -1, -1, -1);
+
+ const fatBuf = Buffer.alloc(sectorSize, 0xFF);
+ fatBuf.writeInt32LE(-3, 0);
+ fatBuf.writeInt32LE(-2, 4);
+ for (let i = 0; i < wordDocSectCount; i++) {
+ const sect = wordDocStartSect + i;
+ const next = (i === wordDocSectCount - 1) ? -2 : sect + 1;
+ fatBuf.writeInt32LE(next, sect * 4);
+ }
+ for (let i = 0; i < tableSectCount; i++) {
+ const sect = tableStartSect + i;
+ const next = (i === tableSectCount - 1) ? -2 : sect + 1;
+ fatBuf.writeInt32LE(next, sect * 4);
+ }
+
+ return Buffer.concat([header, fatBuf, dirBuf, wordDocBuf, tableBuf]);
+}
+
test("recognizes text and markdown attachments by mime or extension", async () => {
const { isTextAttachmentFile } = await loadSubject();
@@ -98,3 +356,851 @@ test("formats attachment limits for the composer", async () => {
assert.equal(formatAttachmentBytes(512 * 1024), "512 KB");
assert.equal(formatAttachmentBytes(4 * 1024 * 1024), "4 MB");
});
+
+test("isImageAttachmentFile and inferImageMimeType handle raster images and MIME inference", async () => {
+ const { isImageAttachmentFile, inferImageMimeType } = await loadSubject();
+
+ assert.equal(isImageAttachmentFile({ name: "photo.PNG", type: "" }), true);
+ assert.equal(inferImageMimeType({ name: "photo.PNG", type: "" }), "image/png");
+
+ assert.equal(isImageAttachmentFile({ name: "photo.jpg", type: "application/octet-stream" }), true);
+ assert.equal(inferImageMimeType({ name: "photo.jpg", type: "application/octet-stream" }), "image/jpeg");
+
+ assert.equal(isImageAttachmentFile({ name: "pic.webp", type: "image/webp" }), true);
+ assert.equal(inferImageMimeType({ name: "pic.webp", type: "image/webp" }), "image/webp");
+
+ assert.equal(isImageAttachmentFile({ name: "icon.svg", type: "" }), false);
+ assert.equal(isImageAttachmentFile({ name: "icon.svg", type: "image/svg+xml" }), true);
+ assert.equal(inferImageMimeType({ name: "icon.svg", type: "image/svg+xml" }), "image/svg+xml");
+
+ assert.equal(isImageAttachmentFile({ name: "doc.pdf", type: "" }), false);
+});
+
+test("readAttachmentText decodes PDF with FlateDecode + ToUnicode CMap (including CJK) and handles empty/scanned PDF", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const cjkPdf = createPdf({ text: "<00010002> Tj", withToUnicode: true, useFlate: true });
+ const cjkResult = await readAttachmentText(mockFile("test-cjk.pdf", "application/pdf", cjkPdf));
+ assert.equal(cjkResult, "你好");
+
+ const pdfWithBigImageAndFont = createPdf({
+ text: "<00010002> Tj",
+ withToUnicode: true,
+ useFlate: true,
+ withLargeImageBeforeText: true,
+ });
+ const bigMediaResult = await readAttachmentText(mockFile("big-media.pdf", "application/pdf", pdfWithBigImageAndFont));
+ assert.equal(bigMediaResult, "你好");
+
+ const asciiPdf = createPdf({ text: "(Hello World) Tj", withToUnicode: false, useFlate: true });
+ const asciiResult = await readAttachmentText(mockFile("test-ascii.pdf", "application/pdf", asciiPdf));
+ assert.equal(asciiResult, "Hello World");
+
+ const emptyPdf = createPdf({ text: "", withToUnicode: false, useFlate: true });
+ const emptyResult = await readAttachmentText(mockFile("scanned.pdf", "application/pdf", emptyPdf));
+ assert.equal(emptyResult, null);
+});
+
+test("readAttachmentText extracts docx paragraphs and tables", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const docxZip = createZip([
+ {
+ name: "word/document.xml",
+ data: `
+
+ Header Paragraph
+
+
+ Col 1
+ Col 2
+
+
+ A
+ B
+
+
+
+ `,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("sample.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", docxZip));
+ assert.match(result, /Header Paragraph/);
+ assert.match(result, /\| Col 1 \| Col 2 \|/);
+ assert.match(result, /\| A \| B \|/);
+});
+
+test("readAttachmentText extracts xlsx with sharedStrings and worksheet into Markdown table", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const xlsxZip = createZip([
+ {
+ name: "xl/sharedStrings.xml",
+ data: `ItemPriceApple`,
+ },
+ {
+ name: "xl/workbook.xml",
+ data: ``,
+ },
+ {
+ name: "xl/_rels/workbook.xml.rels",
+ data: ``,
+ },
+ {
+ name: "xl/worksheets/sheet1.xml",
+ data: `
+ 01
+ 210.5
+ `,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("book.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip));
+ assert.match(result, /### Sales/);
+ assert.match(result, /\| Item \| Price \|/);
+ assert.match(result, /\| Apple \| 10\.5 \|/);
+});
+
+test("readAttachmentText extracts pptx with slides and speaker notes", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const pptxZip = createZip([
+ {
+ name: "ppt/presentation.xml",
+ data: ``,
+ },
+ {
+ name: "ppt/slides/slide1.xml",
+ data: `
+
+ Slide 1 Title
+
+ `,
+ },
+ {
+ name: "ppt/notesSlides/notesSlide1.xml",
+ data: `
+
+ Speaker note for slide 1
+
+ `,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("pres.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", pptxZip));
+ assert.match(result, /### Slide 1/);
+ assert.match(result, /Slide 1 Title/);
+ assert.match(result, /Speaker note for slide 1/);
+});
+
+test("readAttachmentText extracts odt with paragraphs", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const odtZip = createZip([
+ {
+ name: "content.xml",
+ data: `
+
+ ODT Heading
+ ODT Paragraph text
+
+ `,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("document.odt", "application/vnd.oasis.opendocument.text", odtZip));
+ assert.match(result, /ODT Heading/);
+ assert.match(result, /ODT Paragraph text/);
+});
+
+test("readAttachmentText extracts legacy Word 97-2003 .doc with UTF-16LE CJK text and guards against cyclic FAT", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const oleDoc = createOleDoc("繁體中文 Word 97 測試 123");
+ const result = await readAttachmentText(mockFile("legacy.doc", "application/msword", oleDoc));
+ assert.equal(result, "繁體中文 Word 97 測試 123");
+
+ // Self-referential FAT entry (sector 1 -> sector 1) must terminate cleanly without hanging.
+ const cyclicDoc = Buffer.from(oleDoc);
+ cyclicDoc.writeInt32LE(1, 512 + 4);
+ const cyclicResult = await readAttachmentText(mockFile("cyclic.doc", "application/msword", cyclicDoc));
+ assert.equal(cyclicResult, "繁體中文 Word 97 測試 123");
+});
+
+test("readAttachmentText decodes UTF-16LE and UTF-16BE BOM text files", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const leBuf = Buffer.concat([Buffer.from([0xFF, 0xFE]), Buffer.from("Hello UTF-16LE", "utf16le")]);
+ const leResult = await readAttachmentText(mockFile("utf16le.txt", "text/plain", leBuf));
+ assert.equal(leResult, "Hello UTF-16LE");
+
+ const beBuf = Buffer.from([0xFE, 0xFF, 0x00, 0x48, 0x00, 0x69]); // "Hi"
+ const beResult = await readAttachmentText(mockFile("utf16be.txt", "text/plain", beBuf));
+ assert.equal(beResult, "Hi");
+});
+
+test("readAttachmentText returns null on raw binary files", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const binBuf = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D]);
+ const binResult = await readAttachmentText(mockFile("image.png", "image/png", binBuf));
+ assert.equal(binResult, null);
+});
+
+test("decodeXmlEntities decodes entities in a single pass and supports astral numeric references", async () => {
+ const { decodeXmlEntities } = await loadSubject();
+
+ // Single-pass decoding: < preserves <, never turns into <
+ assert.equal(decodeXmlEntities("<"), "<");
+ assert.equal(decodeXmlEntities(">"), ">");
+ assert.equal(decodeXmlEntities("&"), "&");
+ assert.equal(decodeXmlEntities("""), '"');
+ assert.equal(decodeXmlEntities("'"), "'");
+
+ // Decimal and hex astral numeric references above U+FFFF
+ assert.equal(decodeXmlEntities("😀"), "😀");
+ assert.equal(decodeXmlEntities("😀"), "😀");
+
+ // Preserves invalid codepoints (surrogates and out-of-range)
+ assert.equal(decodeXmlEntities(""), "");
+ assert.equal(decodeXmlEntities(""), "");
+});
+
+test("readAttachmentText extracts epub and decodes XML entities", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const epubZip = createZip([
+ {
+ name: "META-INF/container.xml",
+ data: `
+
+
+
+
+ `,
+ },
+ {
+ name: "OEBPS/content.opf",
+ data: `
+
+
+
+
+
+
+
+ `,
+ },
+ {
+ name: "OEBPS/ch1.xhtml",
+ data: `Chapter 1: <Escaped> & 😀
`,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("book.epub", "application/epub+zip", epubZip));
+ assert.match(result, /Chapter 1: <Escaped> & 😀/);
+});
+
+test("readAttachmentText separates lines for PDF Td and positioning operators", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const multiLinePdf = createPdf({
+ text: "(First line) Tj 0 -15 Td (Second line) Tj T* (Third line) Tj",
+ withToUnicode: false,
+ useFlate: true,
+ });
+ const result = await readAttachmentText(mockFile("multiline.pdf", "application/pdf", multiLinePdf));
+ assert.equal(result, "First line\nSecond line\nThird line");
+});
+
+test("readAttachmentText sorts out-of-order PDF table columns by (Y, X) and spaces TJ cells", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ // Simulate an Excel-exported PDF where ASCII columns are drawn first via TJ negative kerning
+ // and a middle column (dates) is drawn in a subsequent BT...ET block at the same Y coordinates.
+ const tablePdf = createPdf({
+ text: [
+ "1 0 0 1 20 700 Tm [(0653) -4500 (265W36507D) -1200 (S1-300) -20 (A)] TJ",
+ "1 0 0 1 20 680 Tm [(0654) -4500 (264W365059) -1200 (S3-300)] TJ",
+ "ET",
+ "BT /F1 12 Tf",
+ "1 0 0 1 55 700 Tm (10/08) Tj",
+ "1 0 0 1 55 680 Tm (10/14) Tj",
+ ].join("\n"),
+ withToUnicode: false,
+ useFlate: true,
+ });
+ const result = await readAttachmentText(mockFile("table.pdf", "application/pdf", tablePdf));
+ assert.equal(result, "0653 10/08 265W36507D S1-300A\n0654 10/14 264W365059 S3-300");
+});
+
+test("readAttachmentText extracts xlsx with absolute relationship target path", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const xlsxZip = createZip([
+ {
+ name: "xl/workbook.xml",
+ data: ``,
+ },
+ {
+ name: "xl/_rels/workbook.xml.rels",
+ data: ``,
+ },
+ {
+ name: "xl/worksheets/sheet1.xml",
+ data: `
+ 100200
+ `,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("absolute.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip));
+ assert.match(result, /### Data/);
+ assert.match(result, /\| 100 \| 200 \|/);
+});
+
+test("readAttachmentText handles xlsx self-closing empty cells and rows without shifting columns", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const xlsxZip = createZip([
+ {
+ name: "xl/workbook.xml",
+ data: ``,
+ },
+ {
+ name: "xl/_rels/workbook.xml.rels",
+ data: ``,
+ },
+ {
+ name: "xl/worksheets/sheet1.xml",
+ data: `
+
+
+ 42
+
+
+
+ 99
+
+ `,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("sparse.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip));
+ assert.match(result, /### Sheet1/);
+ assert.match(result, /\|\s*\|\s*42\s*\|/);
+ assert.match(result, /\|\s*99\s*\|/);
+});
+
+test("readAttachmentText extracts odf tables with self-closing cells preserving column alignment", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const odsZip = createZip([
+ {
+ name: "content.xml",
+ data: `
+
+
+
+
+ ColA
+ ColB
+ ColC
+
+
+ ValA
+
+ ValC
+
+
+
+
+ `,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("sheet.ods", "application/vnd.oasis.opendocument.spreadsheet", odsZip));
+ assert.match(result, /\| ColA \| ColB \| ColC \|/);
+ assert.match(result, /\| ValA \|\s*\| ValC \|/);
+});
+
+test("readAttachmentText extracts xlsx worksheet with attribute-less row elements", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const xlsxZip = createZip([
+ {
+ name: "xl/workbook.xml",
+ data: ``,
+ },
+ {
+ name: "xl/_rels/workbook.xml.rels",
+ data: ``,
+ },
+ {
+ name: "xl/worksheets/sheet1.xml",
+ data: `NoRowAttrs
`,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("no-row-attrs.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip));
+ assert.match(result, /### Sheet1/);
+ assert.match(result, /\| NoRowAttrs \|/);
+});
+
+test("readAttachmentText expands odf repeated columns and trims trailing empty cells", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const odsZip = createZip([
+ {
+ name: "content.xml",
+ data: `
+
+
+
+
+
+ Middle
+
+
+
+
+
+ `,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("repeated.ods", "application/vnd.oasis.opendocument.spreadsheet", odsZip));
+ // Should have 3 columns total: 2 leading empty columns + "Middle" column. Trailing 500 empty columns trimmed.
+ assert.match(result, /\|\s*\|\s*\|\s*Middle\s*\|/);
+ assert.doesNotMatch(result, /\| Middle \|(?:\s*\|){5,}/);
+});
+
+test("readAttachmentText rejects odf spreadsheet exceeding output byte budget via repeated cells", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ // Each row has repeated cells with non-empty text, expanding beyond 4 MiB
+ const cellText = "A".repeat(1000);
+ const rowXml = `${cellText}`;
+ // 64 * 1003 bytes ~ 64 KB per row; 70 rows > 4.4 MB (> 4 MiB MAX_ATTACHED_TEXT_BYTES)
+ const rowsXml = rowXml.repeat(70);
+
+ const odsZip = createZip([
+ {
+ name: "content.xml",
+ data: `
+
+
+
+ ${rowsXml}
+
+
+
+ `,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("huge-repeated.ods", "application/vnd.oasis.opendocument.spreadsheet", odsZip));
+ assert.strictEqual(result, null);
+});
+
+test("readAttachmentText rejects xlsx exceeding output byte budget via repeated shared strings", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ const sharedString = "B".repeat(10000);
+ // 500 rows referencing the 10KB shared string -> 5 MB (> 4 MiB MAX_ATTACHED_TEXT_BYTES)
+ let rowsXml = "";
+ for (let r = 1; r <= 500; r++) {
+ rowsXml += `0
`;
+ }
+
+ const xlsxZip = createZip([
+ {
+ name: "xl/sharedStrings.xml",
+ data: `${sharedString}`,
+ },
+ {
+ name: "xl/workbook.xml",
+ data: ``,
+ },
+ {
+ name: "xl/_rels/workbook.xml.rels",
+ data: ``,
+ },
+ {
+ name: "xl/worksheets/sheet1.xml",
+ data: `${rowsXml}`,
+ },
+ ]);
+
+ const result = await readAttachmentText(mockFile("huge-shared-strings.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip));
+ assert.strictEqual(result, null);
+});
+
+test("enforces text byte budget on extracted text byte length", async () => {
+ const {
+ selectTextAttachments,
+ MAX_ATTACHED_TEXT_BYTES,
+ MAX_TOTAL_ATTACHED_TEXT_BYTES,
+ describeTextAttachmentSkip,
+ } = await loadSubject();
+
+ // Compressed file is small, but extracted content expands beyond MAX_ATTACHED_TEXT_BYTES
+ const largeExtractedCandidate = {
+ name: "expanded.docx",
+ mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ content: "x".repeat(MAX_ATTACHED_TEXT_BYTES + 10),
+ size: new TextEncoder().encode("x".repeat(MAX_ATTACHED_TEXT_BYTES + 10)).byteLength,
+ };
+
+ const selOversized = selectTextAttachments([largeExtractedCandidate], { usedBytes: 0, usedSlots: 0 });
+ assert.equal(selOversized.accepted.length, 0);
+ assert.equal(selOversized.tooLarge, 1);
+ assert.equal(selOversized.overBudget, 0);
+ assert.equal(
+ describeTextAttachmentSkip(selOversized),
+ "1 file(s) skipped: files up to 4 MB are supported.",
+ );
+
+ // Extracted content exceeds remaining aggregate budget
+ const moderateExtractedCandidate = {
+ name: "moderate.pdf",
+ mimeType: "application/pdf",
+ content: "x".repeat(1024 * 1024),
+ size: new TextEncoder().encode("x".repeat(1024 * 1024)).byteLength,
+ };
+
+ const selOverBudget = selectTextAttachments([moderateExtractedCandidate], {
+ usedBytes: MAX_TOTAL_ATTACHED_TEXT_BYTES - 512 * 1024,
+ usedSlots: 1,
+ });
+ assert.equal(selOverBudget.accepted.length, 0);
+ assert.equal(selOverBudget.tooLarge, 0);
+ assert.equal(selOverBudget.overBudget, 1);
+ assert.equal(
+ describeTextAttachmentSkip(selOverBudget),
+ "1 file(s) skipped: attachments are limited to 4 MB per message.",
+ );
+});
+
+test("readAttachmentText handles 40,000 unclosed in DOCX in linear time without regex backtracking", async () => {
+ const { readAttachmentText } = await loadSubject();
+ const unclosed = "A".repeat(40_000);
+ const docxZip = createZip([
+ {
+ name: "word/document.xml",
+ data: `${unclosed}`,
+ },
+ ]);
+ const start = performance.now();
+ const result = await readAttachmentText(mockFile("unclosed.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", docxZip));
+ const elapsed = performance.now() - start;
+ assert.ok(elapsed < 2000, `Took ${elapsed}ms, expected linear scaling`);
+ assert.ok(result !== null);
+ assert.ok(result.length > 0);
+});
+
+test("readAttachmentText bounds extreme xlsx cell coordinates like ZZZZZZZZ1 without huge allocation", async () => {
+ const { readAttachmentText } = await loadSubject();
+ const sheetData = `0
`;
+ const xlsxZip = createZip([
+ {
+ name: "xl/sharedStrings.xml",
+ data: `OutOfBounds`,
+ },
+ {
+ name: "xl/workbook.xml",
+ data: ``,
+ },
+ {
+ name: "xl/_rels/workbook.xml.rels",
+ data: ``,
+ },
+ {
+ name: "xl/worksheets/sheet1.xml",
+ data: `${sheetData}`,
+ },
+ ]);
+ const start = performance.now();
+ const result = await readAttachmentText(mockFile("extreme-coord.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip));
+ const elapsed = performance.now() - start;
+ assert.ok(elapsed < 1000, `Took ${elapsed}ms`);
+ assert.strictEqual(result, null);
+});
+
+test("readAttachmentText rejects sparse huge-column XFD XLSX without large memory allocation", async () => {
+ const { readAttachmentText } = await loadSubject();
+ let rowsXml = "";
+ for (let r = 1; r <= 100; r++) {
+ rowsXml += `${r}
`;
+ }
+ const xlsxZip = createZip([
+ {
+ name: "xl/workbook.xml",
+ data: ``,
+ },
+ {
+ name: "xl/_rels/workbook.xml.rels",
+ data: ``,
+ },
+ {
+ name: "xl/worksheets/sheet1.xml",
+ data: `${rowsXml}`,
+ },
+ ]);
+ const start = performance.now();
+ const result = await readAttachmentText(mockFile("sparse-xfd.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxZip));
+ const elapsed = performance.now() - start;
+ assert.ok(elapsed < 1000, `Took ${elapsed}ms`);
+ assert.strictEqual(result, null);
+});
+
+test("readAttachmentText rejects ODF with extreme column repeat counts without allocating huge arrays", async () => {
+ const { readAttachmentText } = await loadSubject();
+ const odsZip = createZip([
+ {
+ name: "content.xml",
+ data: `Repeat`,
+ },
+ ]);
+ const start = performance.now();
+ const result = await readAttachmentText(mockFile("extreme-repeat.ods", "application/vnd.oasis.opendocument.spreadsheet", odsZip));
+ const elapsed = performance.now() - start;
+ assert.ok(elapsed < 500, `Took ${elapsed}ms`);
+ assert.strictEqual(result, null);
+});
+
+test("extractPdfText rejects ObjStm with count exceeding MAX_OBJSTM_OBJECTS or non-monotonic offsets", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ // 1. /N 50000 > MAX_OBJSTM_OBJECTS (2048)
+ const hugeObjStmStream = Buffer.from("10 0 11 100 << /Type /Font >> << /Type /Font >>");
+ const hugeObjStmPdf = Buffer.from(
+ `%PDF-1.4\n1 0 obj\n<< /Type /ObjStm /N 50000 /First 8 /Length ${hugeObjStmStream.length} >>\nstream\n` +
+ hugeObjStmStream.toString("binary") +
+ `\nendstream\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF`
+ );
+ const hugeResult = await readAttachmentText(mockFile("huge-objstm.pdf", "application/pdf", hugeObjStmPdf));
+ assert.strictEqual(hugeResult, null);
+
+ // 2. Non-monotonic offsets in ObjStm
+ // Two objects: obj 10 at offset 50, obj 11 at offset 20 (decreasing)
+ const badOffsetsStream = Buffer.from("10 50 11 20" + " ".repeat(10) + "hello world content stream data");
+ const badOffsetsPdf = Buffer.from(
+ `%PDF-1.4\n1 0 obj\n<< /Type /ObjStm /N 2 /First 11 /Length ${badOffsetsStream.length} >>\nstream\n` +
+ badOffsetsStream.toString("binary") +
+ `\nendstream\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF`
+ );
+ const badOffsetsResult = await readAttachmentText(mockFile("bad-offsets.pdf", "application/pdf", badOffsetsPdf));
+ assert.strictEqual(badOffsetsResult, null);
+});
+
+test("readAttachmentText exhibits parity between extension and extensionless document files", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ // PDF
+ const pdfBuf = createPdf({ text: "(Parity Test PDF) Tj", withToUnicode: false, useFlate: true });
+ const withExtPdf = await readAttachmentText(mockFile("report.pdf", "application/pdf", pdfBuf));
+ const noExtPdf = await readAttachmentText(mockFile("report", "", pdfBuf));
+ assert.equal(withExtPdf, "Parity Test PDF");
+ assert.equal(noExtPdf, "Parity Test PDF");
+
+ // DOCX
+ const docxZip = createZip([
+ {
+ name: "word/document.xml",
+ data: `Parity Test DOCX`,
+ },
+ ]);
+ const withExtDocx = await readAttachmentText(mockFile("report.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", docxZip));
+ const noExtDocx = await readAttachmentText(mockFile("report", "", docxZip));
+ assert.equal(withExtDocx, "Parity Test DOCX");
+ assert.equal(noExtDocx, "Parity Test DOCX");
+});
+
+test("isImageAttachmentFile excludes undecodable HEIC/HEIF files while accepting supported images", async () => {
+ const { isImageAttachmentFile, inferImageMimeType } = await loadSubject();
+
+ assert.equal(isImageAttachmentFile(mockFile("photo.heic", "image/heic", "x")), false);
+ assert.equal(isImageAttachmentFile(mockFile("photo.heif", "image/heif", "x")), false);
+ assert.equal(isImageAttachmentFile(mockFile("burst.heic", "image/heic-sequence", "x")), false);
+ assert.equal(isImageAttachmentFile(mockFile("photo.heic", "application/octet-stream", "x")), false);
+ assert.equal(isImageAttachmentFile(mockFile("photo.png", "image/png", "x")), true);
+ assert.equal(isImageAttachmentFile(mockFile("photo.png", "application/octet-stream", "x")), true);
+ assert.equal(inferImageMimeType(mockFile("photo.png", "application/octet-stream", "x")), "image/png");
+});
+
+test("readAttachmentText extracts ODF inline text:span without spaces and escapes table pipes once", async () => {
+ const { readAttachmentText } = await loadSubject();
+ const odtZip = createZip([
+ {
+ name: "content.xml",
+ data:
+ `` +
+ `` +
+ `Unbroken` +
+ `` +
+ `` +
+ `A|B` +
+ `Para 1Para 2` +
+ `` +
+ `` +
+ ``,
+ },
+ ]);
+ const result = await readAttachmentText(
+ mockFile("table.odt", "application/vnd.oasis.opendocument.text", odtZip),
+ );
+ assert.ok(result.includes("Unbroken"), `Expected concatenated span 'Unbroken', got: ${result}`);
+ assert.ok(result.includes("| A\\|B | Para 1 Para 2 |"), `Expected single pipe escape and space-joined cell paragraphs, got: ${result}`);
+ assert.ok(!result.includes("\\\\|"), `Expected no double-escaped pipe, got: ${result}`);
+});
+
+test("readAttachmentText extracts .doc when 1Table is stored in the OLE2 mini-stream (< 4096 bytes)", async () => {
+ const { readAttachmentText } = await loadSubject();
+ const text = "MiniStream Word 97 Table";
+ const sectorSize = 512;
+ const miniSectorSize = 64;
+
+ const textBuf = Buffer.from(text, "utf16le");
+ // WordDocument >= 4096 bytes so it lives in regular sectors (8 sectors = 4096 bytes)
+ const wordDocBuf = Buffer.alloc(4096);
+ wordDocBuf.writeUInt16LE(0xA5EC, 0);
+ wordDocBuf.writeUInt16LE(0x0200, 0x000A); // fWhichTblStm = 1 (1Table)
+ textBuf.copy(wordDocBuf, 0x200);
+
+ const pcdBuf = Buffer.alloc(8);
+ pcdBuf.writeUInt32LE(0x0200, 2);
+ const clxPart = Buffer.alloc(1 + 4 + 4 * 2 + 8);
+ clxPart[0] = 2;
+ clxPart.writeUInt32LE(4 * 2 + 8, 1);
+ clxPart.writeUInt32LE(0, 5);
+ clxPart.writeUInt32LE(text.length, 9);
+ pcdBuf.copy(clxPart, 13);
+
+ wordDocBuf.writeUInt32LE(0, 0x01A2); // fcClx
+ wordDocBuf.writeUInt32LE(clxPart.length, 0x01A6); // lcbClx
+
+ // Place 1Table at mini-sector 2 (offset 128 inside Root Entry's mini-stream) so reading regular sector 2 would fail
+ const miniStreamBuf = Buffer.alloc(sectorSize);
+ clxPart.copy(miniStreamBuf, 2 * miniSectorSize);
+
+ const miniFatBuf = Buffer.alloc(sectorSize, 0xFF);
+ miniFatBuf.writeInt32LE(-2, 2 * 4); // mini-sector 2 -> ENDOFCHAIN
+
+ // Sector layout:
+ // 0: FAT
+ // 1: Directory
+ // 2..9: WordDocument (8 sectors)
+ // 10: MiniFAT
+ // 11: MiniStream (Root Entry stream)
+ const dirBuf = Buffer.alloc(sectorSize);
+ function writeDirEntry(offset, name, type, startSect, size, childId = -1, leftId = -1, rightId = -1) {
+ const nameBuf = Buffer.from(name, "utf16le");
+ nameBuf.copy(dirBuf, offset);
+ dirBuf.writeUInt16LE(nameBuf.length + 2, offset + 64);
+ dirBuf.writeUInt8(type, offset + 66);
+ dirBuf.writeUInt8(1, offset + 67);
+ dirBuf.writeInt32LE(leftId, offset + 68);
+ dirBuf.writeInt32LE(rightId, offset + 72);
+ dirBuf.writeInt32LE(childId, offset + 76);
+ dirBuf.writeInt32LE(startSect, offset + 116);
+ dirBuf.writeUInt32LE(size, offset + 120);
+ }
+ writeDirEntry(0, "Root Entry", 5, 11, miniStreamBuf.length, 1);
+ writeDirEntry(128, "WordDocument", 2, 2, wordDocBuf.length, -1, -1, 2);
+ writeDirEntry(256, "1Table", 2, 2, clxPart.length, -1, -1, -1); // startSect = mini-sector 2, size < 4096
+
+ const fatBuf = Buffer.alloc(sectorSize, 0xFF);
+ fatBuf.writeInt32LE(-3, 0 * 4); // FAT
+ fatBuf.writeInt32LE(-2, 1 * 4); // Dir
+ for (let i = 0; i < 8; i++) {
+ fatBuf.writeInt32LE(i === 7 ? -2 : 2 + i + 1, (2 + i) * 4);
+ }
+ fatBuf.writeInt32LE(-2, 10 * 4); // MiniFAT
+ fatBuf.writeInt32LE(-2, 11 * 4); // MiniStream
+
+ const header = Buffer.alloc(512);
+ header.set([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1], 0);
+ header.writeUInt16LE(0xFFFE, 28);
+ header.writeUInt16LE(9, 30);
+ header.writeUInt16LE(6, 32);
+ header.writeUInt32LE(1, 44);
+ header.writeInt32LE(1, 48);
+ header.writeUInt32LE(0x1000, 56);
+ header.writeInt32LE(10, 60); // firstMiniFatSector = 10
+ header.writeUInt32LE(1, 64); // numMiniFatSectors = 1
+ header.writeInt32LE(-2, 68);
+ header.writeUInt32LE(0, 72);
+ header.writeInt32LE(0, 76);
+ for (let i = 1; i < 109; i++) {
+ header.writeInt32LE(-1, 76 + i * 4);
+ }
+
+ const oleBuf = Buffer.concat([header, fatBuf, dirBuf, wordDocBuf, miniFatBuf, miniStreamBuf]);
+ const result = await readAttachmentText(mockFile("ministream.doc", "application/msword", oleBuf));
+ assert.equal(result, text);
+});
+
+test("readAttachmentText bounds hostile unclosed XML tags in XLSX and EPUB and hostile PDF digit/string streams in linear time", async () => {
+ const { readAttachmentText } = await loadSubject();
+
+ // 1. workbook.xml.rels filled with unclosed ` + `` },
+ ]);
+ const t0 = performance.now();
+ await readAttachmentText(
+ mockFile("hostile-rels.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlsxRelsZip),
+ );
+ const relsMs = performance.now() - t0;
+ assert.ok(relsMs < 250, `Expected linear scan on unclosed ` + `` +
+ `- ` },
+ { name: "OEBPS/content.opf", data: unclosedOpf },
+ ]);
+ const t2 = performance.now();
+ await readAttachmentText(mockFile("hostile.epub", "application/epub+zip", epubZip));
+ const epubMs = performance.now() - t2;
+ assert.ok(epubMs < 250, `Expected linear scan on unclosed EPUB
- >\nstream\nBT (Fast) Tj ET\nendstream\nendobj\n`, "latin1");
+ const t3 = performance.now();
+ const pdfDigitRes = await readAttachmentText(mockFile("digits.pdf", "application/pdf", hostilePdfDigits));
+ const pdfDigitMs = performance.now() - t3;
+ assert.equal(pdfDigitRes, "Fast");
+ assert.ok(pdfDigitMs < 250, `Expected linear scan on 100 KB PDF digit run (< 250ms), took ${pdfDigitMs.toFixed(1)}ms`);
+
+ // 5. PDF text stream BT followed by 200 KB of repeated unclosed escaped strings
+ const unclosedStreamBody = `BT (Valid) Tj ` + `(abc\\(def`.repeat(23_000) + `\nET`;
+ const hostilePdfStream = Buffer.from(
+ `%PDF-1.4\n1 0 obj\n<< /Length ${unclosedStreamBody.length} >>\nstream\n${unclosedStreamBody}\nendstream\nendobj\n`,
+ "latin1",
+ );
+ const t4 = performance.now();
+ const pdfStreamRes = await readAttachmentText(mockFile("unclosed-stream.pdf", "application/pdf", hostilePdfStream));
+ const pdfStreamMs = performance.now() - t4;
+ assert.equal(pdfStreamRes, "Valid");
+ assert.ok(pdfStreamMs < 250, `Expected linear scan on 200 KB unclosed PDF strings (< 250ms), took ${pdfStreamMs.toFixed(1)}ms`);
+});
diff --git a/lib/chat-attachments.ts b/lib/chat-attachments.ts
index 559814685..94e7b05a6 100644
--- a/lib/chat-attachments.ts
+++ b/lib/chat-attachments.ts
@@ -27,8 +27,10 @@ export interface AttachedTextFileData {
mimeType: string;
content: string;
size: number;
+ uploadId?: string;
}
+/** Extracts lowercased file extension without leading dot. */
function getFileExtension(name: string): string {
return name.toLowerCase().replace(/\\/g, "/").split("/").pop()?.split(".").pop() ?? "";
}
@@ -86,18 +88,87 @@ export function selectTextAttachments(
return { accepted, tooLarge, overBudget };
}
+/** Banner text for a batch that produced no usable attachments. */
+export function describeTextAttachmentSkip(
+ selection: Pick, "tooLarge" | "overBudget">,
+): string | null {
+ if (selection.tooLarge > 0) {
+ return `${selection.tooLarge} file(s) skipped: files up to ${formatAttachmentBytes(MAX_ATTACHED_TEXT_BYTES)} are supported.`;
+ }
+ if (selection.overBudget > 0) {
+ return `${selection.overBudget} file(s) skipped: attachments are limited to ${formatAttachmentBytes(MAX_TOTAL_ATTACHED_TEXT_BYTES)} per message.`;
+ }
+ return null;
+}
+
+/** Checks whether file is candidate for text attachment by MIME type or extension. */
export function isTextAttachmentFile(file: Pick): boolean {
return file.type === "text/plain"
|| file.type === "text/markdown"
|| TEXT_FILE_EXTENSIONS[getFileExtension(file.name)] === true;
}
+const MARKDOWN_EXTENSIONS: Record = {
+ md: true,
+ markdown: true,
+ mdx: true,
+ docx: true,
+ xlsx: true,
+ pptx: true,
+ odt: true,
+ ods: true,
+ odp: true,
+ epub: true,
+};
+
+const RASTER_IMAGE_EXTENSIONS: Record = {
+ png: "image/png",
+ jpg: "image/jpeg",
+ jpeg: "image/jpeg",
+ gif: "image/gif",
+ webp: "image/webp",
+ bmp: "image/bmp",
+ avif: "image/avif",
+ ico: "image/x-icon",
+};
+
+const UNSUPPORTED_INLINE_IMAGE_MIME_TYPES: Record = {
+ "image/heic": true,
+ "image/heif": true,
+ "image/heic-sequence": true,
+ "image/heif-sequence": true,
+};
+
+/** Checks whether file is candidate for image attachment by MIME type or extension. */
+export function isImageAttachmentFile(file: Pick): boolean {
+ const mime = file.type?.toLowerCase() ?? "";
+ if (mime.startsWith("image/")) {
+ return !UNSUPPORTED_INLINE_IMAGE_MIME_TYPES[mime];
+ }
+ if (!mime || mime === "application/octet-stream") {
+ const ext = getFileExtension(file.name);
+ return Boolean(RASTER_IMAGE_EXTENSIONS[ext]);
+ }
+ return false;
+}
+
+/** Determines MIME type for image file from type property or extension fallback. */
+export function inferImageMimeType(file: Pick): string {
+ if (file.type && file.type.startsWith("image/")) {
+ return file.type;
+ }
+ const ext = getFileExtension(file.name);
+ return RASTER_IMAGE_EXTENSIONS[ext] || file.type || "application/octet-stream";
+}
+
+/** Maps file extension to composer markdown language identifier. */
function languageForFile(name: string): string {
const extension = getFileExtension(name);
- if (extension === "md" || extension === "markdown" || extension === "mdx") return "markdown";
+ if (MARKDOWN_EXTENSIONS[extension]) return "markdown";
return "text";
}
+/** Computes markdown code fence backtick count that safely encloses content. */
function fenceForContent(content: string): string {
const longestRun = content.match(/`+/g)?.reduce((longest, run) => Math.max(longest, run.length), 0) ?? 0;
return "`".repeat(Math.max(3, longestRun + 1));
@@ -115,3 +186,2242 @@ export function composeMessageWithTextAttachments(
});
return [message.trim(), ...blocks].filter(Boolean).join("\n\n");
}
+
+/** Decodes XML named and numeric character entities in a single pass. */
+export function decodeXmlEntities(str: string): string {
+ const named: Record = {
+ amp: "&",
+ lt: "<",
+ gt: ">",
+ quot: '"',
+ apos: "'",
+ nbsp: "\u00a0",
+ };
+ return str.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|([a-zA-Z]+));/g, (whole, dec, hex, name) => {
+ if (name) return named[name] ?? whole;
+ const cp = dec ? parseInt(dec, 10) : parseInt(hex, 16);
+ return cp > 0 && cp <= 0x10ffff && (cp < 0xd800 || cp > 0xdfff)
+ ? String.fromCodePoint(cp)
+ : whole;
+ });
+}
+
+export const MAX_XML_TAGS = 250_000;
+export const MAX_TABLE_COLS = 512;
+export const MAX_TABLE_ROWS = 10_000;
+export const MAX_TABLE_CELLS = 100_000;
+export const MAX_PDF_OBJECTS = 8_192;
+export const MAX_OBJSTM_OBJECTS = 2_048;
+export const MAX_PDF_STREAM_TOKENS = 200_000;
+
+export const MAX_DECOMPRESSED_BYTES = MAX_TOTAL_ATTACHED_TEXT_BYTES * 4;
+
+const oversizedDocumentFiles = new WeakSet