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 { 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
68describe("isMarkdownPreviewFile", () => {
69 it("recognizes markdown and MDX files case-insensitively", () => {
70 expect(isMarkdownPreviewFile("README.md")).toBe(true);
71 expect(isMarkdownPreviewFile("docs/guide.MDX")).toBe(true);
72 expect(isMarkdownPreviewFile("docs/guide.MARKDOWN")).toBe(true);
73 expect(isMarkdownPreviewFile("docs/guide.mdown")).toBe(true);
74 expect(isMarkdownPreviewFile("docs/guide.mkd")).toBe(true);
75 });
76});
77
78describe("resolveFilePreviewPath", () => {
79 it.each([
80 ["/repo/project", null],
81 ["/repo/project/", null],
82 [".", null],
83 [null, null],
84 ["/repo/project/src", "/repo/project/src"],
85 ["/repo/project/src/main.ts", "/repo/project/src/main.ts"],
86 ["src/main.ts", "src/main.ts"],
87 ["/repo/project-other", "/repo/project-other"],
88 ])("opens %s in the appropriate workspace surface", (path, expected) => {
89 const relativePath = resolveFilePreviewPath(path, "/repo/project");
90 expect(relativePath).toBe(expected);
91 if (expected === null) {
92 expect(
93 shouldShowFileExplorer({ relativePath, explorerOpen: false, attachmentOpen: false }),
94 ).toBe(true);
95 }
96 });
97});
98
99describe("workspaceAssetResource", () => {
100 const input = {
101 kind: "workspace-file" as const,
102 threadRef: {
103 environmentId: "env" as ScopedThreadRef["environmentId"],
104 threadId: "thread-1" as ScopedThreadRef["threadId"],
105 },
106 workspaceRoot: "/repo",
107 absolutePath: "/repo/docs/index.html",
108 };
109
110 // regression: #21067 images outside the workspace load through the host media resource
111 it("serves a file outside the workspace as host media and keeps workspace files on workspace access", () => {
112 expect(
113 workspaceAssetResource({ ...input, absolutePath: "/tmp/screenshots/shot.png", draft: false }),
114 ).toEqual({ _tag: "media-file", threadId: "thread-1", path: "/tmp/screenshots/shot.png" });
115 expect(workspaceAssetResource({ ...input, draft: false })).toEqual({
116 _tag: "workspace-file",
117 threadId: "thread-1",
118 path: "/repo/docs/index.html",
119 });
120 });
121
122 it("names the workspace root for a draft, which the server cannot resolve from a thread", () => {
123 expect(workspaceAssetResource({ ...input, draft: true })).toEqual({
124 _tag: "draft-workspace-file",
125 cwd: "/repo",
126 path: "/repo/docs/index.html",
127 });
128 expect(
129 workspaceAssetResource({ ...input, absolutePath: "/tmp/screenshots/shot.png", draft: true }),
130 ).toEqual({ _tag: "draft-workspace-file", cwd: "/repo", path: "/tmp/screenshots/shot.png" });
131 });
132});
133
134describe("document preview contents", () => {
135 const bytes = (text: string) => new TextEncoder().encode(text).buffer;
136
137 it.each(["?", String.raw`\'3f`, String.raw`\\`])(
138 "consumes skipped rich text Unicode fallback %s",
139 (fallback) => {
140 const result = openRtf(bytes(String.raw`{\rtf1{\*\unknown\u945` + fallback + "}Hello}"));
141 if (result.type !== "document") throw new Error("Expected document");
142 expect(result.pages[0]!.html).toBe("<p>Hello</p>");
143 },
144 );
145
146 it("bounds EPUB markup made entirely of empty allowed elements", async () => {
147 const archive = new JSZip()
148 .file(
149 "META-INF/container.xml",
150 '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>',
151 )
152 .file(
153 "book.opf",
154 '<package><manifest><item id="a" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine>' +
155 '<itemref idref="a"/>'.repeat(30) +
156 "</spine></package>",
157 )
158 .file("chapter.xhtml", "<html><body>" + "<figcaption/>".repeat(30_000) + "</body></html>");
159 await expect(openEpub(archive)).rejects.toThrow("too large");
160 });
161
162 it("decodes rich text formatting and Unicode without showing hidden destinations", () => {
163 const result = openRtf(
164 bytes(
165 String.raw`{\rtf1\ansi{\fonttbl{\f0 Hidden font;}}Hello \b bold\b0\par Unicode: \u945?{\*\unknown hidden}{\field{\*\fldinst HYPERLINK "https://example.com"}{\fldrslt visible}}}`,
166 ),
167 );
168 expect(result.type).toBe("document");
169 if (result.type !== "document") throw new Error("Expected document");
170 const html = result.pages[0]!.html;
171 expect(html.replaceAll(/<[^>]*>/g, "")).toBe("Hello boldUnicode: αvisible");
172 expect(html).toContain("<strong>");
173 expect(html).not.toContain("https:");
174 });
175
176 it("treats a backslash before a line break as a paragraph break, as TextEdit writes them", () => {
177 const html = (rtf: string) => {
178 const result = openRtf(bytes(rtf));
179 if (result.type !== "document") throw new Error("Expected document");
180 return result.pages.map((page) => page.html);
181 };
182 const textEdit = String.raw`{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}
183\pard\f0\fs24 \cf0 First\
184Second\
185\
186Third}`;
187 const expected = html(
188 String.raw`{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\pard\f0\fs24 \cf0 First\par Second\par \par Third}`,
189 );
190 expect(html(textEdit)).toEqual(expected);
191 expect(html(textEdit.replaceAll("\n", "\r\n"))).toEqual(expected);
192 });
193
194 it("preserves rich text page breaks and formatting without splitting hidden destinations", () => {
195 const result = openRtf(
196 bytes(String.raw`{\rtf1\b First\page Second\b0{\*\unknown \page hidden}\page Third\page}`),
197 );
198 if (result.type !== "document") throw new Error("Expected document");
199 expect(result.navigation).toBe("page");
200 expect(result.pages.map((page) => page.html)).toEqual([
201 "<p><strong>First</strong></p>",
202 "<p><strong>Second</strong></p>",
203 "<p>Third</p>",
204 ]);
205 expect(() => openRtf(bytes(String.raw`{\rtf1 ` + String.raw`\page`.repeat(501) + "}"))).toThrow(
206 "500 pages",
207 );
208 });
209
210 it("decodes declared rich text code pages for raw bytes and escaped byte runs", () => {
211 const input = new TextEncoder().encode(
212 String.raw`{\rtf1\ansi\ansicpg1251 A \'c0\par\ansicpg932\'82\'a0}`,
213 );
214 input[input.indexOf(65)] = 0xc0;
215 const result = openRtf(input.buffer);
216 if (result.type !== "document") throw new Error("Expected document");
217 expect(result.pages[0]!.html).toBe("<p>А А<br>あ</p>");
218 expect(() => openRtf(bytes(String.raw`{\rtf1\ansicpg99999 text}`))).toThrow("code page");
219 });
220
221 it("resolves scoped ODF namespaces and explicit spreadsheet whitespace", async () => {
222 const archive = new JSZip().file(
223 "content.xml",
224 '<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</p></t:table-cell></t:table-row></t:table></o:spreadsheet></o:body></o:document-content>',
225 );
226 const result = await openDocument(archive, "ods");
227 if (result.type !== "ods") throw new Error("Expected workbook");
228 expect(result.sheets[0]!.name).toBe("Accounts & names");
229 expect(result.sheets[0]!.rows[0]).toEqual(["Account Name A\tB\nC"]);
230 });
231
232 it("stops repeated slide images before encoding beyond the output budget", async () => {
233 const pixels = new Uint8Array(4 * 1024 * 1024);
234 pixels.set(
235 Buffer.from(
236 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
237 "base64",
238 ),
239 );
240 const archive = new JSZip()
241 .file(
242 "content.xml",
243 '<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>' +
244 '<d:page><d:image l:href="picture.png"/></d:page>'.repeat(500) +
245 "</o:body></o:document-content>",
246 )
247 .file("picture.png", pixels);
248 const image = archive.file("picture.png")!;
249 const read = vi.spyOn(image, "async");
250 await expect(openDocument(archive, "odp")).rejects.toThrow("too large");
251 expect(read.mock.calls.filter(([type]) => type === "base64")).toHaveLength(2);
252 expect(read).toHaveBeenCalledTimes(5);
253 });
254
255 it("reads saved notebook cells and preferred outputs without executing code", () => {
256 const result = openNotebook(
257 bytes(
258 JSON.stringify({
259 nbformat: 4,
260 metadata: { language_info: { name: "python" } },
261 cells: [
262 { cell_type: "markdown", source: ["# Results"] },
263 {
264 cell_type: "code",
265 source: ["print(42)"],
266 outputs: [
267 { output_type: "stream", text: ["\n "] },
268 { output_type: "display_data", data: {} },
269 { data: { "text/html": [""] } },
270 { data: { "text/html": [], "text/plain": "array fallback" } },
271 { data: { "text/html": "", "text/plain": "string fallback" } },
272 { data: { "text/html": " ", "text/plain": "space fallback" } },
273 { output_type: "stream", text: ["42\n"] },
274 { data: { "text/html": ["<b>Results</b>"], "text/plain": ["Results"] } },
275 ],
276 },
277 ],
278 }),
279 ),
280 );
281 expect(result).toEqual({
282 type: "notebook",
283 language: "python",
284 cells: [
285 { kind: "markdown", source: "# Results", outputs: [] },
286 {
287 kind: "code",
288 source: "print(42)",
289 outputs: [
290 { kind: "text", text: "array fallback" },
291 { kind: "text", text: "string fallback" },
292 { kind: "text", text: "space fallback" },
293 { kind: "text", text: "42\n" },
294 { kind: "html", text: "<b>Results</b>" },
295 ],
296 },
297 ],
298 });
299 expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow("version 4");
300 expect(() =>
301 openNotebook(
302 bytes(JSON.stringify({ nbformat: 4, cells: Array.from({ length: 501 }, () => ({})) })),
303 ),
304 ).toThrow("500 cells");
305 });
306
307 it("bounds repeated OpenDocument spreadsheet cells and keeps sheet names and values", async () => {
308 const archive = new JSZip().file(
309 "content.xml",
310 '<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>',
311 );
312 const result = await openDocument(archive, "ods");
313 expect(result.type).toBe("ods");
314 if (result.type !== "ods") throw new Error("Expected workbook");
315 expect(result.sheets[0]!.name).toBe("Budget");
316 expect(result.sheets[0]!.truncated).toBe(true);
317 expect(result.sheets[0]!.rows).toHaveLength(500);
318 expect(result.sheets[0]!.rows[0]).toHaveLength(50);
319 expect(result.sheets[0]!.rows[0]![0]).toBe("Research & design");
320 });
321
322 it.each([1, 500])("ignores styled ODS filler after %s populated rows", async (count) => {
323 const archive = new JSZip().file(
324 "content.xml",
325 `<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>`,
326 );
327 const result = await openDocument(archive, "ods");
328 if (result.type !== "ods") throw new Error("Expected workbook");
329 expect(result.sheets[0]).toMatchObject({ rowCount: count, columns: 1, truncated: false });
330 expect(result.sheets[0]!.rows).toEqual(Array.from({ length: count }, () => ["North"]));
331 });
332
333 it.each([2, 999999])(
334 "preserves internal ODS gaps of %s rows and reports real overflow",
335 async (gap) => {
336 const archive = new JSZip().file(
337 "content.xml",
338 `<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>`,
339 );
340 const result = await openDocument(archive, "ods");
341 if (result.type !== "ods") throw new Error("Expected workbook");
342 expect(result.sheets[0]).toMatchObject({
343 rowCount: Math.min(gap + 2, 500),
344 columns: gap === 2 ? 3 : 1,
345 truncated: gap !== 2,
346 });
347 expect(result.sheets[0]!.rows[1]).toEqual([]);
348 if (gap === 2) expect(result.sheets[0]!.rows[3]).toEqual(["", "", "Last"]);
349 },
350 );
351
352 it.each(["odt", "odp"] as const)("reads %s text and rejects XML entities", async (kind) => {
353 const archive = new JSZip().file(
354 "content.xml",
355 `<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"><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></draw:page>'}</office:body></office:document-content>`,
356 );
357 const result = await openDocument(archive, kind);
358 expect(result.type).toBe("document");
359 if (result.type !== "document") throw new Error("Expected document");
360 expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan");
361 archive.file(
362 "content.xml",
363 '<!DOCTYPE x [<!ENTITY external SYSTEM "file:///etc/passwd">]><x>&external;</x>',
364 );
365 await expect(openDocument(archive, kind)).rejects.toThrow("unsupported XML");
366 });
367
368 it("reads EPUB chapters in spine order and removes active and remote content", async () => {
369 const archive = new JSZip()
370 .file(
371 "META-INF/container.xml",
372 '<container><rootfiles><rootfile full-path="Book/book.opf"/></rootfiles></container>',
373 )
374 .file(
375 "Book/book.opf",
376 '<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>',
377 )
378 .file(
379 "Book/one.xhtml",
380 '<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>',
381 )
382 .file(
383 "Book/two&&&.xhtml",
384 '<!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><img src="cover.png" alt="© ≂̸"/></body></html>',
385 )
386 .file(
387 "Book/cover.png",
388 Buffer.from(
389 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
390 "base64",
391 ),
392 );
393 const result = await openEpub(archive);
394 expect(result.type).toBe("document");
395 if (result.type !== "document") throw new Error("Expected document");
396 expect(result.pages.map((page) => page.title)).toEqual(["Second", "First"]);
397 expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &lt;");
398 expect(result.pages[0]!.html).toContain('alt="© ≂̸"');
399 expect(result.pages[1]!.html).toContain('src="data:image/png;base64,');
400 expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/);
401 });
402});