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