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