/** Programmatic fixtures for the document tests. Nothing here is used by production code. */ import { strToU8, zipSync } from 'fflate'; const latin1 = (text: string): Uint8Array => Uint8Array.from(text, (ch) => ch.charCodeAt(0) & 0xff); function pdfString(text: string): string { return `(${text.replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)')})`; } export interface PdfPage { /** Lines of text, drawn top-down at 12pt with 14pt leading. `''` leaves a paragraph gap. */ lines?: string[]; /** Raw content stream, used instead of `lines`. */ raw?: string; } export interface PdfOptions { title?: string; /** Adds a standard security handler whose user password is not empty. */ encrypted?: boolean; } /** Builds a small but valid PDF (Helvetica, one content stream per page). */ export function buildPdf(pages: PdfPage[], options: PdfOptions = {}): Uint8Array { const objects: string[] = []; const add = (body: string): number => { objects.push(body); return objects.length; }; const catalogId = add(''); const pagesId = add(''); const fontId = add('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>'); const pageIds: number[] = []; for (const page of pages) { let stream = page.raw ?? ''; if (page.raw === undefined && page.lines && page.lines.length > 0) { const ops: string[] = ['BT', '/F1 12 Tf', '14 TL', '72 720 Td']; for (const line of page.lines) { if (line === '') ops.push('0 -14 Td'); else ops.push(`${pdfString(line)} Tj`, 'T*'); } ops.push('ET'); stream = ops.join('\n'); } const contentId = add(`<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`); pageIds.push( add( `<< /Type /Page /Parent ${pagesId} 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 ${fontId} 0 R >> >> /Contents ${contentId} 0 R >>`, ), ); } objects[catalogId - 1] = `<< /Type /Catalog /Pages ${pagesId} 0 R >>`; objects[pagesId - 1] = `<< /Type /Pages /Count ${pageIds.length} /Kids [${pageIds.map((id) => `${id} 0 R`).join(' ')}] >>`; let infoId = 0; if (options.title !== undefined && !options.encrypted) infoId = add(`<< /Title ${pdfString(options.title)} /Producer (study-desk tests) >>`); let encryptId = 0; if (options.encrypted) { const o = 'a1'.repeat(32); const u = 'b2'.repeat(32); encryptId = add(`<< /Filter /Standard /V 1 /R 2 /Length 40 /O <${o}> /U <${u}> /P -44 >>`); } let out = '%PDF-1.4\n%\xE2\xE3\xCF\xD3\n'; const offsets: number[] = []; objects.forEach((body, index) => { offsets.push(out.length); out += `${index + 1} 0 obj\n${body}\nendobj\n`; }); const xrefOffset = out.length; out += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`; for (const offset of offsets) out += `${String(offset).padStart(10, '0')} 00000 n \n`; out += `trailer\n<< /Size ${objects.length + 1} /Root ${catalogId} 0 R`; if (infoId) out += ` /Info ${infoId} 0 R`; if (encryptId) out += ` /Encrypt ${encryptId} 0 R /ID [<0123456789abcdef0123456789abcdef> <0123456789abcdef0123456789abcdef>]`; out += ` >>\nstartxref\n${xrefOffset}\n%%EOF\n`; return latin1(out); } const xmlEscape = (text: string): string => text.replace(/&/g, '&').replace(//g, '>'); const XML_HEADER = ''; function coreProps(title: string | undefined): string { return `${XML_HEADER}${ title === undefined ? '' : `${xmlEscape(title)}` }Tests`; } // --------------------------------------------------------------------------- // DOCX // --------------------------------------------------------------------------- export type DocxBlock = | { type: 'heading'; level: number; text: string } | { type: 'p'; text: string; bold?: string } | { type: 'bullet'; text: string; level?: number } | { type: 'number'; text: string; level?: number } | { type: 'table'; rows: string[][] } | { type: 'image' }; const W_NS = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'; function docxRun(text: string, bold = false): string { return `${bold ? '' : ''}${xmlEscape(text)}`; } function docxBlock(block: DocxBlock): string { switch (block.type) { case 'heading': return `${docxRun(block.text)}`; case 'p': return `${block.bold ? docxRun(block.bold, true) : ''}${docxRun(block.text)}`; case 'bullet': case 'number': return `${docxRun(block.text)}`; case 'table': return `${block.rows .map((row) => `${row.map((cell) => `${docxRun(cell)}`).join('')}`) .join('')}`; case 'image': return ''; } } /** Builds a minimal DOCX with headings (style ids Heading1..6), lists, tables. */ export function buildDocx(blocks: DocxBlock[], options: { title?: string; extraFiles?: Record } = {}): Uint8Array { const levels = (format: string) => [0, 1, 2].map((lvl) => ``).join(''); const files: Record = { '[Content_Types].xml': strToU8( `${XML_HEADER}`, ), '_rels/.rels': strToU8( `${XML_HEADER}`, ), 'word/_rels/document.xml.rels': strToU8( `${XML_HEADER}`, ), 'word/numbering.xml': strToU8( `${XML_HEADER}${levels('bullet')}${levels('decimal')}`, ), 'word/document.xml': strToU8(`${XML_HEADER}${blocks.map(docxBlock).join('')}`), 'docProps/core.xml': strToU8(coreProps(options.title)), ...options.extraFiles, }; return zipSync(files); } // --------------------------------------------------------------------------- // PPTX // --------------------------------------------------------------------------- export interface PptxSlide { /** File number: the slide is stored as ppt/slides/slide.xml regardless of its position. */ file: number; title?: string; /** Body placeholder paragraphs. */ bullets?: Array; /** A free text box (not a placeholder). */ textBox?: string[]; table?: string[][]; notes?: string[]; } const P_NS = 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"'; function aParagraph(text: string, level = 0): string { return `${level ? `` : ''}${xmlEscape(text)}`; } function shape(id: number, placeholder: string | null, paragraphs: string): string { const ph = placeholder === null ? '' : placeholder === 'body' ? '' : ``; return `${ph}${paragraphs}`; } function slideXml(slide: PptxSlide): string { const shapes: string[] = []; let id = 2; if (slide.title !== undefined) shapes.push(shape(id++, 'title', aParagraph(slide.title))); if (slide.bullets) { shapes.push( shape(id++, 'body', slide.bullets.map((b) => (typeof b === 'string' ? aParagraph(b) : aParagraph(b.text, b.level))).join('')), ); } if (slide.textBox) shapes.push(shape(id++, null, slide.textBox.map((line) => aParagraph(line)).join(''))); if (slide.table) { const rows = slide.table .map((row) => `${row.map((cell) => `${aParagraph(cell)}`).join('')}`) .join(''); shapes.push( `${rows}`, ); } // Every slide also carries a slide-number placeholder, which must be ignored. shapes.push(shape(id++, 'sldNum', '9')); return `${XML_HEADER}${shapes.join('')}`; } function notesXml(lines: string[]): string { return `${XML_HEADER}${shape( 2, 'sldImg', '', )}${shape(3, 'body', lines.map((line) => aParagraph(line)).join(''))}${shape(4, 'sldNum', aParagraph('9'))}`; } /** Builds a minimal PPTX. Slides appear in the order given, whatever their file numbers. */ export function buildPptx(slides: PptxSlide[], options: { title?: string } = {}): Uint8Array { const REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'; const files: Record = { '[Content_Types].xml': strToU8( `${XML_HEADER}`, ), '_rels/.rels': strToU8( `${XML_HEADER}`, ), 'docProps/core.xml': strToU8(coreProps(options.title)), 'ppt/presentation.xml': strToU8( `${XML_HEADER}${slides .map((slide, index) => ``) .join('')}`, ), 'ppt/_rels/presentation.xml.rels': strToU8( `${XML_HEADER}${slides .map((slide) => ``) .join('')}`, ), }; for (const slide of slides) { files[`ppt/slides/slide${slide.file}.xml`] = strToU8(slideXml(slide)); if (slide.notes) { files[`ppt/slides/_rels/slide${slide.file}.xml.rels`] = strToU8( `${XML_HEADER}`, ); files[`ppt/notesSlides/notesSlide${slide.file}.xml`] = strToU8(notesXml(slide.notes)); } } return zipSync(files); } // --------------------------------------------------------------------------- // Misc // --------------------------------------------------------------------------- /** PNG signature plus an IHDR chunk header: enough for signature sniffing. */ export const TINY_PNG = Uint8Array.from([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, ]); export const TINY_JPEG = Uint8Array.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01]); export const TINY_GIF = Uint8Array.from([...'GIF89a'].map((ch) => ch.charCodeAt(0)).concat([1, 0, 1, 0, 0, 0, 0])); export const TINY_WEBP = Uint8Array.from([...'RIFF'].map((c) => c.charCodeAt(0)).concat([4, 0, 0, 0], [...'WEBP'].map((c) => c.charCodeAt(0)))); /** A stored zip whose central directory claims a tiny size for a highly compressible entry. */ export function buildLyingZip(name: string, realBytes: number): Uint8Array { const zip = zipSync({ [name]: new Uint8Array(realBytes), 'word/document.xml': strToU8('') }, { level: 9 }); // Patch the uncompressed size of `name` in its central directory record to 16 bytes. const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength); for (let i = 0; i + 46 < zip.length; i++) { if (view.getUint32(i, true) !== 0x02014b50) continue; const nameLen = view.getUint16(i + 28, true); const entryName = new TextDecoder().decode(zip.subarray(i + 46, i + 46 + nameLen)); if (entryName === name) view.setUint32(i + 24, 16, true); } return zip; }