Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

extendedDocumentPreview.ts

672 lines24.2 KB

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