Open History to see the last commit
1import { pipe } from "effect/Function";
2import {
3 IMAGE_DIMENSIONS_HEADER_BYTES,
4 readImageDimensions,
5} from "@t3tools/shared/imageDimensions";
6import { XMLParser, XMLValidator } from "fast-xml-parser";
7import { decodeHTMLAttribute, decodeHTMLStrict as decodeEntities } from "entities";
8import type JSZip from "jszip";
9import {
10 terminalOutputCollapseRedraws,
11 terminalOutputPlainText,
12} from "@t3tools/shared/terminalOutput";
13
14import { type OfficeWorkerResult, type NotebookCell } from "./officePreviewProtocol";
15import { PreviewError } from "./previewFailure";
16
17const TABLE_PREVIEW_MAX_ROWS = 500;
18const TABLE_PREVIEW_MAX_COLUMNS = 50;
19
20// `text` and `attrs` hold decoded values: escaped text is decoded once, CDATA stays literal.
21type XmlNode = { name: string; attrs: Record<string, string>; children: XmlNode[]; text: string };
22type OrderedXml = { [key: string]: OrderedXml[] | Record<string, string> | string };
23const escape = (value: string) =>
24 value
25 .replaceAll("&", "&")
26 .replaceAll("<", "<")
27 .replaceAll(">", ">")
28 .replaceAll('"', """);
29
30const namespacePrefixes: Record<string, string> = {
31 "urn:oasis:names:tc:opendocument:xmlns:office:1.0": "office",
32 "urn:oasis:names:tc:opendocument:xmlns:table:1.0": "table",
33 "urn:oasis:names:tc:opendocument:xmlns:text:1.0": "text",
34 "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0": "draw",
35 "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0": "svg",
36 "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0": "presentation",
37 "http://www.w3.org/1999/xlink": "xlink",
38 "http://www.w3.org/1999/xhtml": "",
39 "http://www.idpf.org/2007/opf": "",
40 "urn:oasis:names:tc:opendocument:xmlns:container": "",
41};
42function parseXml(source: string): XmlNode {
43 // EPUB XHTML commonly declares an external DTD: discard it without resolving it. Any other
44 // declaration is rejected; CDATA, comments and processing instructions pass through untouched.
45 let declares = false;
46 source = source.replaceAll(
47 /<\?[\s\S]*?(?:\?>|$)|<!\[CDATA\[[\s\S]*?(?:]]>|$)|<!--[\s\S]*?(?:-->|$)|(<!DOCTYPE\s+[^<>[\]]*>)|(<!\s*(?:DOCTYPE|ENTITY))/gi,
48 (markup, externalDoctype?: string, declaration?: string) => {
49 if (declaration) declares = true;
50 return externalDoctype ? " " : markup;
51 },
52 );
53 if (source.length > 8 * 1024 * 1024 || declares || XMLValidator.validate(source) !== true)
54 throw new PreviewError({ code: "xml-invalid" });
55 const parser = new XMLParser({
56 preserveOrder: true,
57 ignoreAttributes: false,
58 attributeNamePrefix: "",
59 processEntities: false,
60 trimValues: false,
61 parseTagValue: false,
62 cdataPropName: "#cdata",
63 });
64 const ordered = parser.parse(source) as OrderedXml[];
65 let count = 0;
66 function convert(
67 items: OrderedXml[],
68 depth: number,
69 inherited: Record<string, string>,
70 ): XmlNode[] {
71 if (depth > 100) throw new PreviewError({ code: "xml-too-deep" });
72 return items.map((item) => {
73 if (++count > 100_000) throw new PreviewError({ code: "xml-too-much-content" });
74 const name = Object.keys(item).find((key) => key !== ":@") ?? "#text";
75 const value = item[name];
76 if (name === "#cdata") {
77 const literal = Array.isArray(value)
78 ? value.map((part) => part["#text"] ?? "").join("")
79 : "";
80 return { name: "#text", attrs: {}, children: [], text: literal };
81 }
82 const attrs = Object.fromEntries(
83 Object.entries((item[":@"] ?? {}) as Record<string, string>).map(([key, value]) => {
84 // fast-xml-parser accepts raw '<' in element attributes, which can mask declarations
85 // above. Processing instructions end at their first '?>', so their data may hold '<'.
86 if (!name.startsWith("?") && value.includes("<"))
87 throw new PreviewError({ code: "xml-invalid" });
88 return [key, decodeEntities(value)];
89 }),
90 );
91 const namespaces = Object.create(inherited) as Record<string, string>;
92 for (const [key, value] of Object.entries(attrs)) {
93 if (key === "xmlns") namespaces[""] = value;
94 else if (key.startsWith("xmlns:")) namespaces[key.slice(6)] = value;
95 }
96 const expanded = (name: string, attribute = false) => {
97 if (name.startsWith("#")) return name;
98 const colon = name.indexOf(":");
99 if (colon < 0 && attribute) return name;
100 const uri = namespaces[colon < 0 ? "" : name.slice(0, colon)];
101 if (!uri) return name;
102 const prefix = Object.hasOwn(namespacePrefixes, uri) ? namespacePrefixes[uri] : undefined;
103 const local = name.slice(colon + 1);
104 return prefix === undefined
105 ? "{" + uri + "}" + local
106 : prefix
107 ? prefix + ":" + local
108 : local;
109 };
110 return {
111 name: expanded(name),
112 attrs: Object.fromEntries(
113 Object.entries(attrs).map(([key, value]) => [expanded(key, true), value]),
114 ),
115 children: Array.isArray(value) ? convert(value, depth + 1, namespaces) : [],
116 text: typeof value === "string" ? decodeEntities(value) : "",
117 };
118 });
119 }
120 return {
121 name: "root",
122 attrs: {},
123 children: convert(ordered, 0, Object.create(null) as Record<string, string>),
124 text: "",
125 };
126}
127function find(node: XmlNode, name: string, skip?: string): XmlNode[] {
128 return node.children.flatMap((child) =>
129 child.name === skip
130 ? []
131 : child.name === name || (!name.includes(":") && child.name.endsWith(`:${name}`))
132 ? [child]
133 : find(child, name, skip),
134 );
135}
136function text(node: XmlNode): string {
137 if (node.name === "office:annotation") return "";
138 if (node.name === "text:s") return " ".repeat(repeat(node.attrs["text:c"], 100));
139 if (node.name === "text:tab") return "\t";
140 if (node.name === "text:line-break") return "\n";
141 return node.name === "#text" ? node.text : node.children.map(text).join("");
142}
143function archivePath(base: string, href: string): string | null {
144 if (/^(?:[a-z][a-z\d+.-]*:|\/|\\)/i.test(href)) return null;
145 const parts = base.split("/").slice(0, -1);
146 let decoded: string;
147 try {
148 decoded = decodeURIComponent(href.split(/[?#]/, 1)[0] ?? "");
149 } catch {
150 return null;
151 }
152 for (const part of decoded.split("/")) {
153 if (part === "..") {
154 if (!parts.length) return null;
155 parts.pop();
156 } else if (part && part !== ".") parts.push(part);
157 }
158 return parts.join("/");
159}
160function imageFits(bytes: Uint8Array) {
161 const size = readImageDimensions(bytes.subarray(0, IMAGE_DIMENSIONS_HEADER_BYTES));
162 return size !== null && size.width <= 16_777_216 / size.height;
163}
164function base64ImageFits(base64: string) {
165 return (
166 /^[a-z\d+/]*={0,2}$/i.test(base64) &&
167 base64.length % 4 !== 1 &&
168 (!base64.endsWith("=") || base64.length % 4 === 0) &&
169 imageFits(
170 Uint8Array.from(
171 atob(base64.slice(0, 4 * Math.ceil(IMAGE_DIMENSIONS_HEADER_BYTES / 3))),
172 (char) => char.charCodeAt(0),
173 ),
174 )
175 );
176}
177function htmlImagesFit(html: string) {
178 // HTML attribute entities can obscure a data URL until the client parses it.
179 for (const match of decodeHTMLAttribute(html).matchAll(
180 /data:image\/(?:png|jpeg|gif|webp);base64,([a-z\d+/]*={0,2})/gi,
181 ))
182 if (!base64ImageFits(match[1]!)) return false;
183 return true;
184}
185async function imageData(archive: JSZip, path: string | null): Promise<string> {
186 if (!path) return "";
187 const mime = (
188 { png: "png", jpg: "jpeg", jpeg: "jpeg", gif: "gif", webp: "webp" } as Record<string, string>
189 )[path.split(".").at(-1)?.toLowerCase() ?? ""];
190 const entry = archive.file(path);
191 if (!mime || !entry) return "";
192 const bytes = await entry.async("uint8array");
193 if (bytes.length > 4 * 1024 * 1024 || !imageFits(bytes)) return "";
194 reserveMarkup(4 * Math.ceil(bytes.length / 3) + 100);
195 return `data:image/${mime};base64,${await entry.async("base64")}`;
196}
197let markupBytes = 0;
198function reserveMarkup(size: number) {
199 markupBytes += size;
200 if (markupBytes > 16 * 1024 * 1024) throw new PreviewError({ code: "rendered-too-large" });
201}
202function boundedMarkup(value: string): string {
203 reserveMarkup(value.length);
204 return value;
205}
206const HTML_TAGS = new Set([
207 "p",
208 "h1",
209 "h2",
210 "h3",
211 "h4",
212 "h5",
213 "h6",
214 "div",
215 "span",
216 "strong",
217 "b",
218 "em",
219 "i",
220 "u",
221 "s",
222 "ul",
223 "ol",
224 "li",
225 "blockquote",
226 "pre",
227 "code",
228 "table",
229 "thead",
230 "tbody",
231 "tr",
232 "th",
233 "td",
234 "caption",
235 "figure",
236 "figcaption",
237 "br",
238 "hr",
239 "sub",
240 "sup",
241 "dl",
242 "dt",
243 "dd",
244]);
245async function epubHtml(node: XmlNode, archive: JSZip, base: string): Promise<string> {
246 if (node.name === "#text") return pipe(text(node), escape, boundedMarkup);
247 const tag =
248 node.name
249 .replace(/^\{[^}]*\}/, "")
250 .split(":")
251 .at(-1) ?? "";
252 if (["head", "script", "style", "iframe", "object", "embed", "svg", "math", "form"].includes(tag))
253 return "";
254 if (tag === "br" || tag === "hr") return boundedMarkup(`<${tag}>`);
255 if (tag === "img") {
256 const src = await imageData(archive, archivePath(base, node.attrs.src ?? ""));
257 return src ? `<img src="${src}" alt="${boundedMarkup(escape(node.attrs.alt ?? ""))}">` : "";
258 }
259 let children = "";
260 for (const child of node.children) children += await epubHtml(child, archive, base);
261 if (!HTML_TAGS.has(tag)) return children;
262 const spans =
263 tag === "td" || tag === "th"
264 ? ["colspan", "rowspan"]
265 .map((name) =>
266 /^\d{1,4}$/.test(node.attrs[name] ?? "") ? ` ${name}="${node.attrs[name]}"` : "",
267 )
268 .join("")
269 : "";
270 reserveMarkup(tag.length * 2 + spans.length + 5);
271 return `<${tag}${spans}>${children}</${tag}>`;
272}
273async function odfHtml(
274 node: XmlNode,
275 archive: JSZip,
276 imageAlt = "",
277 inRepeatedRow = false,
278): Promise<string> {
279 if (node.name === "#text") return pipe(text(node), escape, boundedMarkup);
280 if (node.name === "text:s" || node.name === "text:tab")
281 return boundedMarkup(
282 `<span data-odf-whitespace>${node.name === "text:tab" ? "	" : " ".repeat(repeat(node.attrs["text:c"], 100))}</span>`,
283 );
284 if (node.name === "text:line-break") return boundedMarkup("<br>");
285 if (node.name === "draw:image") {
286 const src = await imageData(
287 archive,
288 archivePath("content.xml", node.attrs["xlink:href"] ?? ""),
289 );
290 return src ? `<img src="${src}" alt="${boundedMarkup(escape(imageAlt))}">` : "";
291 }
292 if (
293 [
294 "office:annotation",
295 "presentation:notes",
296 "svg:title",
297 "svg:desc",
298 "text:tracked-changes",
299 "office:scripts",
300 "draw:object",
301 "draw:object-ole",
302 "text:table-of-content-source",
303 "text:illustration-index-source",
304 "text:table-index-source",
305 "text:object-index-source",
306 "text:user-index-source",
307 "text:alphabetical-index-source",
308 "text:bibliography-source",
309 "table:covered-table-cell",
310 ].includes(node.name)
311 )
312 return "";
313 const childImageAlt =
314 node.name === "draw:frame"
315 ? ["svg:title", "svg:desc"]
316 .map((name) => node.children.find((child) => child.name === name))
317 .map((child) => (child ? text(child).trim() : ""))
318 .filter(Boolean)
319 .join(" ")
320 : "";
321 let children = "";
322 const repeatedRow =
323 node.name === "table:table-row"
324 ? Number(node.attrs["table:number-rows-repeated"]) > 1
325 : inRepeatedRow;
326 for (const child of node.children)
327 children += await odfHtml(child, archive, childImageAlt, repeatedRow);
328 const tags: Record<string, string> = {
329 "text:p": "p",
330 "text:h": "h2",
331 "text:span": "span",
332 "text:list": "ul",
333 "text:list-item": "li",
334 "table:table": "table",
335 "table:table-row": "tr",
336 "table:table-cell": "td",
337 };
338 const tag = tags[node.name];
339 if (!tag) return children;
340 const count =
341 tag === "tr"
342 ? repeat(node.attrs["table:number-rows-repeated"], TABLE_PREVIEW_MAX_ROWS)
343 : tag === "td"
344 ? repeat(node.attrs["table:number-columns-repeated"], TABLE_PREVIEW_MAX_COLUMNS)
345 : 1;
346 let spans = "";
347 // Spans on repeated cells or rows would multiply past the preview's table limits.
348 if (tag === "td" && count === 1)
349 for (const [name, attr, max] of [
350 ["colspan", "table:number-columns-spanned", TABLE_PREVIEW_MAX_COLUMNS],
351 ["rowspan", "table:number-rows-spanned", repeatedRow ? 1 : TABLE_PREVIEW_MAX_ROWS],
352 ] as const) {
353 const span = Number(node.attrs[attr]);
354 if (max > 1 && Number.isSafeInteger(span) && span > 1)
355 spans += ` ${name}="${Math.min(span, max)}"`;
356 }
357 const markup = `<${tag}${spans}>${children}</${tag}>`;
358 reserveMarkup(count * markup.length - children.length);
359 return markup.repeat(count);
360}
361function repeat(value: string | undefined, max: number) {
362 const count = Number(value ?? 1);
363 if (!Number.isSafeInteger(count) || count < 1)
364 throw new PreviewError({ code: "repeated-content-invalid" });
365 return Math.min(count, max);
366}
367export async function openDocument(
368 archive: JSZip,
369 kind: "odt" | "ods" | "odp",
370): Promise<OfficeWorkerResult> {
371 markupBytes = 0;
372 const source = await archive.file("content.xml")?.async("string");
373 if (!source) throw new PreviewError({ code: "odf-no-content" });
374 const root = parseXml(source);
375 if (kind === "ods") {
376 const tables = find(root, "table:table");
377 if (!tables.length || tables.length > 100) throw new PreviewError({ code: "ods-sheet-count" });
378 let cellBytes = 0;
379 return {
380 type: "ods",
381 sheets: tables.map((table) => {
382 const rows: string[][] = [];
383 let truncated = false;
384 let pendingEmptyRows = 0;
385 for (const row of find(table, "table:table-row")) {
386 const cells: string[] = [];
387 for (const cell of row.children.filter((child) =>
388 ["table:table-cell", "table:covered-table-cell"].includes(child.name),
389 )) {
390 const value =
391 cell.name === "table:covered-table-cell"
392 ? ""
393 : find(cell, "text:p", "office:annotation").map(text).join("\n") ||
394 cell.attrs["office:value"] ||
395 cell.attrs["office:date-value"] ||
396 cell.attrs["office:time-value"] ||
397 cell.attrs["office:boolean-value"] ||
398 cell.attrs["office:string-value"] ||
399 "";
400 const count = repeat(
401 cell.attrs["table:number-columns-repeated"],
402 TABLE_PREVIEW_MAX_COLUMNS + 1,
403 );
404 if (value && cells.length + count > TABLE_PREVIEW_MAX_COLUMNS) truncated = true;
405 for (let i = 0; i < count && cells.length < TABLE_PREVIEW_MAX_COLUMNS; i++) {
406 if (value.length > 10_000) throw new PreviewError({ code: "ods-cell-too-large" });
407 cells.push(value);
408 }
409 }
410 while (cells.at(-1) === "") cells.pop();
411 const count = repeat(row.attrs["table:number-rows-repeated"], TABLE_PREVIEW_MAX_ROWS + 1);
412 if (!cells.length) {
413 pendingEmptyRows = Math.min(TABLE_PREVIEW_MAX_ROWS + 1, pendingEmptyRows + count);
414 continue;
415 }
416 while (pendingEmptyRows > 0 && rows.length < TABLE_PREVIEW_MAX_ROWS) {
417 rows.push([]);
418 pendingEmptyRows--;
419 }
420 pendingEmptyRows = 0;
421 if (rows.length + count > TABLE_PREVIEW_MAX_ROWS) truncated = true;
422 if (rows.length >= TABLE_PREVIEW_MAX_ROWS) break;
423 for (let i = 0; i < count && rows.length < TABLE_PREVIEW_MAX_ROWS; i++) {
424 cellBytes += cells.reduce((size, cell) => size + cell.length, 0);
425 if (cellBytes > 8 * 1024 * 1024) throw new PreviewError({ code: "ods-too-much-text" });
426 rows.push(cells);
427 }
428 }
429 return {
430 name: table.attrs["table:name"] || undefined,
431 rows,
432 rowCount: rows.length,
433 columns: rows.reduce((columns, row) => Math.max(columns, row.length), 1),
434 truncated,
435 };
436 }),
437 };
438 }
439 const pages = kind === "odp" ? find(root, "draw:page") : find(root, "office:text");
440 if (!pages.length || pages.length > 500) throw new PreviewError({ code: "odf-page-count" });
441 const rendered = [];
442 for (const page of pages) {
443 rendered.push({
444 title: page.attrs["draw:name"] || undefined,
445 html: await odfHtml(page, archive),
446 });
447 }
448 return { type: "document", navigation: kind === "odp" ? "slide" : "page", pages: rendered };
449}
450export async function openEpub(archive: JSZip): Promise<OfficeWorkerResult> {
451 markupBytes = 0;
452 const container = parseXml((await archive.file("META-INF/container.xml")?.async("string")) ?? "");
453 const fullPath = find(container, "rootfile")[0]?.attrs["full-path"] ?? "";
454 const rootfile = [archivePath("", fullPath), fullPath].find((path) => path && archive.file(path));
455 if (!rootfile) throw new PreviewError({ code: "epub-no-package" });
456 const packageRoot = parseXml(await archive.file(rootfile)!.async("string"));
457 const manifest = new Map(find(packageRoot, "item").map((item) => [item.attrs.id, item]));
458 const spine = find(packageRoot, "itemref");
459 if (!spine.length || spine.length > 500) throw new PreviewError({ code: "epub-chapter-count" });
460 const pages = [];
461 for (const itemref of spine) {
462 const item = manifest.get(itemref.attrs.idref);
463 if (!item || item.attrs["media-type"] !== "application/xhtml+xml") continue;
464 const path = archivePath(rootfile, item.attrs.href ?? "");
465 const entry = path ? archive.file(path) : null;
466 if (!entry || !path) continue;
467 const chapter = parseXml(await entry.async("string"));
468 pages.push({
469 title:
470 text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter)
471 .trim()
472 .slice(0, 120) || undefined,
473 html: await epubHtml(chapter, archive, path),
474 });
475 }
476 if (!pages.length) throw new PreviewError({ code: "epub-no-chapters" });
477 return { type: "document", navigation: "chapter", pages };
478}
479function record(value: unknown): Record<string, unknown> {
480 return value !== null && typeof value === "object" && !Array.isArray(value)
481 ? (value as Record<string, unknown>)
482 : {};
483}
484function notebookText(value: unknown, limit = 256_000): string {
485 const result =
486 typeof value === "string"
487 ? value
488 : Array.isArray(value)
489 ? value.filter((part) => typeof part === "string").join("")
490 : "";
491 if (result.length > limit) throw new PreviewError({ code: "notebook-cell-too-large" });
492 return result;
493}
494// IPython traceback frames carry ANSI SGR colors and may omit a final newline.
495function tracebackLines(value: unknown): unknown {
496 if (!Array.isArray(value)) return value;
497 const frames = value
498 .filter((frame): frame is string => typeof frame === "string")
499 .map(terminalOutputPlainText);
500 return frames.map((frame, index) =>
501 index && !frames[index - 1]!.endsWith("\n") ? `\n${frame}` : frame,
502 );
503}
504export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult {
505 if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "notebook-too-large" });
506 const notebook = record(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
507 if (notebook.nbformat !== 4 || !Array.isArray(notebook.cells) || notebook.cells.length > 500)
508 throw new PreviewError({ code: "notebook-unsupported" });
509 const language = String(record(record(notebook.metadata).language_info).name ?? "text")
510 .replaceAll(/[^a-z\d+#-]/gi, "")
511 .slice(0, 40);
512 const cells: NotebookCell[] = notebook.cells.map((value) => {
513 const cell = record(value);
514 const outputs = Array.isArray(cell.outputs) ? cell.outputs : [];
515 if (outputs.length > 100) throw new PreviewError({ code: "notebook-too-many-outputs" });
516 return {
517 kind: cell.cell_type === "markdown" ? "markdown" : cell.cell_type === "code" ? "code" : "raw",
518 source: notebookText(cell.source),
519 outputs: outputs
520 .map((value) => {
521 const output = record(value);
522 const data = record(output.data);
523 for (const mime of ["image/png", "image/jpeg", "image/gif", "image/webp"]) {
524 if (data[mime]) {
525 const base64 = notebookText(data[mime], 4 * 1024 * 1024).replaceAll(/\s/g, "");
526 if (base64ImageFits(base64))
527 return { kind: "image" as const, text: `data:${mime};base64,${base64}` };
528 }
529 }
530 const html = notebookText(data["text/html"]);
531 if (html.trim() && htmlImagesFit(html)) return { kind: "html" as const, text: html };
532 const plain = terminalOutputPlainText(
533 notebookText(output.text ?? data["text/plain"] ?? tracebackLines(output.traceback)),
534 );
535 const text =
536 output.output_type === "stream" ? terminalOutputCollapseRedraws(plain) : plain;
537 if (text.trim() || output.output_type !== "error") return { kind: "text" as const, text };
538 const summary = [output.ename, output.evalue]
539 .filter((part) => typeof part === "string")
540 .map((part) => terminalOutputPlainText(notebookText(part)))
541 .filter((part) => part.trim().length > 0)
542 .join(": ");
543 return { kind: "text" as const, text: summary };
544 })
545 .filter((output) => output.text.trim().length > 0),
546 };
547 });
548 return { type: "notebook", language, cells };
549}
550
551// Characters RTF writes as control symbols (`\~`) and control words (`\emspace`).
552const RTF_CHARACTERS = new Map([
553 ["~", "\u00a0"],
554 ["_", "\u2011"],
555 ["-", "\u00ad"],
556 ["tab", "\t"],
557 ["endash", "–"],
558 // oxlint-disable-next-line t3code/no-em-dash-copy -- Preserve the RTF document's punctuation.
559 ["emdash", "—"],
560 ["bullet", "•"],
561 ["lquote", "‘"],
562 ["rquote", "’"],
563 ["ldblquote", "“"],
564 ["rdblquote", "”"],
565 ["enspace", "\u2002"],
566 ["emspace", "\u2003"],
567 ["qmspace", "\u2005"],
568 ["zwbo", "\u200b"],
569 ["zwnj", "\u200c"],
570 ["zwj", "\u200d"],
571 ["ltrmark", "\u200e"],
572 ["rtlmark", "\u200f"],
573]);
574
575const rtfCodePageLabel = (codePage: number) =>
576 (
577 {
578 0: "windows-1252",
579 866: "ibm866",
580 65001: "utf-8",
581 932: "shift_jis",
582 936: "gbk",
583 949: "euc-kr",
584 950: "big5",
585 874: "windows-874",
586 10000: "macintosh",
587 } as Record<number, string>
588 )[codePage] ?? `windows-${codePage}`;
589
590export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult {
591 if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "rtf-too-large" });
592 // Keep byte offsets intact for binary destinations and multibyte code pages.
593 const input = new Uint8Array(bytes);
594 let source = "";
595 for (let offset = 0; offset < input.length; offset += 8192)
596 source += String.fromCharCode(...input.subarray(offset, offset + 8192));
597 if (!source.startsWith("{\\rtf")) throw new PreviewError({ code: "rtf-invalid" });
598 let state = {
599 skip: false,
600 deleted: false,
601 hiddenText: false,
602 bold: false,
603 italic: false,
604 underline: false,
605 uc: 1,
606 font: 0,
607 fontTable: false,
608 fontFile: false,
609 decoder: new TextDecoder("windows-1252"),
610 };
611 // A font's \cpg, else its \fcharset, encodes the bytes written in that font. A \cpg inside
612 // \fontfile encodes the font's file name instead.
613 const fonts = new Map<number, TextDecoder>();
614 let defaultFont = 0;
615 const stack: (typeof state)[] = [];
616 let html = "";
617 const pages: { title: undefined; html: string }[] = [];
618 let completedLength = 0;
619 const finishPage = () => {
620 if (pages.length >= 500) throw new PreviewError({ code: "rtf-too-many-pages" });
621 pages.push({ title: undefined, html: `<p>${html}</p>` });
622 completedLength += html.length;
623 html = "";
624 };
625 let run = "";
626 let fallback = 0;
627 const hidden = () => state.skip || state.deleted || state.hiddenText;
628 const encoded = new Uint8Array(bytes.byteLength);
629 let encodedLength = 0;
630 const decodeBytes = () => {
631 if (!encodedLength) return;
632 run += escape(
633 (fonts.get(state.font) ?? state.decoder).decode(encoded.subarray(0, encodedLength)),
634 );
635 encodedLength = 0;
636 };
637 const flush = () => {
638 decodeBytes();
639 if (completedLength + html.length + run.length > 8 * 1024 * 1024)
640 throw new PreviewError({ code: "rtf-too-much-content" });
641 if (!run) return;
642 let span = run;
643 if (state.bold) span = `<strong>${span}</strong>`;
644 if (state.italic) span = `<em>${span}</em>`;
645 if (state.underline) span = `<u>${span}</u>`;
646 html += span;
647 run = "";
648 };
649 const emit = (value: string, skip = hidden()) => {
650 if (fallback > 0) {
651 fallback--;
652 return;
653 }
654 if (skip) return;
655 decodeBytes();
656 run += escape(value);
657 if (completedLength + html.length + run.length > 8 * 1024 * 1024)
658 throw new PreviewError({ code: "rtf-too-much-content" });
659 };
660 const emitByte = (value: number) => {
661 if (fallback > 0) fallback--;
662 else if (!hidden()) encoded[encodedLength++] = value;
663 };
664 for (let i = 0; i < source.length;) {
665 const char = source[i++];
666 if (char === "{") {
667 flush();
668 fallback = 0;
669 if (stack.length > 100) throw new PreviewError({ code: "rtf-too-deep" });
670 stack.push({ ...state });
671 } else if (char === "}") {
672 flush();
673 fallback = 0;
674 const parent = stack.pop();
675 if (!parent) throw new PreviewError({ code: "rtf-damaged" });
676 state = parent;
677 } else if (char === "\\") {
678 const next = source[i];
679 if (next === "'") {
680 const hex = source.slice(i + 1, i + 3);
681 if (!/^[\da-f]{2}$/i.test(hex)) throw new PreviewError({ code: "rtf-byte-escape" });
682 i += 3;
683 emitByte(Number.parseInt(hex, 16));
684 continue;
685 }
686 // \u, \uc and skipped fallbacks change no formatting, so a character written as two \u
687 // words stays in one run.
688 if (fallback === 0 && !/^uc?-?\d/.test(source.slice(i, i + 4))) flush();
689 if (next === "\\" || next === "{" || next === "}") {
690 i++;
691 emit(next);
692 continue;
693 }
694 if (next === "*") {
695 state.skip = true;
696 i++;
697 continue;
698 }
699 const match = /^([a-z]+)(-?\d+)? ?/i.exec(source.slice(i));
700 if (!match) {
701 const character = RTF_CHARACTERS.get(next!);
702 if (character) emit(character);
703 // A backslash before a line break is \par; TextEdit ends paragraphs this way.
704 else if (next === "\n" || next === "\r") {
705 if (fallback > 0) fallback--;
706 else if (!hidden()) html += "<br>";
707 }
708 i++;
709 continue;
710 }
711 i += match[0].length;
712 const word = match[1];
713 const arg = match[2] === undefined ? 1 : Number(match[2]);
714 if (word === "bin") {
715 if (!Number.isSafeInteger(arg) || arg < 0 || arg > source.length - i)
716 throw new PreviewError({ code: "rtf-binary-data" });
717 i += arg;
718 }
719 if (fallback > 0) {
720 fallback--;
721 continue;
722 }
723 if (word === "fonttbl") {
724 state.fontTable = true;
725 state.skip = true;
726 } else if (word === "deff") state.font = defaultFont = arg;
727 else if (word === "f") state.font = arg;
728 else if (word === "fcharset" && state.fontTable) {
729 const label = (
730 {
731 0: "windows-1252",
732 1: state.decoder.encoding,
733 77: "macintosh",
734 128: "shift_jis",
735 129: "euc-kr",
736 134: "gbk",
737 136: "big5",
738 161: "windows-1253",
739 162: "windows-1254",
740 163: "windows-1258",
741 177: "windows-1255",
742 178: "windows-1256",
743 186: "windows-1257",
744 204: "windows-1251",
745 222: "windows-874",
746 238: "windows-1250",
747 255: "ibm866",
748 } as Record<number, string>
749 )[arg];
750 if (label) fonts.set(state.font, new TextDecoder(label));
751 } else if (word === "fontfile") state.fontFile = true;
752 else if (word === "cpg" && state.fontTable && !state.fontFile) {
753 try {
754 fonts.set(state.font, new TextDecoder(rtfCodePageLabel(arg)));
755 } catch {
756 // An unknown font code page leaves the font on its \fcharset.
757 }
758 } else if (
759 [
760 "colortbl",
761 "stylesheet",
762 "info",
763 "pict",
764 "object",
765 "fldinst",
766 "header",
767 "headerl",
768 "headerr",
769 "headerf",
770 "footer",
771 "footerl",
772 "footerr",
773 "footerf",
774 "filetbl",
775 "datastore",
776 "themedata",
777 ].includes(word!)
778 )
779 state.skip = true;
780 else if (word === "mac") state.decoder = new TextDecoder("macintosh");
781 else if (word === "ansicpg") {
782 try {
783 state.decoder = new TextDecoder(rtfCodePageLabel(arg));
784 } catch {
785 throw new PreviewError({ code: "rtf-code-page" });
786 }
787 } else if (word === "b") state.bold = arg !== 0;
788 else if (word === "i") state.italic = arg !== 0;
789 else if (word === "ul") state.underline = arg !== 0;
790 else if (word === "ulnone") state.underline = false;
791 else if (word === "deleted") state.deleted = arg !== 0;
792 else if (word === "v") state.hiddenText = arg !== 0;
793 else if (word === "plain")
794 state = {
795 ...state,
796 deleted: false,
797 hiddenText: false,
798 bold: false,
799 italic: false,
800 underline: false,
801 font: defaultFont,
802 };
803 else if (word === "uc") state.uc = Math.max(0, Math.min(10, arg));
804 else if (word === "u") {
805 fallback = 0;
806 // TextEdit writes a soft line break as U+2028, where Chromium does not break the line.
807 if (arg !== 0x2028) emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg));
808 else if (!hidden()) {
809 flush();
810 html += "<br>";
811 }
812 fallback = state.uc;
813 } else if (!hidden() && word === "page") finishPage();
814 else if (word === "cell") emit("\t", state.skip);
815 else if (
816 (!state.skip && word === "row") ||
817 (!hidden() && (word === "par" || word === "line"))
818 )
819 html += "<br>";
820 // Writers usually end the paragraph before these breaks; a second break would add a blank line.
821 else if (!hidden() && (word === "sect" || word === "column")) {
822 if (html && !html.endsWith("<br>")) html += "<br>";
823 } else {
824 const character = RTF_CHARACTERS.get(word!);
825 if (character) emit(character);
826 }
827 } else if (char !== "\r" && char !== "\n" && char) emitByte(char.charCodeAt(0));
828 }
829 if (stack.length) throw new PreviewError({ code: "rtf-damaged" });
830 flush();
831 if (html || !pages.length) finishPage();
832 return { type: "document", navigation: "page", pages };
833}