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.length && 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 const title = text(find(chapter, "title")[0] ?? find(chapter, "h1")[0] ?? chapter).trim();
469 const last = title.charCodeAt(119);
470 pages.push({
471 title: title.slice(0, last >= 0xd800 && last <= 0xdbff ? 119 : 120) || undefined,
472 html: await epubHtml(chapter, archive, path),
473 });
474 }
475 if (!pages.length) throw new PreviewError({ code: "epub-no-chapters" });
476 return { type: "document", navigation: "chapter", pages };
477}
478function record(value: unknown): Record<string, unknown> {
479 return value !== null && typeof value === "object" && !Array.isArray(value)
480 ? (value as Record<string, unknown>)
481 : {};
482}
483function notebookText(value: unknown, limit = 256_000): string {
484 const result =
485 typeof value === "string"
486 ? value
487 : Array.isArray(value)
488 ? value.filter((part) => typeof part === "string").join("")
489 : "";
490 if (result.length > limit) throw new PreviewError({ code: "notebook-cell-too-large" });
491 return result;
492}
493// IPython traceback frames carry ANSI SGR colors and may omit a final newline.
494function tracebackLines(value: unknown): unknown {
495 if (!Array.isArray(value)) return value;
496 const frames = value
497 .filter((frame): frame is string => typeof frame === "string")
498 .map(terminalOutputPlainText);
499 return frames.map((frame, index) =>
500 index && !frames[index - 1]!.endsWith("\n") ? `\n${frame}` : frame,
501 );
502}
503export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult {
504 if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "notebook-too-large" });
505 const notebook = record(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
506 if (notebook.nbformat !== 4 || !Array.isArray(notebook.cells) || notebook.cells.length > 500)
507 throw new PreviewError({ code: "notebook-unsupported" });
508 const language =
509 String(record(record(notebook.metadata).language_info).name ?? "")
510 .replaceAll(/[^a-z\d+#-]/gi, "")
511 .slice(0, 40) || "text";
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 54936: "gb18030",
588 } as Record<number, string>
589 )[codePage] ?? `windows-${codePage}`;
590
591export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult {
592 if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "rtf-too-large" });
593 // Keep byte offsets intact for binary destinations and multibyte code pages.
594 const input = new Uint8Array(bytes);
595 let source = "";
596 for (let offset = 0; offset < input.length; offset += 8192)
597 source += String.fromCharCode(...input.subarray(offset, offset + 8192));
598 if (!source.startsWith("{\\rtf")) throw new PreviewError({ code: "rtf-invalid" });
599 let state = {
600 skip: false,
601 deleted: false,
602 hiddenText: false,
603 bold: false,
604 italic: false,
605 underline: false,
606 uc: 1,
607 font: 0,
608 fontTable: false,
609 fontFile: false,
610 decoder: new TextDecoder("windows-1252"),
611 };
612 // A font's \cpg, else its \fcharset, encodes the bytes written in that font. A \cpg inside
613 // \fontfile encodes the font's file name instead.
614 const fonts = new Map<number, TextDecoder>();
615 let defaultFont = 0;
616 const stack: (typeof state)[] = [];
617 let html = "";
618 const pages: { title: undefined; html: string }[] = [];
619 let completedLength = 0;
620 const finishPage = () => {
621 if (pages.length >= 500) throw new PreviewError({ code: "rtf-too-many-pages" });
622 pages.push({ title: undefined, html: `<p>${html}</p>` });
623 completedLength += html.length;
624 html = "";
625 };
626 let run = "";
627 let fallback = 0;
628 const hidden = () => state.skip || state.deleted || state.hiddenText;
629 const encoded = new Uint8Array(bytes.byteLength);
630 let encodedLength = 0;
631 const decodeBytes = () => {
632 if (!encodedLength) return;
633 run += escape(
634 (fonts.get(state.font) ?? state.decoder).decode(encoded.subarray(0, encodedLength)),
635 );
636 encodedLength = 0;
637 };
638 const flush = () => {
639 decodeBytes();
640 if (completedLength + html.length + run.length > 8 * 1024 * 1024)
641 throw new PreviewError({ code: "rtf-too-much-content" });
642 if (!run) return;
643 let span = run;
644 if (state.bold) span = `<strong>${span}</strong>`;
645 if (state.italic) span = `<em>${span}</em>`;
646 if (state.underline) span = `<u>${span}</u>`;
647 html += span;
648 run = "";
649 };
650 const emit = (value: string, skip = hidden()) => {
651 if (fallback > 0) {
652 fallback--;
653 return;
654 }
655 if (skip) return;
656 decodeBytes();
657 run += escape(value);
658 if (completedLength + html.length + run.length > 8 * 1024 * 1024)
659 throw new PreviewError({ code: "rtf-too-much-content" });
660 };
661 const emitByte = (value: number) => {
662 if (fallback > 0) fallback--;
663 else if (!hidden()) encoded[encodedLength++] = value;
664 };
665 for (let i = 0; i < source.length;) {
666 const char = source[i++];
667 if (char === "{") {
668 flush();
669 fallback = 0;
670 if (stack.length > 100) throw new PreviewError({ code: "rtf-too-deep" });
671 stack.push({ ...state });
672 } else if (char === "}") {
673 flush();
674 fallback = 0;
675 const parent = stack.pop();
676 if (!parent) throw new PreviewError({ code: "rtf-damaged" });
677 state = parent;
678 } else if (char === "\\") {
679 const next = source[i];
680 if (next === "'") {
681 const hex = source.slice(i + 1, i + 3);
682 if (!/^[\da-f]{2}$/i.test(hex)) throw new PreviewError({ code: "rtf-byte-escape" });
683 i += 3;
684 emitByte(Number.parseInt(hex, 16));
685 continue;
686 }
687 // \u, \uc and skipped fallbacks change no formatting, so a character written as two \u
688 // words stays in one run.
689 if (fallback === 0 && !/^uc?-?\d/.test(source.slice(i, i + 4))) flush();
690 if (next === "\\" || next === "{" || next === "}") {
691 i++;
692 emit(next);
693 continue;
694 }
695 if (next === "*") {
696 state.skip = true;
697 i++;
698 continue;
699 }
700 const match = /^([a-z]+)(-?\d+)? ?/i.exec(source.slice(i));
701 if (!match) {
702 const character = RTF_CHARACTERS.get(next!);
703 if (character) emit(character);
704 // A backslash before a line break is \par; TextEdit ends paragraphs this way.
705 else if (next === "\n" || next === "\r") {
706 if (fallback > 0) fallback--;
707 else if (!hidden()) html += "<br>";
708 }
709 i++;
710 continue;
711 }
712 i += match[0].length;
713 const word = match[1];
714 const arg = match[2] === undefined ? 1 : Number(match[2]);
715 if (word === "bin") {
716 if (!Number.isSafeInteger(arg) || arg < 0 || arg > source.length - i)
717 throw new PreviewError({ code: "rtf-binary-data" });
718 i += arg;
719 }
720 if (fallback > 0) {
721 fallback--;
722 continue;
723 }
724 if (word === "fonttbl") {
725 state.fontTable = true;
726 state.skip = true;
727 } else if (word === "deff") state.font = defaultFont = arg;
728 else if (word === "f") state.font = arg;
729 else if (word === "fcharset" && state.fontTable) {
730 const label = (
731 {
732 0: "windows-1252",
733 1: state.decoder.encoding,
734 77: "macintosh",
735 128: "shift_jis",
736 129: "euc-kr",
737 134: "gbk",
738 136: "big5",
739 161: "windows-1253",
740 162: "windows-1254",
741 163: "windows-1258",
742 177: "windows-1255",
743 178: "windows-1256",
744 186: "windows-1257",
745 204: "windows-1251",
746 222: "windows-874",
747 238: "windows-1250",
748 255: "ibm866",
749 } as Record<number, string>
750 )[arg];
751 if (label) fonts.set(state.font, new TextDecoder(label));
752 } else if (word === "fontfile") state.fontFile = true;
753 else if (word === "cpg" && state.fontTable && !state.fontFile) {
754 try {
755 fonts.set(state.font, new TextDecoder(rtfCodePageLabel(arg)));
756 } catch {
757 // An unknown font code page leaves the font on its \fcharset.
758 }
759 } else if (
760 [
761 "colortbl",
762 "stylesheet",
763 "info",
764 "pict",
765 "object",
766 "fldinst",
767 "header",
768 "headerl",
769 "headerr",
770 "headerf",
771 "footer",
772 "footerl",
773 "footerr",
774 "footerf",
775 "filetbl",
776 "datastore",
777 "themedata",
778 ].includes(word!)
779 )
780 state.skip = true;
781 else if (word === "mac") state.decoder = new TextDecoder("macintosh");
782 else if (word === "ansicpg") {
783 try {
784 state.decoder = new TextDecoder(rtfCodePageLabel(arg));
785 } catch {
786 throw new PreviewError({ code: "rtf-code-page" });
787 }
788 } else if (word === "b") state.bold = arg !== 0;
789 else if (word === "i") state.italic = arg !== 0;
790 else if (word === "ul") state.underline = arg !== 0;
791 else if (word === "ulnone") state.underline = false;
792 else if (word === "deleted") state.deleted = arg !== 0;
793 else if (word === "v") state.hiddenText = arg !== 0;
794 else if (word === "plain")
795 state = {
796 ...state,
797 deleted: false,
798 hiddenText: false,
799 bold: false,
800 italic: false,
801 underline: false,
802 font: defaultFont,
803 };
804 else if (word === "uc") state.uc = Math.max(0, Math.min(10, arg));
805 else if (word === "u") {
806 fallback = 0;
807 // TextEdit writes a soft line break as U+2028, where Chromium does not break the line.
808 if (arg !== 0x2028) emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg));
809 else if (!hidden()) {
810 flush();
811 html += "<br>";
812 }
813 fallback = state.uc;
814 } else if (!hidden() && word === "page") finishPage();
815 else if (word === "cell") emit("\t", state.skip);
816 else if (
817 (!state.skip && word === "row") ||
818 (!hidden() && (word === "par" || word === "line"))
819 )
820 html += "<br>";
821 // Writers usually end the paragraph before these breaks; a second break would add a blank line.
822 else if (!hidden() && (word === "sect" || word === "column")) {
823 if (html && !html.endsWith("<br>")) html += "<br>";
824 } else {
825 const character = RTF_CHARACTERS.get(word!);
826 if (character) emit(character);
827 }
828 } else if (char !== "\r" && char !== "\n" && char) emitByte(char.charCodeAt(0));
829 }
830 if (stack.length) throw new PreviewError({ code: "rtf-damaged" });
831 flush();
832 if (html || !pages.length) finishPage();
833 return { type: "document", navigation: "page", pages };
834}