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("preserves rich text page breaks and formatting without splitting hidden destinations", () => {
177 const result = openRtf(
178 bytes(String.raw`{\rtf1\b First\page Second\b0{\*\unknown \page hidden}\page Third\page}`),
179 );
180 if (result.type !== "document") throw new Error("Expected document");
181 expect(result.navigation).toBe("page");
182 expect(result.pages.map((page) => page.html)).toEqual([
183 "<p><strong>First</strong></p>",
184 "<p><strong>Second</strong></p>",
185 "<p>Third</p>",
186 ]);
187 expect(() => openRtf(bytes(String.raw`{\rtf1 ` + String.raw`\page`.repeat(501) + "}"))).toThrow(
188 "500 pages",
189 );
190 });
191
192 it("decodes declared rich text code pages for raw bytes and escaped byte runs", () => {
193 const input = new TextEncoder().encode(
194 String.raw`{\rtf1\ansi\ansicpg1251 A \'c0\par\ansicpg932\'82\'a0}`,
195 );
196 input[input.indexOf(65)] = 0xc0;
197 const result = openRtf(input.buffer);
198 if (result.type !== "document") throw new Error("Expected document");
199 expect(result.pages[0]!.html).toBe("<p>А А<br>あ</p>");
200 expect(() => openRtf(bytes(String.raw`{\rtf1\ansicpg99999 text}`))).toThrow("code page");
201 });
202
203 it("resolves scoped ODF namespaces and explicit spreadsheet whitespace", async () => {
204 const archive = new JSZip().file(
205 "content.xml",
206 '<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>',
207 );
208 const result = await openDocument(archive, "ods");
209 if (result.type !== "ods") throw new Error("Expected workbook");
210 expect(result.sheets[0]!.name).toBe("Accounts & names");
211 expect(result.sheets[0]!.rows[0]).toEqual(["Account Name A\tB\nC"]);
212 });
213
214 it("stops repeated slide images before encoding beyond the output budget", async () => {
215 const pixels = new Uint8Array(4 * 1024 * 1024);
216 pixels.set(
217 Buffer.from(
218 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
219 "base64",
220 ),
221 );
222 const archive = new JSZip()
223 .file(
224 "content.xml",
225 '<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>' +
226 '<d:page><d:image l:href="picture.png"/></d:page>'.repeat(500) +
227 "</o:body></o:document-content>",
228 )
229 .file("picture.png", pixels);
230 const image = archive.file("picture.png")!;
231 const read = vi.spyOn(image, "async");
232 await expect(openDocument(archive, "odp")).rejects.toThrow("too large");
233 expect(read.mock.calls.filter(([type]) => type === "base64")).toHaveLength(2);
234 expect(read).toHaveBeenCalledTimes(5);
235 });
236
237 it("reads saved notebook cells and preferred outputs without executing code", () => {
238 const result = openNotebook(
239 bytes(
240 JSON.stringify({
241 nbformat: 4,
242 metadata: { language_info: { name: "python" } },
243 cells: [
244 { cell_type: "markdown", source: ["# Results"] },
245 {
246 cell_type: "code",
247 source: ["print(42)"],
248 outputs: [
249 { output_type: "stream", text: ["\n "] },
250 { output_type: "display_data", data: {} },
251 { data: { "text/html": [""] } },
252 { data: { "text/html": [], "text/plain": "array fallback" } },
253 { data: { "text/html": "", "text/plain": "string fallback" } },
254 { data: { "text/html": " ", "text/plain": "space fallback" } },
255 { output_type: "stream", text: ["42\n"] },
256 { data: { "text/html": ["<b>Results</b>"], "text/plain": ["Results"] } },
257 ],
258 },
259 ],
260 }),
261 ),
262 );
263 expect(result).toEqual({
264 type: "notebook",
265 language: "python",
266 cells: [
267 { kind: "markdown", source: "# Results", outputs: [] },
268 {
269 kind: "code",
270 source: "print(42)",
271 outputs: [
272 { kind: "text", text: "array fallback" },
273 { kind: "text", text: "string fallback" },
274 { kind: "text", text: "space fallback" },
275 { kind: "text", text: "42\n" },
276 { kind: "html", text: "<b>Results</b>" },
277 ],
278 },
279 ],
280 });
281 expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow("version 4");
282 expect(() =>
283 openNotebook(
284 bytes(JSON.stringify({ nbformat: 4, cells: Array.from({ length: 501 }, () => ({})) })),
285 ),
286 ).toThrow("500 cells");
287 });
288
289 it("bounds repeated OpenDocument spreadsheet cells and keeps sheet names and values", async () => {
290 const archive = new JSZip().file(
291 "content.xml",
292 '<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>',
293 );
294 const result = await openDocument(archive, "ods");
295 expect(result.type).toBe("ods");
296 if (result.type !== "ods") throw new Error("Expected workbook");
297 expect(result.sheets[0]!.name).toBe("Budget");
298 expect(result.sheets[0]!.truncated).toBe(true);
299 expect(result.sheets[0]!.rows).toHaveLength(500);
300 expect(result.sheets[0]!.rows[0]).toHaveLength(50);
301 expect(result.sheets[0]!.rows[0]![0]).toBe("Research & design");
302 });
303
304 it.each([1, 500])("ignores styled ODS filler after %s populated rows", async (count) => {
305 const archive = new JSZip().file(
306 "content.xml",
307 `<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>`,
308 );
309 const result = await openDocument(archive, "ods");
310 if (result.type !== "ods") throw new Error("Expected workbook");
311 expect(result.sheets[0]).toMatchObject({ rowCount: count, columns: 1, truncated: false });
312 expect(result.sheets[0]!.rows).toEqual(Array.from({ length: count }, () => ["North"]));
313 });
314
315 it.each([2, 999999])(
316 "preserves internal ODS gaps of %s rows and reports real overflow",
317 async (gap) => {
318 const archive = new JSZip().file(
319 "content.xml",
320 `<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>`,
321 );
322 const result = await openDocument(archive, "ods");
323 if (result.type !== "ods") throw new Error("Expected workbook");
324 expect(result.sheets[0]).toMatchObject({
325 rowCount: Math.min(gap + 2, 500),
326 columns: gap === 2 ? 3 : 1,
327 truncated: gap !== 2,
328 });
329 expect(result.sheets[0]!.rows[1]).toEqual([]);
330 if (gap === 2) expect(result.sheets[0]!.rows[3]).toEqual(["", "", "Last"]);
331 },
332 );
333
334 it.each(["odt", "odp"] as const)("reads %s text and rejects XML entities", async (kind) => {
335 const archive = new JSZip().file(
336 "content.xml",
337 `<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>`,
338 );
339 const result = await openDocument(archive, kind);
340 expect(result.type).toBe("document");
341 if (result.type !== "document") throw new Error("Expected document");
342 expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan");
343 archive.file(
344 "content.xml",
345 '<!DOCTYPE x [<!ENTITY external SYSTEM "file:///etc/passwd">]><x>&external;</x>',
346 );
347 await expect(openDocument(archive, kind)).rejects.toThrow("unsupported XML");
348 });
349
350 it("reads EPUB chapters in spine order and removes active and remote content", async () => {
351 const archive = new JSZip()
352 .file(
353 "META-INF/container.xml",
354 '<container><rootfiles><rootfile full-path="Book/book.opf"/></rootfiles></container>',
355 )
356 .file(
357 "Book/book.opf",
358 '<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>',
359 )
360 .file(
361 "Book/one.xhtml",
362 '<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>',
363 )
364 .file(
365 "Book/two&&&.xhtml",
366 '<!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>',
367 )
368 .file(
369 "Book/cover.png",
370 Buffer.from(
371 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
372 "base64",
373 ),
374 );
375 const result = await openEpub(archive);
376 expect(result.type).toBe("document");
377 if (result.type !== "document") throw new Error("Expected document");
378 expect(result.pages.map((page) => page.title)).toEqual(["Second", "First"]);
379 expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &lt;");
380 expect(result.pages[0]!.html).toContain('alt="© ≂̸"');
381 expect(result.pages[1]!.html).toContain('src="data:image/png;base64,');
382 expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/);
383 });
384});