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