Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FilePreviewPanel.test.ts

749 lines36.8 KB

1import JSZip from "jszip";
2import { openRtf, openNotebook, openDocument, openEpub } from "./extendedDocumentPreview";
3import type { ScopedThreadRef } from "@t3tools/contracts";
4import { ProjectReadFileError } from "@t3tools/contracts";
5import * as Schema from "effect/Schema";
6import { describe, expect, it, vi } from "vite-plus/test";
7​
8import { promptFileCommentEntries, remapFileCommentAnnotations } from "./fileCommentAnnotations";
9import {
10 filePreviewReadErrorMessage,
11 isMarkdownPreviewFile,
12 resolveFilePreviewPath,
13 shouldShowFileExplorer,
14 workspaceAssetResource,
15} from "./filePreviewMode";
16​
17const decodeReadError = Schema.decodeSync(ProjectReadFileError);
18​
19describe("file preview read errors", () => {
20 // regression: #15628 read errors from servers without attempted paths keep their own message
21 it("preserves the public message from older servers", () => {
22 const error = decodeReadError({
23 _tag: "ProjectReadFileError",
24 message: "Legacy file read failure.",
25 });
26 expect(filePreviewReadErrorMessage(error)).toBe("Legacy file read failure.");
27 });
28});
29​
30describe("file comment annotations", () => {
31 it("keeps an annotation range attached when Pierre remaps its anchor line", () => {
32 expect(
33 remapFileCommentAnnotations([
34 {
35 lineNumber: 20,
36 metadata: {
37 entries: [
38 {
39 id: "comment-1",
40 kind: "comment",
41 startLine: 7,
42 endLine: 16,
43 text: "Keep this guarded.",
44 },
45 ],
46 },
47 },
48 ]),
49 ).toEqual([
50 {
51 lineNumber: 20,
52 metadata: {
53 entries: [
54 {
55 id: "comment-1",
56 kind: "comment",
57 startLine: 11,
58 endLine: 20,
59 text: "Keep this guarded.",
60 },
61 ],
62 },
63 },
64 ]);
65 });
66​
67 it("shows only drafts and comments still in the prompt", () => {
68 const entry = (id: string, kind: "draft" | "comment") => ({
69 id,
70 kind,
71 startLine: 3,
72 endLine: 3,
73 text: "",
74 });
75 expect(
76 promptFileCommentEntries(
77 [entry("sent", "comment"), entry("new", "draft"), entry("kept", "comment")],
78 new Set(["kept"]),
79 ),
80 ).toEqual([entry("new", "draft"), entry("kept", "comment")]);
81 });
82});
83​
84describe("isMarkdownPreviewFile", () => {
85 it("recognizes markdown and MDX files case-insensitively", () => {
86 expect(isMarkdownPreviewFile("README.md")).toBe(true);
87 expect(isMarkdownPreviewFile("docs/guide.MDX")).toBe(true);
88 expect(isMarkdownPreviewFile("docs/guide.MARKDOWN")).toBe(true);
89 expect(isMarkdownPreviewFile("docs/guide.mdown")).toBe(true);
90 expect(isMarkdownPreviewFile("docs/guide.mkd")).toBe(true);
91 });
92});
93​
94describe("resolveFilePreviewPath", () => {
95 it.each([
96 ["/repo/project", null],
97 ["/repo/project/", null],
98 [".", null],
99 [null, null],
100 ["/repo/project/src", "/repo/project/src"],
101 ["/repo/project/src/main.ts", "/repo/project/src/main.ts"],
102 ["src/main.ts", "src/main.ts"],
103 ["/repo/project-other", "/repo/project-other"],
104 ])("opens %s in the appropriate workspace surface", (path, expected) => {
105 const relativePath = resolveFilePreviewPath(path, "/repo/project");
106 expect(relativePath).toBe(expected);
107 if (expected === null) {
108 expect(
109 shouldShowFileExplorer({ relativePath, explorerOpen: false, attachmentOpen: false }),
110 ).toBe(true);
111 }
112 });
113});
114​
115describe("workspaceAssetResource", () => {
116 const input = {
117 kind: "workspace-file" as const,
118 threadRef: {
119 environmentId: "env" as ScopedThreadRef["environmentId"],
120 threadId: "thread-1" as ScopedThreadRef["threadId"],
121 },
122 workspaceRoot: "/repo",
123 absolutePath: "/repo/docs/index.html",
124 };
125​
126 // regression: #21067 images outside the workspace load through the host media resource
127 it("serves a file outside the workspace as host media and keeps workspace files on workspace access", () => {
128 expect(
129 workspaceAssetResource({ ...input, absolutePath: "/tmp/screenshots/shot.png", draft: false }),
130 ).toEqual({ _tag: "media-file", threadId: "thread-1", path: "/tmp/screenshots/shot.png" });
131 expect(workspaceAssetResource({ ...input, draft: false })).toEqual({
132 _tag: "workspace-file",
133 threadId: "thread-1",
134 path: "/repo/docs/index.html",
135 });
136 });
137​
138 it("names the workspace root for a draft, which the server cannot resolve from a thread", () => {
139 expect(workspaceAssetResource({ ...input, draft: true })).toEqual({
140 _tag: "draft-workspace-file",
141 cwd: "/repo",
142 path: "/repo/docs/index.html",
143 });
144 expect(
145 workspaceAssetResource({ ...input, absolutePath: "/tmp/screenshots/shot.png", draft: true }),
146 ).toEqual({ _tag: "draft-workspace-file", cwd: "/repo", path: "/tmp/screenshots/shot.png" });
147 });
148});
149​
150describe("document preview contents", () => {
151 const bytes = (text: string) => new TextEncoder().encode(text).buffer;
152​
153 it.each([
154 ["control symbols", String.raw`{\rtf1 Jean\_Luc\-X\~Y}`, "Jean\u2011Luc\u00adX\u00a0Y"],
155 [
156 "named spaces, joiners and direction marks",
157 String.raw`{\rtf1 A\tab B\emspace C\enspace D\qmspace E\zwj F\zwnj G\zwbo H\ltrmark I\rtlmark J}`,
158 "A\tB\u2003C\u2002D\u2005E\u200dF\u200cG\u200bH\u200eI\u200fJ",
159 ],
160 ["a Unicode fallback", String.raw`{\rtf1 Jean\u8209\_Luc}`, "Jean\u2011Luc"],
161 [
162 "visible text around hidden character formatting",
163 String.raw`{\rtf1 A{\v hidden{\v0 B}hidden}C\v hidden\v0 D\v hidden\plain E}`,
164 "ABCDE",
165 ],
166 ["a tracked replacement", String.raw`{\rtf1 aaa{\deleted bbb}{\revised BBB}ccc}`, "aaaBBBccc"],
167 [
168 "text after a deletion reset",
169 String.raw`{\rtf1 A\deleted old\deleted0 B\deleted old\plain C}`,
170 "ABC",
171 ],
172 [
173 "text around a deleted Unicode span",
174 String.raw`{\rtf1 A{\deleted\uc1\u945\deleted0 old}B}`,
175 "AB",
176 ],
177 ])("keeps the text of %s", (_name, source, expected) => {
178 const result = openRtf(bytes(source));
179 if (result.type !== "document") throw new Error("Expected document");
180 expect(result.pages[0]!.html.replaceAll(/<[^>]*>/g, "")).toBe(expected);
181 });
182​
183 it.each(["?", String.raw`\'3f`, String.raw`\\`])(
184 "consumes skipped rich text Unicode fallback %s",
185 (fallback) => {
186 const result = openRtf(bytes(String.raw`{\rtf1{\*\unknown\u945` + fallback + "}Hello}"));
187 if (result.type !== "document") throw new Error("Expected document");
188 expect(result.pages[0]!.html).toBe("<p>Hello</p>");
189 },
190 );
191​
192 it("bounds EPUB markup made entirely of empty allowed elements", async () => {
193 const archive = new JSZip()
194 .file(
195 "META-INF/container.xml",
196 '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>',
197 )
198 .file(
199 "book.opf",
200 '<package><manifest><item id="a" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine>' +
201 '<itemref idref="a"/>'.repeat(30) +
202 "</spine></package>",
203 )
204 .file("chapter.xhtml", "<html><body>" + "<figcaption/>".repeat(30_000) + "</body></html>");
205 await expect(openEpub(archive)).rejects.toMatchObject({ code: "rendered-too-large" });
206 });
207​
208 it("decodes rich text formatting and Unicode without showing hidden destinations", () => {
209 const result = openRtf(
210 bytes(
211 String.raw`{\rtf1\ansi{\fonttbl{\f0 Hidden font;}}Hello \b bold\b0\par Unicode: \u945?{\*\unknown hidden\_\emspace\zwj}{\field{\*\fldinst HYPERLINK "https://example.com"}{\fldrslt visible}}}`,
212 ),
213 );
214 expect(result.type).toBe("document");
215 if (result.type !== "document") throw new Error("Expected document");
216 const html = result.pages[0]!.html;
217 expect(html.replaceAll(/<[^>]*>/g, "")).toBe("Hello boldUnicode: αvisible");
218 expect(html).toContain("<strong>");
219 expect(html).not.toContain("https:");
220 const styled = openRtf(
221 bytes(
222 "{\\rtf1\\ansi\\b \\uc0\\u55357 \\u56960 Launch\\b0 \\i\\uc1\\u-10187?\\u-8904?\\i0}",
223 ),
224 );
225 if (styled.type !== "document") throw new Error("Expected document");
226 expect(styled.pages[0]!.html).toBe("<p><strong>🚀 Launch</strong> <em>𝔸</em></p>");
227 const fallbacks = openRtf(bytes("{\\rtf1\\b\\uc1\\u-10179\\_\\uc0\\u-8576 }"));
228 if (fallbacks.type !== "document") throw new Error("Expected document");
229 expect(fallbacks.pages[0]!.html).toBe("<p><strong>🚀</strong></p>");
230 const escapedBreak = openRtf(bytes("{\\rtf1\\b A\\u66\\\nC\\par D}"));
231 if (escapedBreak.type !== "document") throw new Error("Expected document");
232 expect(escapedBreak.pages[0]!.html).toBe("<p><strong>ABC</strong><br><strong>D</strong></p>");
233 });
234​
235 it("breaks lines at the paragraph and line breaks TextEdit writes", () => {
236 const html = (rtf: string) => {
237 const result = openRtf(bytes(rtf));
238 if (result.type !== "document") throw new Error("Expected document");
239 return result.pages.map((page) => page.html);
240 };
241 const textEdit = String.raw`{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}
242\pard\f0\fs24 \cf0 First\
243Second\
245Third}`;
246 const expected = html(
247 String.raw`{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\pard\f0\fs24 \cf0 First\par Second\par \par Third}`,
248 );
249 expect(html(textEdit)).toEqual(expected);
250 expect(html(textEdit.replaceAll("\n", "\r\n"))).toEqual(expected);
251 const lineBreak = html(String.raw`{\rtf1\ansi First line\line Second line}`);
252 expect(lineBreak).toEqual(["<p>First line<br>Second line</p>"]);
253 expect(html(String.raw`{\rtf1\ansi{\v\line\line\line}First line\line Second line}`)).toEqual(
254 lineBreak,
255 );
256 expect(html(String.raw`{\rtf1\ansi First line\uc0\u8232 Second line}`)).toEqual(lineBreak);
257 expect(html(String.raw`{\rtf1\ansi First line\u8232?Second line{\deleted\u8232?}}`)).toEqual(
258 lineBreak,
259 );
260 });
261​
262 it("preserves rich text page breaks and formatting without splitting hidden destinations", () => {
263 const result = openRtf(
264 bytes(String.raw`{\rtf1\b First\page Second\b0{\*\unknown \page hidden}\page Third\page}`),
265 );
266 if (result.type !== "document") throw new Error("Expected document");
267 expect(result.navigation).toBe("page");
268 expect(result.pages.map((page) => page.html)).toEqual([
269 "<p><strong>First</strong></p>",
270 "<p><strong>Second</strong></p>",
271 "<p>Third</p>",
272 ]);
273 expect(() => openRtf(bytes(String.raw`{\rtf1 ` + String.raw`\page`.repeat(501) + "}"))).toThrow(
274 expect.objectContaining({ code: "rtf-too-many-pages" }),
275 );
276 });
277​
278 it("starts a new line at rich text section and column breaks", () => {
279 const result = openRtf(
280 bytes(
281 String.raw`{\rtf1\ansi\sectd\cols2\pard North quota: 120\column South quota: 240\page East quota: 360\sect\sectd\pard West quota: 480\par}`,
282 ),
283 );
284 if (result.type !== "document") throw new Error("Expected document");
285 expect(result.pages.map((page) => page.html)).toEqual([
286 "<p>North quota: 120<br>South quota: 240</p>",
287 "<p>East quota: 360<br>West quota: 480<br></p>",
288 ]);
289 const written = openRtf(
290 bytes(String.raw`{\rtf1\ansi First\par\sect\sectd Second\par\column Third\page\sect Fourth}`),
291 );
292 if (written.type !== "document") throw new Error("Expected document");
293 expect(written.pages.map((page) => page.html)).toEqual([
294 "<p>First<br>Second<br>Third</p>",
295 "<p>Fourth</p>",
296 ]);
297 });
298​
299 it("decodes declared rich text code pages for raw bytes and escaped byte runs", () => {
300 const input = new TextEncoder().encode(
301 String.raw`{\rtf1\ansi\ansicpg1251 A \'c0\par\ansicpg932\'82\'a0}`,
302 );
303 input[input.indexOf(65)] = 0xc0;
304 const result = openRtf(input.buffer);
305 if (result.type !== "document") throw new Error("Expected document");
306 expect(result.pages[0]!.html).toBe("<p>А А<br>あ</p>");
307 for (const header of [String.raw`\mac`, String.raw`\mac\ansicpg10000`]) {
308 const mac = openRtf(bytes(String.raw`{\rtf1` + header + String.raw` Caf\'8e Cr\'8fme}`));
309 if (mac.type !== "document") throw new Error("Expected document");
310 expect(mac.pages[0]!.html).toBe("<p>Café Crème</p>");
311 }
312 for (const [rtf, expected] of [
313 [String.raw`{\rtf1\ansi\ansicpg0 Caf\'e9}`, "<p>Café</p>"],
314 [String.raw`{\rtf1\ansi\ansicpg866 \'8f\'e0\'a8\'a2\'a5\'e2}`, "<p>Привет</p>"],
315 [
316 String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl\f0\froman\fcharset0 Times-Roman;}\f0 \'805 caf\'e9}`,
317 "<p>€5 café</p>",
318 ],
319 [
320 String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0 LucidaGrande;}\f0 pridr\'9eana}`,
321 "<p>pridržana</p>",
322 ],
323 [
324 String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\fnil\fcharset0\cpg1251 Arial;}{\f1\fnil\fcharset204 Arial{\*\fontfile\cpg1252 arial.ttf};}}\f0 \'cf\'f0\'e8\f1\'e2\'e5\'f2}`,
325 "<p>Привет</p>",
326 ],
327 ] as const) {
328 const decoded = openRtf(bytes(rtf));
329 if (decoded.type !== "document") throw new Error("Expected document");
330 expect(decoded.pages[0]!.html).toBe(expected);
331 }
332 expect(() => openRtf(bytes(String.raw`{\rtf1\ansicpg99999 text}`))).toThrow(
333 expect.objectContaining({ code: "rtf-code-page" }),
334 );
335 });
336​
337 it("resolves scoped ODF namespaces and explicit spreadsheet whitespace", async () => {
338 const archive = new JSZip().file(
339 "content.xml",
340 '<o:document-content xmlns:o="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:t="urn:oasis:names:tc:opendocument:xmlns:table:1.0"><o:body><o:spreadsheet><t:table t:name="Accounts &amp; names"><t:table-row><t:table-cell><p xmlns="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:x="urn:oasis:names:tc:opendocument:xmlns:text:1.0">Account<s/>Name<s x:c="3"/>A<tab/>B<line-break/>C &amp; <![CDATA[&amp;]]></p></t:table-cell></t:table-row></t:table></o:spreadsheet></o:body></o:document-content>',
341 );
342 const result = await openDocument(archive, "ods");
343 if (result.type !== "ods") throw new Error("Expected workbook");
344 expect(result.sheets[0]!.name).toBe("Accounts & names");
345 expect(result.sheets[0]!.rows[0]).toEqual(["Account Name A\tB\nC & &amp;"]);
346 });
347​
348 it("stops repeated slide images before encoding beyond the output budget", async () => {
349 const pixels = new Uint8Array(4 * 1024 * 1024);
350 pixels.set(
351 Buffer.from(
352 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
353 "base64",
354 ),
355 );
356 const archive = new JSZip()
357 .file(
358 "content.xml",
359 '<o:document-content xmlns:o="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:d="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:l="http://www.w3.org/1999/xlink"><o:body>' +
360 '<d:page><d:image l:href="picture.png"/></d:page>'.repeat(500) +
361 "</o:body></o:document-content>",
362 )
363 .file("picture.png", pixels);
364 const image = archive.file("picture.png")!;
365 const read = vi.spyOn(image, "async");
366 await expect(openDocument(archive, "odp")).rejects.toMatchObject({
367 code: "rendered-too-large",
368 });
369 expect(read.mock.calls.filter(([type]) => type === "base64")).toHaveLength(2);
370 expect(read).toHaveBeenCalledTimes(5);
371 });
372​
373 it("reads saved notebook cells and preferred outputs without executing code", () => {
374 const result = openNotebook(
375 bytes(
376 JSON.stringify({
377 nbformat: 4,
378 metadata: { language_info: { name: "python" } },
379 cells: [
380 { cell_type: "markdown", source: ["# Results"] },
381 {
382 cell_type: "code",
383 source: ["print(42)"],
384 outputs: [
385 { output_type: "stream", text: ["\n "] },
386 { output_type: "display_data", data: {} },
387 { data: { "text/html": [""] } },
388 { data: { "text/html": [], "text/plain": "array fallback" } },
389 { data: { "text/html": "", "text/plain": "\u001b[1mstring fallback\u001b[0m" } },
390 { data: { "text/html": " ", "text/plain": "space fallback" } },
391 { output_type: "stream", text: ["\u001b[", "32m42\u001b[0m\n"] },
392 {
393 output_type: "stream",
394 name: "stderr",
395 text: ["\r 10%|# |", "\r100%|##########|\n", "done\r\n", "🚀 ready\rX\n"],
396 },
397 { data: { "text/html": ["<b>Results</b>"], "text/plain": ["Results"] } },
398 ],
399 },
400 ],
401 }),
402 ),
403 );
404 expect(result).toEqual({
405 type: "notebook",
406 language: "python",
407 cells: [
408 { kind: "markdown", source: "# Results", outputs: [] },
409 {
410 kind: "code",
411 source: "print(42)",
412 outputs: [
413 { kind: "text", text: "array fallback" },
414 { kind: "text", text: "string fallback" },
415 { kind: "text", text: "space fallback" },
416 { kind: "text", text: "42\n" },
417 { kind: "text", text: "100%|##########|\ndone\nX ready\n" },
418 { kind: "html", text: "<b>Results</b>" },
419 ],
420 },
421 ],
422 });
423 // IPython traceback frames can omit trailing newlines or place ANSI resets after them.
424 const failed = openNotebook(
425 bytes(
426 JSON.stringify({
427 nbformat: 4,
428 cells: [
429 {
430 cell_type: "code",
431 source: "fail()",
432 outputs: [
433 {
434 output_type: "error",
435 traceback: [
436 "-----",
437 "ValueError Traceback (most recent call last)",
438 "Cell In[1], line 4\n----> 4 fail()\n",
439 "Cell In[1], line 2, in fail()\n----> 2 raise ValueError()\n",
440 "ValueError: preview proof",
441 ],
442 },
443 {
444 output_type: "error",
445 traceback: [
446 "Traceback (most recent call last):\n",
447 " Cell In[2], line 5\n fail()\n",
448 "ValueError: preview proof\n",
449 ],
450 },
451 {
452 output_type: "error",
453 traceback: [
454 "\u001b[31mTraceback (most recent call last):\n\u001b[0m",
455 "\u001b[38:2::255:0:0mCell In[3], line 1\n----> 1 fail()\n\u001b[0m\u001b[39m",
456 "\u001b[31mValueError: preview proof\u001b[0m",
457 "final entry",
458 ],
459 },
460 {
461 output_type: "error",
462 ename: "ZeroDivisionError",
463 evalue: "division by zero",
464 traceback: [],
465 },
466 {
467 output_type: "error",
468 evalue: "\u001b[31mbad input\u001b[0m",
469 traceback: [],
470 },
471 {
472 output_type: "error",
473 ename: "RuntimeError",
474 evalue: "kernel reset",
475 traceback: ["\u001b[31m\u001b[0m", " \n"],
476 },
477 ],
478 },
479 ],
480 }),
481 ),
482 );
483 if (failed.type !== "notebook") throw new Error("Expected notebook");
484 expect(failed.cells[0]!.outputs).toEqual([
485 {
486 kind: "text",
487 text: "-----\nValueError Traceback (most recent call last)\nCell In[1], line 4\n----> 4 fail()\nCell In[1], line 2, in fail()\n----> 2 raise ValueError()\nValueError: preview proof",
488 },
489 {
490 kind: "text",
491 text: "Traceback (most recent call last):\n Cell In[2], line 5\n fail()\nValueError: preview proof\n",
492 },
493 {
494 kind: "text",
495 text: "Traceback (most recent call last):\nCell In[3], line 1\n----> 1 fail()\nValueError: preview proof\nfinal entry",
496 },
497 { kind: "text", text: "ZeroDivisionError: division by zero" },
498 { kind: "text", text: "bad input" },
499 { kind: "text", text: "RuntimeError: kernel reset" },
500 ]);
501 expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow(
502 expect.objectContaining({ code: "notebook-unsupported" }),
503 );
504 expect(() =>
505 openNotebook(
506 bytes(JSON.stringify({ nbformat: 4, cells: Array.from({ length: 501 }, () => ({})) })),
507 ),
508 ).toThrow(expect.objectContaining({ code: "notebook-unsupported" }));
509 });
510​
511 it("bounds repeated OpenDocument spreadsheet cells and keeps sheet names and values", async () => {
512 const archive = new JSZip().file(
513 "content.xml",
514 '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet><table:table table:name="Budget"><table:table-row table:number-rows-repeated="999999999"><table:table-cell table:number-columns-repeated="999999999"><text:p>Research &amp; design</text:p></table:table-cell></table:table-row></table:table></office:spreadsheet></office:body></office:document-content>',
515 );
516 const result = await openDocument(archive, "ods");
517 expect(result.type).toBe("ods");
518 if (result.type !== "ods") throw new Error("Expected workbook");
519 expect(result.sheets[0]!.name).toBe("Budget");
520 expect(result.sheets[0]!.truncated).toBe(true);
521 expect(result.sheets[0]!.rows).toHaveLength(500);
522 expect(result.sheets[0]!.rows[0]).toHaveLength(50);
523 expect(result.sheets[0]!.rows[0]![0]).toBe("Research & design");
524 });
525​
526 it("hides ODS values kept in cells a merge covers", async () => {
527 const archive = new JSZip().file(
528 "content.xml",
529 '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet><table:table table:name="Merged">' +
530 '<table:table-row><table:table-cell table:number-columns-spanned="4" table:number-rows-spanned="2"><text:p>Total</text:p></table:table-cell><table:covered-table-cell office:value-type="float" office:value="2"><text:p>2</text:p></table:covered-table-cell><table:covered-table-cell table:number-columns-repeated="2"/><table:table-cell><text:p>Lead</text:p></table:table-cell></table:table-row>' +
531 '<table:table-row><table:covered-table-cell office:value-type="string" office:string-value="Below"/><table:covered-table-cell table:number-columns-repeated="3"/><table:table-cell><text:p>Q2</text:p></table:table-cell></table:table-row>' +
532 "</table:table></office:spreadsheet></office:body></office:document-content>",
533 );
534 const result = await openDocument(archive, "ods");
535 if (result.type !== "ods") throw new Error("Expected workbook");
536 expect(result.sheets[0]!.rows).toEqual([
537 ["Total", "", "", "", "Lead"],
538 ["", "", "", "", "Q2"],
539 ]);
540 });
541​
542 it("reads an ODS time cell that has no display paragraph", async () => {
543 const archive = new JSZip().file(
544 "content.xml",
545 `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"><office:body><office:spreadsheet><table:table table:name="Values"><table:table-row><table:table-cell office:value-type="time" office:time-value="PT03H30M00S"></table:table-cell></table:table-row></table:table></office:spreadsheet></office:body></office:document-content>`,
546 );
547 const result = await openDocument(archive, "ods");
548 if (result.type !== "ods") throw new Error("Expected workbook");
549 expect(result.sheets[0]!.rows).toEqual([["PT03H30M00S"]]);
550 });
551​
552 it.each([1, 500])("ignores styled ODS filler after %s populated rows", async (count) => {
553 const archive = new JSZip().file(
554 "content.xml",
555 `<office:document><table:table><table:table-row table:number-rows-repeated="${count}"><table:table-cell><text:p>North</text:p></table:table-cell><table:table-cell table:number-columns-repeated="1024"/></table:table-row><table:table-row table:number-rows-repeated="1048570"><table:table-cell table:number-columns-repeated="1024"/></table:table-row></table:table></office:document>`,
556 );
557 const result = await openDocument(archive, "ods");
558 if (result.type !== "ods") throw new Error("Expected workbook");
559 expect(result.sheets[0]).toMatchObject({ rowCount: count, columns: 1, truncated: false });
560 expect(result.sheets[0]!.rows).toEqual(Array.from({ length: count }, () => ["North"]));
561 });
562​
563 it.each([2, 999999])(
564 "preserves internal ODS gaps of %s rows and reports real overflow",
565 async (gap) => {
566 const archive = new JSZip().file(
567 "content.xml",
568 `<office:document><table:table><table:table-row><table:table-cell><text:p>First</text:p></table:table-cell></table:table-row><table:table-row table:number-rows-repeated="${gap}"><table:table-cell/></table:table-row><table:table-row><table:table-cell table:number-columns-repeated="2"/><table:table-cell><text:p>Last</text:p></table:table-cell></table:table-row></table:table></office:document>`,
569 );
570 const result = await openDocument(archive, "ods");
571 if (result.type !== "ods") throw new Error("Expected workbook");
572 expect(result.sheets[0]).toMatchObject({
573 rowCount: Math.min(gap + 2, 500),
574 columns: gap === 2 ? 3 : 1,
575 truncated: gap !== 2,
576 });
577 expect(result.sheets[0]!.rows[1]).toEqual([]);
578 if (gap === 2) expect(result.sheets[0]!.rows[3]).toEqual(["", "", "Last"]);
579 },
580 );
581​
582 const approved = "<text:p>Approved <text:span>now</text:span></text:p>";
583 const approvedRow = `<tr>${"<td><p>Approved <span>now</span></p></td>".repeat(2)}</tr>`;
584 it.each([
585 [
586 "expands",
587 `<table:table-row>${`<table:table-cell>${approved}</table:table-cell>`.repeat(2)}</table:table-row><table:table-row table:number-rows-repeated="2"><table:table-cell table:number-columns-repeated="2">${approved}</table:table-cell></table:table-row>`,
588 approvedRow.repeat(3),
589 ],
590 [
591 "bounds",
592 '<table:table-row table:number-rows-repeated="999999999"><table:table-cell table:number-columns-repeated="999999999"><text:p>x</text:p></table:table-cell></table:table-row>',
593 `<tr>${"<td><p>x</p></td>".repeat(50)}</tr>`.repeat(500),
594 ],
595 ])("%s repeated ODT table rows and cells", async (_, rows, html) => {
596 const archive = new JSZip().file(
597 "content.xml",
598 `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:text><table:table><table:table-column table:number-columns-repeated="2"/>${rows}</table:table></office:text></office:body></office:document-content>`,
599 );
600 const result = await openDocument(archive, "odt");
601 if (result.type !== "document") throw new Error("Expected document");
602 expect(result.pages[0]!.html).toBe(`<table>${html}</table>`);
603 });
604​
605 it("preserves ODT table colspan and rowspan on merged cells", async () => {
606 const archive = new JSZip().file(
607 "content.xml",
608 '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:text><table:table><table:table-column table:number-columns-repeated="3"/>' +
609 '<table:table-row><table:table-cell table:number-columns-spanned="2"><text:p>Quarter</text:p></table:table-cell><table:covered-table-cell/><table:table-cell><text:p>Lead</text:p></table:table-cell></table:table-row>' +
610 '<table:table-row><table:table-cell table:number-rows-spanned="2"><text:p>North</text:p></table:table-cell><table:table-cell><text:p>Q1</text:p></table:table-cell><table:table-cell><text:p>Lead A</text:p></table:table-cell></table:table-row>' +
611 "<table:table-row><table:covered-table-cell><text:p>Hidden</text:p></table:covered-table-cell><table:table-cell><text:p>Q2</text:p></table:table-cell><table:table-cell><text:p>Lead B</text:p></table:table-cell></table:table-row>" +
612 '<table:table-row><table:table-cell table:number-columns-spanned="9999" table:number-rows-spanned="0"><text:p>Total</text:p></table:table-cell><table:table-cell table:number-columns-spanned="Infinity" table:number-rows-spanned="50.5"/></table:table-row>' +
613 '<table:table-row table:number-rows-repeated="2"><table:table-cell table:number-columns-spanned="2" table:number-rows-spanned="2"><table:table><table:table-row><table:table-cell table:number-rows-spanned="2"/></table:table-row></table:table></table:table-cell><table:table-cell table:number-columns-repeated="2" table:number-columns-spanned="2"/></table:table-row>' +
614 "</table:table></office:text></office:body></office:document-content>",
615 );
616 const result = await openDocument(archive, "odt");
617 if (result.type !== "document") throw new Error("Expected document");
618 expect(result.pages[0]!.html).toBe(
619 `<table><tr><td colspan="2"><p>Quarter</p></td><td><p>Lead</p></td></tr><tr><td rowspan="2"><p>North</p></td><td><p>Q1</p></td><td><p>Lead A</p></td></tr><tr><td><p>Q2</p></td><td><p>Lead B</p></td></tr><tr><td colspan="50"><p>Total</p></td><td></td></tr>${'<tr><td colspan="2"><table><tr><td rowspan="2"></td></tr></table></td><td></td><td></td></tr>'.repeat(2)}</table>`,
620 );
621 });
622​
623 // LibreOffice writes every index as the templates it was built from, then the built index.
624 const indexes = [
625 "table-of-content",
626 "illustration-index",
627 "table-index",
628 "object-index",
629 "user-index",
630 "alphabetical-index",
631 "bibliography",
632 ].map(
633 (name) =>
634 `<text:${name}><text:${name}-source><text:index-title-template>Index</text:index-title-template><text:${name}-entry-template><text:index-entry-text/><text:index-entry-span>: </text:index-entry-span><text:index-entry-page-number/></text:${name}-entry-template></text:${name}-source><text:index-body><text:index-title><text:p>Index</text:p></text:index-title><text:p>Field notes: 1</text:p></text:index-body></text:${name}>`,
635 );
636 it.each(["odt", "odp"] as const)("reads %s text and rejects unsupported XML", async (kind) => {
637 const archive = new JSZip().file(
638 "content.xml",
639 `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"><office:body>${kind === "odt" ? `<office:text><text:p>Field notes</text:p>${indexes.join("")}</office:text>` : '<draw:page draw:name="Overview"><text:h>Launch plan</text:h><presentation:notes><draw:frame><draw:text-box><text:p>Speaker only</text:p></draw:text-box></draw:frame></presentation:notes></draw:page>'}</office:body></office:document-content>`,
640 );
641 const result = await openDocument(archive, kind);
642 expect(result.type).toBe("document");
643 if (result.type !== "document") throw new Error("Expected document");
644 expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan");
645 expect(result.pages[0]!.html).not.toContain("Speaker only");
646 if (kind === "odt")
647 expect(result.pages[0]!.html).toBe(
648 `<p>Field notes</p>${"<p>Index</p><p>Field notes: 1</p>".repeat(indexes.length)}`,
649 );
650 for (const source of [
651 '<!DOCTYPE x [<!ENTITY external SYSTEM "file:///etc/passwd">]><x>&external;</x>',
652 '<html><body><p title="<!--">x</p><!DOCTYPE x [<!ENTITY e "boom">]><b title="-->">&e;</b></body></html>',
653 '<html><body><p title="<![CDATA[">x</p><!DOCTYPE x [<!ENTITY e "boom">]><b title="]]>">&e;</b></body></html>',
654 '<!DOC<!DOCTYPE a>TYPE x [<!EN<!DOCTYPE a>TITY e "boom">]><x>&e;</x>',
655 '<?test <![CDATA[ ?><!DOCTYPE html [<!ENTITY e "boom">]><html><body><pre><![CDATA[x]]></pre></body></html>',
656 '<?test <!-- ?><!DOCTYPE html [<!ENTITY e "boom">]><html><body><!-- x --></body></html>',
657 "<html><body>" + "<!--".repeat(80_000) + "</body></html>",
658 "<html><body>" + "<![CDATA[".repeat(80_000) + "</body></html>",
659 ]) {
660 archive.file("content.xml", source);
661 await expect(openDocument(archive, kind)).rejects.toMatchObject({ code: "xml-invalid" });
662 }
663 });
664​
665 it("keeps OpenDocument image descriptions in image alt text", async () => {
666 const archive = new JSZip()
667 .file(
668 "content.xml",
669 '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:l="http://www.w3.org/1999/xlink" xmlns:s="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0">' +
670 '<office:body><office:text><text:p><draw:frame><draw:image l:href="picture.png"/><s:title>Logo</s:title><s:desc>Research &amp; &quot;Design&quot;</s:desc></draw:frame>Visible caption</text:p></office:text></office:body></office:document-content>',
671 )
672 .file(
673 "picture.png",
674 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
675 { base64: true },
676 );
677​
678 const result = await openDocument(archive, "odt");
679 if (result.type !== "document") throw new Error("Expected document");
680 expect(result.pages[0]!.html).toMatch(
681 /^<p><img src="data:image\/png;base64,[^"]+" alt="Logo Research &amp; &quot;Design&quot;">Visible caption<\/p>$/,
682 );
683 });
684​
685 it("reads EPUB chapters in spine order and removes active and remote content", async () => {
686 const archive = new JSZip()
687 .file(
688 "META-INF/container.xml",
689 '<container><rootfiles><rootfile full-path="Book/book.opf"/></rootfiles></container>',
690 )
691 .file(
692 "Book/book.opf",
693 '<package><manifest><item id="a" href="one.xhtml" media-type="application/xhtml+xml"/><item id="b" href="two&amp;&#x26;&#38;.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
694 )
695 .file(
696 "Book/one.xhtml",
697 '<html><head><title>First</title></head><body><h1>First chapter</h1><img src="cover.png" alt="Cover"/><img src="https://example.com/tracker.png"/><script>alert(1)</script><style>@import "https://example.com/style.css";</style></body></html>',
698 )
699 .file(
700 "Book/two&&&.xhtml",
701 '<?xml-stylesheet href="a<b.css"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><head><title>Second</title></head><body><h1>Second chapter</h1><p>A&nbsp;B &copy; &mdash; &NotEqualTilde; &amp;lt;</p><pre><![CDATA[Use &amp; and &lt; literally]]></pre><pre><![CDATA[<!DOCTYPE html><!ENTITY author "Ada">]]></pre><!-- <!ENTITY note "x"> --><img src="cover.png" alt="&lt; &copy; &NotEqualTilde;"/></body></html>',
702 )
703 .file(
704 "Book/cover.png",
705 Buffer.from(
706 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
707 "base64",
708 ),
709 );
710 const result = await openEpub(archive);
711 expect(result.type).toBe("document");
712 if (result.type !== "document") throw new Error("Expected document");
713 expect(result.pages.map((page) => page.title)).toEqual(["Second", "First"]);
714 expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &amp;lt;");
715 expect(result.pages[0]!.html).toContain("<pre>Use &amp;amp; and &amp;lt; literally</pre>");
716 expect(result.pages[0]!.html).toContain(
717 "<pre>&lt;!DOCTYPE html&gt;&lt;!ENTITY author &quot;Ada&quot;&gt;</pre>",
718 );
719 expect(result.pages[0]!.html).toContain('alt="&lt; © ≂̸"');
720 expect(result.pages[1]!.html).toContain('src="data:image/png;base64,');
721 expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/);
722 });
723​
724 it.each([
725 ["percent-encoded", "My%20Book/book%201.opf", "My Book/book 1.opf", "My Book/one.xhtml"],
726 ["literal percent", "My%20Book/book.opf", "My%20Book/book.opf", "My%20Book/one.xhtml"],
727 ["malformed percent", "Book%ZZ/book.opf", "Book%ZZ/book.opf", "Book%ZZ/one.xhtml"],
728 ])(
729 "reads EPUB packages with %s rootfile paths",
730 async (_label, fullPath, packagePath, chapterPath) => {
731 const archive = new JSZip()
732 .file(
733 "META-INF/container.xml",
734 `<container><rootfiles><rootfile full-path="${fullPath}"/></rootfiles></container>`,
735 )
736 .file(
737 packagePath,
738 '<package><manifest><item id="a" href="one.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="a"/></spine></package>',
739 )
740 .file(
741 chapterPath,
742 "<html><head><title>First</title></head><body><p>Hello</p></body></html>",
743 );
744 const result = await openEpub(archive);
745 if (result.type !== "document") throw new Error("Expected document");
746 expect(result.pages).toEqual([{ title: "First", html: "<p>Hello</p>" }]);
747 },
748 );
749});