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