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