Open History to see the last commit
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 });
221
222 it("breaks lines at the paragraph and line breaks TextEdit writes", () => {
223 const html = (rtf: string) => {
224 const result = openRtf(bytes(rtf));
225 if (result.type !== "document") throw new Error("Expected document");
226 return result.pages.map((page) => page.html);
227 };
228 const textEdit = String.raw`{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}
229\pard\f0\fs24 \cf0 First\
230Second\
231\
232Third}`;
233 const expected = html(
234 String.raw`{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\pard\f0\fs24 \cf0 First\par Second\par \par Third}`,
235 );
236 expect(html(textEdit)).toEqual(expected);
237 expect(html(textEdit.replaceAll("\n", "\r\n"))).toEqual(expected);
238 const lineBreak = html(String.raw`{\rtf1\ansi First line\line Second line}`);
239 expect(lineBreak).toEqual(["<p>First line<br>Second line</p>"]);
240 expect(html(String.raw`{\rtf1\ansi{\v\line\line\line}First line\line Second line}`)).toEqual(
241 lineBreak,
242 );
243 expect(html(String.raw`{\rtf1\ansi First line\uc0\u8232 Second line}`)).toEqual(lineBreak);
244 expect(html(String.raw`{\rtf1\ansi First line\u8232?Second line{\deleted\u8232?}}`)).toEqual(
245 lineBreak,
246 );
247 });
248
249 it("preserves rich text page breaks and formatting without splitting hidden destinations", () => {
250 const result = openRtf(
251 bytes(String.raw`{\rtf1\b First\page Second\b0{\*\unknown \page hidden}\page Third\page}`),
252 );
253 if (result.type !== "document") throw new Error("Expected document");
254 expect(result.navigation).toBe("page");
255 expect(result.pages.map((page) => page.html)).toEqual([
256 "<p><strong>First</strong></p>",
257 "<p><strong>Second</strong></p>",
258 "<p>Third</p>",
259 ]);
260 expect(() => openRtf(bytes(String.raw`{\rtf1 ` + String.raw`\page`.repeat(501) + "}"))).toThrow(
261 expect.objectContaining({ code: "rtf-too-many-pages" }),
262 );
263 });
264
265 it("starts a new line at rich text section and column breaks", () => {
266 const result = openRtf(
267 bytes(
268 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}`,
269 ),
270 );
271 if (result.type !== "document") throw new Error("Expected document");
272 expect(result.pages.map((page) => page.html)).toEqual([
273 "<p>North quota: 120<br>South quota: 240</p>",
274 "<p>East quota: 360<br>West quota: 480<br></p>",
275 ]);
276 const written = openRtf(
277 bytes(String.raw`{\rtf1\ansi First\par\sect\sectd Second\par\column Third\page\sect Fourth}`),
278 );
279 if (written.type !== "document") throw new Error("Expected document");
280 expect(written.pages.map((page) => page.html)).toEqual([
281 "<p>First<br>Second<br>Third</p>",
282 "<p>Fourth</p>",
283 ]);
284 });
285
286 it("decodes declared rich text code pages for raw bytes and escaped byte runs", () => {
287 const input = new TextEncoder().encode(
288 String.raw`{\rtf1\ansi\ansicpg1251 A \'c0\par\ansicpg932\'82\'a0}`,
289 );
290 input[input.indexOf(65)] = 0xc0;
291 const result = openRtf(input.buffer);
292 if (result.type !== "document") throw new Error("Expected document");
293 expect(result.pages[0]!.html).toBe("<p>А А<br>あ</p>");
294 for (const header of [String.raw`\mac`, String.raw`\mac\ansicpg10000`]) {
295 const mac = openRtf(bytes(String.raw`{\rtf1` + header + String.raw` Caf\'8e Cr\'8fme}`));
296 if (mac.type !== "document") throw new Error("Expected document");
297 expect(mac.pages[0]!.html).toBe("<p>Café Crème</p>");
298 }
299 expect(() => openRtf(bytes(String.raw`{\rtf1\ansicpg99999 text}`))).toThrow(
300 expect.objectContaining({ code: "rtf-code-page" }),
301 );
302 });
303
304 it("resolves scoped ODF namespaces and explicit spreadsheet whitespace", async () => {
305 const archive = new JSZip().file(
306 "content.xml",
307 '<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 & 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 & <![CDATA[&]]></p></t:table-cell></t:table-row></t:table></o:spreadsheet></o:body></o:document-content>',
308 );
309 const result = await openDocument(archive, "ods");
310 if (result.type !== "ods") throw new Error("Expected workbook");
311 expect(result.sheets[0]!.name).toBe("Accounts & names");
312 expect(result.sheets[0]!.rows[0]).toEqual(["Account Name A\tB\nC & &"]);
313 });
314
315 it("stops repeated slide images before encoding beyond the output budget", async () => {
316 const pixels = new Uint8Array(4 * 1024 * 1024);
317 pixels.set(
318 Buffer.from(
319 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
320 "base64",
321 ),
322 );
323 const archive = new JSZip()
324 .file(
325 "content.xml",
326 '<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>' +
327 '<d:page><d:image l:href="picture.png"/></d:page>'.repeat(500) +
328 "</o:body></o:document-content>",
329 )
330 .file("picture.png", pixels);
331 const image = archive.file("picture.png")!;
332 const read = vi.spyOn(image, "async");
333 await expect(openDocument(archive, "odp")).rejects.toMatchObject({
334 code: "rendered-too-large",
335 });
336 expect(read.mock.calls.filter(([type]) => type === "base64")).toHaveLength(2);
337 expect(read).toHaveBeenCalledTimes(5);
338 });
339
340 it("reads saved notebook cells and preferred outputs without executing code", () => {
341 const result = openNotebook(
342 bytes(
343 JSON.stringify({
344 nbformat: 4,
345 metadata: { language_info: { name: "python" } },
346 cells: [
347 { cell_type: "markdown", source: ["# Results"] },
348 {
349 cell_type: "code",
350 source: ["print(42)"],
351 outputs: [
352 { output_type: "stream", text: ["\n "] },
353 { output_type: "display_data", data: {} },
354 { data: { "text/html": [""] } },
355 { data: { "text/html": [], "text/plain": "array fallback" } },
356 { data: { "text/html": "", "text/plain": "\u001b[1mstring fallback\u001b[0m" } },
357 { data: { "text/html": " ", "text/plain": "space fallback" } },
358 { output_type: "stream", text: ["\u001b[", "32m42\u001b[0m\n"] },
359 { data: { "text/html": ["<b>Results</b>"], "text/plain": ["Results"] } },
360 ],
361 },
362 ],
363 }),
364 ),
365 );
366 expect(result).toEqual({
367 type: "notebook",
368 language: "python",
369 cells: [
370 { kind: "markdown", source: "# Results", outputs: [] },
371 {
372 kind: "code",
373 source: "print(42)",
374 outputs: [
375 { kind: "text", text: "array fallback" },
376 { kind: "text", text: "string fallback" },
377 { kind: "text", text: "space fallback" },
378 { kind: "text", text: "42\n" },
379 { kind: "html", text: "<b>Results</b>" },
380 ],
381 },
382 ],
383 });
384 // IPython traceback frames can omit trailing newlines or place ANSI resets after them.
385 const failed = openNotebook(
386 bytes(
387 JSON.stringify({
388 nbformat: 4,
389 cells: [
390 {
391 cell_type: "code",
392 source: "fail()",
393 outputs: [
394 {
395 output_type: "error",
396 traceback: [
397 "-----",
398 "ValueError Traceback (most recent call last)",
399 "Cell In[1], line 4\n----> 4 fail()\n",
400 "Cell In[1], line 2, in fail()\n----> 2 raise ValueError()\n",
401 "ValueError: preview proof",
402 ],
403 },
404 {
405 output_type: "error",
406 traceback: [
407 "Traceback (most recent call last):\n",
408 " Cell In[2], line 5\n fail()\n",
409 "ValueError: preview proof\n",
410 ],
411 },
412 {
413 output_type: "error",
414 traceback: [
415 "\u001b[31mTraceback (most recent call last):\n\u001b[0m",
416 "\u001b[38:2::255:0:0mCell In[3], line 1\n----> 1 fail()\n\u001b[0m\u001b[39m",
417 "\u001b[31mValueError: preview proof\u001b[0m",
418 "final entry",
419 ],
420 },
421 ],
422 },
423 ],
424 }),
425 ),
426 );
427 if (failed.type !== "notebook") throw new Error("Expected notebook");
428 expect(failed.cells[0]!.outputs).toEqual([
429 {
430 kind: "text",
431 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",
432 },
433 {
434 kind: "text",
435 text: "Traceback (most recent call last):\n Cell In[2], line 5\n fail()\nValueError: preview proof\n",
436 },
437 {
438 kind: "text",
439 text: "Traceback (most recent call last):\nCell In[3], line 1\n----> 1 fail()\nValueError: preview proof\nfinal entry",
440 },
441 ]);
442 expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow(
443 expect.objectContaining({ code: "notebook-unsupported" }),
444 );
445 expect(() =>
446 openNotebook(
447 bytes(JSON.stringify({ nbformat: 4, cells: Array.from({ length: 501 }, () => ({})) })),
448 ),
449 ).toThrow(expect.objectContaining({ code: "notebook-unsupported" }));
450 });
451
452 it("bounds repeated OpenDocument spreadsheet cells and keeps sheet names and values", async () => {
453 const archive = new JSZip().file(
454 "content.xml",
455 '<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 & design</text:p></table:table-cell></table:table-row></table:table></office:spreadsheet></office:body></office:document-content>',
456 );
457 const result = await openDocument(archive, "ods");
458 expect(result.type).toBe("ods");
459 if (result.type !== "ods") throw new Error("Expected workbook");
460 expect(result.sheets[0]!.name).toBe("Budget");
461 expect(result.sheets[0]!.truncated).toBe(true);
462 expect(result.sheets[0]!.rows).toHaveLength(500);
463 expect(result.sheets[0]!.rows[0]).toHaveLength(50);
464 expect(result.sheets[0]!.rows[0]![0]).toBe("Research & design");
465 });
466
467 it("reads an ODS time cell that has no display paragraph", async () => {
468 const archive = new JSZip().file(
469 "content.xml",
470 `<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>`,
471 );
472 const result = await openDocument(archive, "ods");
473 if (result.type !== "ods") throw new Error("Expected workbook");
474 expect(result.sheets[0]!.rows).toEqual([["PT03H30M00S"]]);
475 });
476
477 it.each([1, 500])("ignores styled ODS filler after %s populated rows", async (count) => {
478 const archive = new JSZip().file(
479 "content.xml",
480 `<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>`,
481 );
482 const result = await openDocument(archive, "ods");
483 if (result.type !== "ods") throw new Error("Expected workbook");
484 expect(result.sheets[0]).toMatchObject({ rowCount: count, columns: 1, truncated: false });
485 expect(result.sheets[0]!.rows).toEqual(Array.from({ length: count }, () => ["North"]));
486 });
487
488 it.each([2, 999999])(
489 "preserves internal ODS gaps of %s rows and reports real overflow",
490 async (gap) => {
491 const archive = new JSZip().file(
492 "content.xml",
493 `<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>`,
494 );
495 const result = await openDocument(archive, "ods");
496 if (result.type !== "ods") throw new Error("Expected workbook");
497 expect(result.sheets[0]).toMatchObject({
498 rowCount: Math.min(gap + 2, 500),
499 columns: gap === 2 ? 3 : 1,
500 truncated: gap !== 2,
501 });
502 expect(result.sheets[0]!.rows[1]).toEqual([]);
503 if (gap === 2) expect(result.sheets[0]!.rows[3]).toEqual(["", "", "Last"]);
504 },
505 );
506
507 const approved = "<text:p>Approved <text:span>now</text:span></text:p>";
508 const approvedRow = `<tr>${"<td><p>Approved <span>now</span></p></td>".repeat(2)}</tr>`;
509 it.each([
510 [
511 "expands",
512 `<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>`,
513 approvedRow.repeat(3),
514 ],
515 [
516 "bounds",
517 '<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>',
518 `<tr>${"<td><p>x</p></td>".repeat(50)}</tr>`.repeat(500),
519 ],
520 ])("%s repeated ODT table rows and cells", async (_, rows, html) => {
521 const archive = new JSZip().file(
522 "content.xml",
523 `<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>`,
524 );
525 const result = await openDocument(archive, "odt");
526 if (result.type !== "document") throw new Error("Expected document");
527 expect(result.pages[0]!.html).toBe(`<table>${html}</table>`);
528 });
529
530 // LibreOffice writes every index as the templates it was built from, then the built index.
531 const indexes = [
532 "table-of-content",
533 "illustration-index",
534 "table-index",
535 "object-index",
536 "user-index",
537 "alphabetical-index",
538 "bibliography",
539 ].map(
540 (name) =>
541 `<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}>`,
542 );
543 it.each(["odt", "odp"] as const)("reads %s text and rejects unsupported XML", async (kind) => {
544 const archive = new JSZip().file(
545 "content.xml",
546 `<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>`,
547 );
548 const result = await openDocument(archive, kind);
549 expect(result.type).toBe("document");
550 if (result.type !== "document") throw new Error("Expected document");
551 expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan");
552 expect(result.pages[0]!.html).not.toContain("Speaker only");
553 if (kind === "odt")
554 expect(result.pages[0]!.html).toBe(
555 `<p>Field notes</p>${"<p>Index</p><p>Field notes: 1</p>".repeat(indexes.length)}`,
556 );
557 for (const source of [
558 '<!DOCTYPE x [<!ENTITY external SYSTEM "file:///etc/passwd">]><x>&external;</x>',
559 '<html><body><p title="<!--">x</p><!DOCTYPE x [<!ENTITY e "boom">]><b title="-->">&e;</b></body></html>',
560 '<html><body><p title="<![CDATA[">x</p><!DOCTYPE x [<!ENTITY e "boom">]><b title="]]>">&e;</b></body></html>',
561 '<!DOC<!DOCTYPE a>TYPE x [<!EN<!DOCTYPE a>TITY e "boom">]><x>&e;</x>',
562 '<?test <![CDATA[ ?><!DOCTYPE html [<!ENTITY e "boom">]><html><body><pre><![CDATA[x]]></pre></body></html>',
563 '<?test <!-- ?><!DOCTYPE html [<!ENTITY e "boom">]><html><body><!-- x --></body></html>',
564 "<html><body>" + "<!--".repeat(80_000) + "</body></html>",
565 "<html><body>" + "<![CDATA[".repeat(80_000) + "</body></html>",
566 ]) {
567 archive.file("content.xml", source);
568 await expect(openDocument(archive, kind)).rejects.toMatchObject({ code: "xml-invalid" });
569 }
570 });
571
572 it("reads EPUB chapters in spine order and removes active and remote content", async () => {
573 const archive = new JSZip()
574 .file(
575 "META-INF/container.xml",
576 '<container><rootfiles><rootfile full-path="Book/book.opf"/></rootfiles></container>',
577 )
578 .file(
579 "Book/book.opf",
580 '<package><manifest><item id="a" href="one.xhtml" media-type="application/xhtml+xml"/><item id="b" href="two&&&.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
581 )
582 .file(
583 "Book/one.xhtml",
584 '<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>',
585 )
586 .file(
587 "Book/two&&&.xhtml",
588 '<?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 B © — ≂̸ &lt;</p><pre><![CDATA[Use & and < literally]]></pre><pre><![CDATA[<!DOCTYPE html><!ENTITY author "Ada">]]></pre><!-- <!ENTITY note "x"> --><img src="cover.png" alt="< © ≂̸"/></body></html>',
589 )
590 .file(
591 "Book/cover.png",
592 Buffer.from(
593 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
594 "base64",
595 ),
596 );
597 const result = await openEpub(archive);
598 expect(result.type).toBe("document");
599 if (result.type !== "document") throw new Error("Expected document");
600 expect(result.pages.map((page) => page.title)).toEqual(["Second", "First"]);
601 expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &lt;");
602 expect(result.pages[0]!.html).toContain("<pre>Use &amp; and &lt; literally</pre>");
603 expect(result.pages[0]!.html).toContain(
604 "<pre><!DOCTYPE html><!ENTITY author "Ada"></pre>",
605 );
606 expect(result.pages[0]!.html).toContain('alt="< © ≂̸"');
607 expect(result.pages[1]!.html).toContain('src="data:image/png;base64,');
608 expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/);
609 });
610});