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