Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- isolated CLI worker; no server runtime is loaded here.
2import * as NodeFSP from "node:fs/promises";
3import * as NodePath from "node:path";
4import * as NodeUtil from "node:util";
5import { characterEntities } from "character-entities";
6import { SaxesParser } from "saxes";
7import * as Yauzl from "yauzl";
8import { terminalOutputCollapseRedraws } from "@t3tools/shared/terminalOutput";
9
10const MAX_INPUT = 16 * 1024 * 1024;
11const MAX_EXPANDED = 32 * 1024 * 1024;
12const MAX_OUTPUT = 1_000_000;
13const CELL_START = Symbol("cell-start");
14const CELL_END = Symbol("cell-end");
15const LINE_START = Symbol("line-start");
16const THEMATIC_BREAK = Symbol("thematic-break");
17const MARKUP_COMPATIBILITY_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006";
18type TextPart =
19 | string
20 | typeof CELL_START
21 | typeof CELL_END
22 | typeof LINE_START
23 | typeof THEMATIC_BREAK
24 | { imageDescription: string }
25 | { fallback: string };
26
27const TRUNCATED = "\n\n[Extracted text truncated at document extraction limits.]";
28// Parts the document never displays: the XHTML head, tracked deletions and moves, field codes,
29// phonetic guides, paragraph properties such as tab-stop definitions, drawing anchor layout
30// values and encoded field data.
31const HIDDEN = new Set([
32 "head",
33 "script",
34 "style",
35 "binary-data",
36 "rPh",
37 "delText",
38 "moveFrom",
39 "instrText",
40 "delInstrText",
41 "tracked-changes",
42 "pPr",
43 "positionH",
44 "positionV",
45 "sizeRelH",
46 "sizeRelV",
47 "fldData",
48 // An OpenDocument index keeps its templates beside the generated index; only the latter is content.
49 "table-of-content-source",
50 "illustration-index-source",
51 "table-index-source",
52 "object-index-source",
53 "user-index-source",
54 "alphabetical-index-source",
55 "bibliography-source",
56]);
57
58// @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel.
59class Truncation extends Error {}
60
61interface XmlNode {
62 name: string;
63 attrs: Record<string, string>;
64 children: Array<XmlNode | string>;
65 imageDescription?: string;
66 spaceCount?: number;
67 hasText?: boolean;
68 hasTextChoice?: boolean;
69 markupCompatibility?: boolean;
70 hasSelectedChoice?: boolean;
71 epubTable?: boolean;
72}
73
74// ODF 1.3 Part 3 §6.1.2: paragraph character data turns TAB, CR and LF into spaces, collapses
75// space runs and trims the ends; only <text:s>, <text:tab> and <text:line-break> keep literal ones.
76function collapseOdfWhitespace(paragraph: XmlNode) {
77 let afterSpace = true;
78 let tail: { node: XmlNode; index: number; value: string } | undefined;
79 const visit = (node: XmlNode) => {
80 for (const [index, child] of node.children.entries()) {
81 if (typeof child !== "string") {
82 if (HIDDEN.has(child.name)) continue;
83 if (child.spaceCount === undefined && !["tab", "line-break", "p", "h"].includes(child.name))
84 visit(child);
85 else {
86 afterSpace = false;
87 tail = undefined;
88 }
89 continue;
90 }
91 let value = child.replaceAll(/[ \t\r\n]+/g, " ");
92 if (afterSpace && value.startsWith(" ")) value = value.slice(1);
93 if (value) {
94 afterSpace = value.endsWith(" ");
95 tail = { node, index, value };
96 }
97 node.children[index] = value;
98 }
99 };
100 visit(paragraph);
101 if (tail && afterSpace) tail.node.children[tail.index] = tail.value.slice(0, -1);
102}
103
104function separateRubyReadings(ruby: XmlNode) {
105 const parts = ruby.children.filter((part) =>
106 typeof part === "string"
107 ? part.trim() !== ""
108 : !HIDDEN.has(part.name) && (part.name !== "rp" || part.hasText),
109 );
110 const isFallback = (part: XmlNode | string | undefined) =>
111 typeof part !== "string" && part?.name === "rp";
112 for (const [index, part] of parts.entries()) {
113 if (typeof part === "string" || part.name !== "rt" || !part.hasText) continue;
114 if (isFallback(parts[index - 1]) || isFallback(parts[index + 1])) continue;
115 part.children.unshift("(");
116 part.children.push(")");
117 }
118}
119
120function xml(source: string, extension: string): XmlNode {
121 const odf = [".odt", ".ods", ".odp"].includes(extension);
122 const root: XmlNode = { name: "root", attrs: {}, children: [] };
123 const stack = [root];
124 let nodes = 0;
125 const parser = new SaxesParser();
126 if (extension === ".epub") Object.assign(parser.ENTITIES, characterEntities);
127 parser.on("opentag", (tag) => {
128 if (++nodes > 200_000 || stack.length > 128) throw new Truncation("XML structure limit");
129 const node: XmlNode = {
130 name: tag.name.split(":").at(-1)!,
131 attrs: Object.fromEntries(
132 Object.entries(tag.attributes).flatMap(([key, value]) => {
133 const local = key.split(":").at(-1)!;
134 // XHTML table spans are unqualified; a prefixed colspan is a foreign attribute.
135 return extension === ".epub" && (local === "colspan" || local === "rowspan")
136 ? [[key, String(value)]]
137 : [
138 [key, String(value)],
139 [local, String(value)],
140 ];
141 }),
142 ),
143 children: [],
144 };
145 if (extension === ".epub" && node.name === "table") node.epubTable = true;
146 if (odf && node.name === "s") node.spaceCount = repeatCount(node.attrs.c);
147 stack.at(-1)!.children.push(node);
148 stack.push(node);
149 if (node.name === "AlternateContent" || node.name === "Choice") {
150 const colon = tag.name.lastIndexOf(":");
151 const binding = colon === -1 ? "xmlns" : `xmlns:${tag.name.slice(0, colon)}`;
152 if (
153 stack.findLast((ancestor) => Object.hasOwn(ancestor.attrs, binding))?.attrs[binding] ===
154 MARKUP_COMPATIBILITY_NS
155 )
156 node.markupCompatibility = true;
157 }
158 });
159 parser.on("closetag", (tag) => {
160 const node = stack.pop()!;
161 const parent = stack.at(-1)!;
162 const isCompatibilityChoice =
163 node.name === "Choice" &&
164 node.markupCompatibility &&
165 parent.name === "AlternateContent" &&
166 parent.markupCompatibility;
167 if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node);
168 if (
169 (extension === ".epub" &&
170 (stack[1] ?? node).name === "html" &&
171 Object.hasOwn(tag.attributes, "hidden") &&
172 !/^until-found$/i.test(String(tag.attributes.hidden))) ||
173 (extension === ".docx" && node.name === "del") ||
174 (extension === ".docx" &&
175 node.name === "r" &&
176 children(node)
177 .flatMap((child) => (child.name === "rPr" ? children(child) : []))
178 .some(
179 (prop) => prop.name === "vanish" && ["true", "1", "on"].includes(prop.attrs.val ?? "1"),
180 )) ||
181 (odf && node.name === "annotation" && parent.name !== "semantics") ||
182 (extension === ".pptx" &&
183 node.name === "timing" &&
184 stack.every((ancestor) =>
185 ["root", "sld", "AlternateContent", "Choice", "Fallback"].includes(ancestor.name),
186 )) ||
187 (extension === ".odp" &&
188 node.name === "page-thumbnail" &&
189 stack.some((ancestor) => ancestor.name === "notes")) ||
190 (isCompatibilityChoice && parent.hasSelectedChoice)
191 ) {
192 parent.children.pop();
193 return;
194 }
195 if (extension === ".epub" && node.name === "ruby" && stack[1]?.name === "html")
196 separateRubyReadings(node);
197 if (node.name === "Fallback" && !retainCompatibilityFallback(parent, node)) return;
198 const alt = tag.attributes.alt;
199 if (
200 extension === ".epub" &&
201 node.name === "img" &&
202 stack[1]?.name === "html" &&
203 alt?.trim() &&
204 !/(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*(?:hidden|collapse))\s*(?:!important\s*)?(?:;|$)/i.test(
205 String(tag.attributes.style ?? ""),
206 )
207 ) {
208 node.imageDescription = alt;
209 node.hasText = true;
210 }
211 if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return;
212 parent.hasText = true;
213 if (node.name === "Choice") parent.hasTextChoice = true;
214 if (isCompatibilityChoice) {
215 parent.hasSelectedChoice = true;
216 parent.children = parent.children.filter(
217 (child) =>
218 child === node ||
219 typeof child === "string" ||
220 !(child.name === "Choice" && child.markupCompatibility),
221 );
222 }
223 });
224 const text = (value: string) => {
225 const node = stack.at(-1)!;
226 node.children.push(value);
227 if (value.trim() !== "") node.hasText = true;
228 };
229 parser.on("text", text);
230 parser.on("cdata", text);
231 parser.write(source).close();
232 return root;
233}
234
235const children = (node: XmlNode | undefined) =>
236 node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? [];
237
238function slideRelationshipId(slide: XmlNode, inheritedAttributes: XmlNode["attrs"]) {
239 for (const [name, value] of Object.entries(slide.attrs)) {
240 if (!name.endsWith(":id")) continue;
241 const binding = `xmlns:${name.slice(0, -3)}`;
242 const namespace = slide.attrs[binding] ?? inheritedAttributes[binding];
243 if (
244 namespace === "http://schemas.openxmlformats.org/officeDocument/2006/relationships" ||
245 namespace === "http://purl.oclc.org/ooxml/officeDocument/relationships"
246 )
247 return value;
248 }
249 return slide.attrs["r:id"] ?? slide.attrs.id;
250}
251
252function retainCompatibilityFallback(parent: XmlNode, fallback: XmlNode): boolean {
253 // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes.
254 // Keep one when no Choice carries text, such as a chart with a VML caption.
255 if (parent.hasTextChoice) {
256 parent.children.pop();
257 return false;
258 }
259 if (fallback.hasText || hasInlineTab(fallback, ["tab", "ptab"])) {
260 parent.children = parent.children.filter(
261 (child) =>
262 typeof child === "string" || child.name !== "Choice" || !hasInlineTab(child, ["ptab"]),
263 );
264 }
265 return true;
266}
267
268function hasInlineTab(node: XmlNode, names: readonly string[]): boolean {
269 return (
270 !HIDDEN.has(node.name) &&
271 (names.includes(node.name) || children(node).some((child) => hasInlineTab(child, names)))
272 );
273}
274function* all(
275 node: XmlNode,
276 name: string | readonly string[],
277 skip: readonly string[] = [],
278): Generator<XmlNode, void> {
279 for (const child of children(node)) {
280 if (typeof name === "string" ? child.name === name : name.includes(child.name)) yield child;
281 else if (!skip.includes(child.name)) yield* all(child, name, skip);
282 }
283}
284function* text(node: XmlNode): Generator<TextPart, void> {
285 if (HIDDEN.has(node.name)) return;
286 if (node.imageDescription !== undefined) {
287 yield { imageDescription: node.imageDescription };
288 return;
289 }
290 // Word text boxes hold their own paragraphs inside the anchoring paragraph.
291 if (node.name === "txbxContent") yield* paragraphs(node);
292 else if (["tab", "ptab", "cell"].includes(node.name)) yield "\t";
293 else if (["br", "line-break", "cr"].includes(node.name)) yield "\n";
294 else if (node.name === "noBreakHyphen") yield "\u2011";
295 else if (node.spaceCount !== undefined) {
296 yield " ".repeat(Math.min(MAX_OUTPUT, node.spaceCount));
297 if (node.spaceCount > MAX_OUTPUT) throw new Truncation("Space repeat limit");
298 } else
299 for (const child of node.children) {
300 if (typeof child === "string") yield child;
301 else yield* text(child);
302 }
303}
304// SpreadsheetML `t` and `v` values are ST_Xstring: `_xHHHH_` is one UTF-16 code unit, and an
305// escaped lead underscore (`_x005F_xHHHH_`) keeps the literal `_xHHHH_`. Decoded in one pass.
306function* xstringText(node: XmlNode): Generator<string, void> {
307 if (HIDDEN.has(node.name)) return;
308 if (node.name !== "t" && node.name !== "v") {
309 for (const child of children(node)) yield* xstringText(child);
310 return;
311 }
312 yield node.children
313 .filter((child) => typeof child === "string")
314 .join("")
315 .replaceAll(
316 /_x005[Ff]_(x[\dA-Fa-f]{4}_)|_x([\dA-Fa-f]{4})_/g,
317 (_, literal?: string, hex?: string) =>
318 literal ? `_${literal}` : String.fromCharCode(Number.parseInt(hex!, 16)),
319 );
320}
321function* paragraphs(node: XmlNode): Generator<TextPart, void> {
322 if (HIDDEN.has(node.name)) return;
323 if (node.imageDescription !== undefined) {
324 yield* text(node);
325 return;
326 }
327 for (const child of node.children) {
328 if (typeof child === "string") yield child;
329 else if (["br", "line-break", "cr"].includes(child.name)) yield "\n";
330 else if (child.name === "hr") yield THEMATIC_BREAK;
331 else if (["tbl", "table"].includes(child.name)) yield* table(child);
332 else if (child.name === "pre" && child.hasText) {
333 yield LINE_START;
334 yield* text(child);
335 yield LINE_START;
336 } else if (["p", "h"].includes(child.name) || /^h[1-6]$/.test(child.name)) {
337 const style =
338 all(child, "pStyle", ["pPrChange", "txbxContent"]).next().value?.attrs.val ?? "";
339 const level =
340 child.name === "h"
341 ? Number(child.attrs["outline-level"]) || 1
342 : /^h[1-6]$/.test(child.name)
343 ? Number(child.name[1])
344 : Number(style.match(/^Heading([1-6])$/i)?.[1]) || 0;
345 if (level) yield `${"#".repeat(Math.min(6, level))} `;
346 yield* text(child);
347 yield "\n";
348 } else if (
349 ["blockquote", "figcaption", "aside", "address"].includes(child.name) &&
350 child.hasText
351 ) {
352 yield LINE_START;
353 yield* paragraphs(child);
354 yield LINE_START;
355 } else {
356 if (["ol", "ul", "dl"].includes(child.name)) {
357 if (!child.hasText) continue;
358 yield LINE_START;
359 }
360 yield* paragraphs(child);
361 if (["li", "div", "section", "dt", "dd"].includes(child.name)) yield "\n";
362 }
363 }
364}
365// A notes page also holds the slide image, slide number, date, header and footer placeholders.
366const NOTES_PAGE_PLACEHOLDERS = new Set(["sldImg", "sldNum", "dt", "hdr", "ftr"]);
367const isNotesPagePlaceholder = (node: XmlNode) =>
368 node.name === "sp" && NOTES_PAGE_PLACEHOLDERS.has(all(node, "ph").next().value?.attrs.type ?? "");
369function withoutNotesPagePlaceholders(node: XmlNode): XmlNode {
370 return {
371 ...node,
372 children: node.children
373 .filter((child) => typeof child === "string" || !isNotesPagePlaceholder(child))
374 .map((child) => (typeof child === "string" ? child : withoutNotesPagePlaceholders(child))),
375 };
376}
377function* inCell(parts: Iterable<TextPart>): Generator<TextPart, void> {
378 yield CELL_START;
379 yield* parts;
380 yield CELL_END;
381}
382function repeatCount(value: string | undefined): number {
383 if (value === undefined) return 1;
384 if (!/^[0-9]+$/.test(value) || Number(value) < 1) throw new Error("Invalid repeat count");
385 return Number(value);
386}
387function odfValue(cell: XmlNode): string {
388 const type = cell.attrs["office:value-type"] ?? cell.attrs["value-type"];
389 const attr = (name: string) => cell.attrs[`office:${name}`] ?? cell.attrs[name] ?? "";
390 switch (type) {
391 case "void":
392 return "";
393 case "string":
394 return attr("string-value");
395 case "boolean":
396 return attr("boolean-value");
397 case "date":
398 return attr("date-value");
399 case "time":
400 return attr("time-value");
401 case "currency":
402 return attr("value").trim() ? `${attr("value")} ${attr("currency")}`.trim() : "";
403 case "percentage":
404 return attr("value").trim() ? `${attr("value")} [ODF value-type=percentage]` : "";
405 default:
406 return attr("value");
407 }
408}
409const covered = (cell: XmlNode) => cell.name === "covered-table-cell";
410function hasCellText(cell: XmlNode): boolean {
411 if (covered(cell)) return false;
412 if (cell.imageDescription !== undefined || odfValue(cell).trim() || cell.name === "noBreakHyphen")
413 return true;
414 // Space markers can have enormous repeat counts; emptiness never requires expanding them.
415 if (HIDDEN.has(cell.name) || cell.spaceCount !== undefined) return false;
416 return cell.children.some((child) =>
417 typeof child === "string" ? !!child.trim() : hasCellText(child),
418 );
419}
420function epubSpan(value: string | undefined) {
421 const digits = value?.match(/^[\t\n\f\r ]*\+?([0-9]+)/)?.[1];
422 return digits === undefined ? 1 : Number(digits);
423}
424
425function* epubTable(node: XmlNode): Generator<TextPart, void> {
426 const occupiedUntil = new Uint32Array(512);
427 let rowIndex = 0;
428 let rowCount = 0;
429 for (const part of children(node)) {
430 const rowGroup = ["thead", "tbody", "tfoot"].includes(part.name);
431 if (!rowGroup && part.name !== "tr") continue;
432 if (rowGroup) occupiedUntil.fill(0);
433 for (const row of rowGroup ? children(part) : [part]) {
434 if (row.name !== "tr") continue;
435 rowIndex++;
436 const cells = children(row)
437 .filter((cell) => cell.name === "td" || cell.name === "th")
438 .map((cell) => ({ cell, rowSpan: epubSpan(cell.attrs.rowspan) }));
439 const lastText = cells.findLastIndex(({ cell }) => hasCellText(cell));
440 if (lastText >= 0 && ++rowCount > 10_000) throw new Truncation("Row limit");
441 if (lastText >= 0 && rowCount === 1) yield LINE_START;
442 // An empty cell can still reserve columns in later rows.
443 const lastCell = Math.max(
444 lastText,
445 cells.findLastIndex(({ rowSpan }) => rowSpan !== 1),
446 );
447 let column = 0;
448 let lastColumn = 0;
449 for (let index = 0; index <= lastCell; index++) {
450 const { cell, rowSpan } = cells[index]!;
451 while ((occupiedUntil[column] ?? 0) > rowIndex) column++;
452 const width = Math.max(1, Math.min(1000, epubSpan(cell.attrs.colspan)));
453 const endColumn = column + width;
454 const inBounds = column < occupiedUntil.length;
455 if (!inBounds && hasCellText(cell)) throw new Truncation("Column limit");
456 if (rowSpan !== 1) {
457 // A zero row span covers the rest of the row group.
458 const endRow = rowSpan === 0 ? 0xffffffff : rowIndex + Math.min(65_534, rowSpan);
459 const trackedEnd = Math.min(endColumn, occupiedUntil.length);
460 for (let slot = column; slot < trackedEnd; slot++) {
461 occupiedUntil[slot] = Math.max(occupiedUntil[slot]!, endRow);
462 }
463 }
464 if (inBounds && index <= lastText) {
465 if (column > lastColumn) yield "\t".repeat(column - lastColumn);
466 yield CELL_START;
467 yield* paragraphs(cell);
468 yield { fallback: odfValue(cell) };
469 yield CELL_END;
470 lastColumn = column;
471 }
472 column = endColumn;
473 }
474 if (lastText >= 0) yield "\n";
475 }
476 if (rowGroup) occupiedUntil.fill(0);
477 }
478}
479
480function* table(node: XmlNode): Generator<TextPart, void> {
481 for (const caption of children(node)) {
482 if (caption.name !== "caption") continue;
483 yield LINE_START;
484 yield* paragraphs(caption);
485 yield LINE_START;
486 }
487 if (node.epubTable) {
488 yield* epubTable(node);
489 return;
490 }
491 let rowCount = 0;
492 for (const row of all(node, ["tr", "table-row"], ["caption"])) {
493 // Word nests a cell inside w:sdt when a content control wraps the whole cell.
494 const cells = [...all(row, ["tc", "table-cell", "covered-table-cell", "td", "th"])];
495 // ODS writers pad sheets with repeated empty rows and trailing cells.
496 while (cells.length && !hasCellText(cells.at(-1)!)) cells.pop();
497 if (!cells.length) continue;
498 const repeat = repeatCount(row.attrs["number-rows-repeated"]);
499 for (let index = 0; index < repeat; index++) {
500 if (++rowCount > 10_000) throw new Truncation("Row limit");
501 let column = 0;
502 let gap = 0;
503 for (const cell of cells) {
504 const count = repeatCount(cell.attrs["number-columns-repeated"]);
505 // Word emits no cell for columns covered by w:gridSpan; pad before the next cell.
506 const tcPr = cell.name === "tc" ? children(cell).find((c) => c.name === "tcPr") : undefined;
507 const val = tcPr && children(tcPr).find((c) => c.name === "gridSpan")?.attrs.val;
508 const span = val ? Math.max(1, Number.parseInt(val, 10) || 1) : 1;
509 for (let i = 0; i < count; i++) {
510 column += span;
511 if (column > 512) throw new Truncation("Column limit");
512 if (gap) yield "\t".repeat(gap);
513 gap = span;
514 // LibreOffice hides the contents a merge covers; the cell still holds its column.
515 if (covered(cell)) continue;
516 yield CELL_START;
517 yield* paragraphs(cell);
518 yield { fallback: odfValue(cell) };
519 yield CELL_END;
520 }
521 }
522 yield "\n";
523 }
524 }
525}
526
527async function archive(path: string): Promise<Map<string, string>> {
528 const zip = await new Promise<Yauzl.ZipFile>((resolve, reject) =>
529 Yauzl.open(
530 path,
531 { lazyEntries: true, validateEntrySizes: true, strictFileNames: true },
532 (error, result) => (error || !result ? reject(error) : resolve(result)),
533 ),
534 );
535 const files = new Map<string, string>();
536 let expanded = 0;
537 let count = 0;
538 try {
539 await new Promise<void>((resolve, reject) => {
540 zip.on("error", reject);
541 zip.on("end", resolve);
542 zip.on("entry", (entry: Yauzl.Entry) => {
543 if (++count > 2048 || zip.entryCount > 2048) {
544 reject(new Truncation("Archive limit"));
545 return;
546 }
547 if (entry.generalPurposeBitFlag & 1) {
548 reject(new Error("Encrypted archive"));
549 return;
550 }
551 if (!/\.(xml|rels|xhtml|html|htm|opf|svg)$/i.test(entry.fileName)) {
552 zip.readEntry();
553 return;
554 }
555 if (
556 entry.uncompressedSize > MAX_EXPANDED ||
557 entry.uncompressedSize > Math.max(1024, entry.compressedSize * 200)
558 ) {
559 reject(new Truncation("Archive limit"));
560 return;
561 }
562 expanded += entry.uncompressedSize;
563 if (expanded > MAX_EXPANDED) {
564 reject(new Truncation("Expanded byte limit"));
565 return;
566 }
567 zip.openReadStream(entry, (error, stream) => {
568 if (error || !stream) {
569 reject(error);
570 return;
571 }
572 const buffers: Buffer[] = [];
573 let size = 0;
574 stream.on("error", reject);
575 stream.on("data", (chunk: Buffer) => {
576 size += chunk.length;
577 if (size > entry.uncompressedSize || size > MAX_EXPANDED) {
578 stream.destroy(new Truncation("Entry byte limit"));
579 return;
580 }
581 buffers.push(chunk);
582 });
583 stream.on("end", () => {
584 const data = Buffer.concat(buffers);
585 // XML's BOM and initial '<' bytes distinguish both UTF-16 byte orders.
586 const encoding =
587 (data[0] === 0xff && data[1] === 0xfe) || (data[0] === 0x3c && data[1] === 0)
588 ? "utf-16le"
589 : (data[0] === 0xfe && data[1] === 0xff) || (data[0] === 0 && data[1] === 0x3c)
590 ? "utf-16be"
591 : "utf-8";
592 files.set(entry.fileName, new TextDecoder(encoding).decode(data));
593 zip.readEntry();
594 });
595 });
596 });
597 zip.readEntry();
598 });
599 } finally {
600 zip.close();
601 }
602 return files;
603}
604
605const NOTEBOOK_CELL_TYPES = ["code", "markdown", "raw"];
606
607function* notebook(source: string): Generator<string, void> {
608 const book: unknown = JSON.parse(source);
609 if (!book || typeof book !== "object" || !("cells" in book) || !Array.isArray(book.cells))
610 throw new Error("Invalid notebook");
611 function* lines(value: unknown): Generator<string, void> {
612 if (typeof value === "string") yield value;
613 else if (Array.isArray(value))
614 for (const line of value) {
615 if (typeof line === "string") yield line;
616 }
617 }
618 function outputText(value: unknown, stream = false): string {
619 // Notebook fragments can split a terminal escape sequence or a CRLF pair.
620 const plain = NodeUtil.stripVTControlCharacters([...lines(value)].join(""));
621 return stream ? terminalOutputCollapseRedraws(plain) : plain;
622 }
623 for (const [index, cell] of book.cells.entries()) {
624 if (index >= 10_000) throw new Truncation("Notebook cell limit");
625 if (!cell || typeof cell !== "object") continue;
626 const cellType = "cell_type" in cell ? cell.cell_type : undefined;
627 const kind = NOTEBOOK_CELL_TYPES.find((type) => type === cellType) ?? "markdown";
628 yield `## Cell ${index + 1} (${kind})\n`;
629 if ("source" in cell) yield* lines(cell.source);
630 if ("outputs" in cell && Array.isArray(cell.outputs)) {
631 yield "\nOutput:\n";
632 for (const output of cell.outputs) {
633 if (!output || typeof output !== "object") continue;
634 if ("text" in output)
635 yield outputText(output.text, "output_type" in output && output.output_type === "stream");
636 else if (
637 "data" in output &&
638 output.data &&
639 typeof output.data === "object" &&
640 "text/plain" in output.data
641 )
642 yield outputText(output.data["text/plain"]);
643 else if ("output_type" in output && output.output_type === "error") {
644 if ("ename" in output) yield* lines(output.ename);
645 if ("evalue" in output) {
646 yield ": ";
647 yield* lines(output.evalue);
648 }
649 yield "\n";
650 if ("traceback" in output)
651 for (const line of lines(output.traceback)) {
652 yield NodeUtil.stripVTControlCharacters(line);
653 yield "\n";
654 }
655 }
656 yield "\n";
657 }
658 }
659 yield "\n\n";
660 }
661}
662
663const FONT_CODE_PAGES = new Map([
664 [0, "windows-1252"],
665 [77, "macintosh"],
666 [128, "shift_jis"],
667 [129, "euc-kr"],
668 [134, "gbk"],
669 [136, "big5"],
670 [161, "windows-1253"],
671 [162, "windows-1254"],
672 [163, "windows-1258"],
673 [177, "windows-1255"],
674 [178, "windows-1256"],
675 [186, "windows-1257"],
676 [204, "windows-1251"],
677 [222, "windows-874"],
678 [238, "windows-1250"],
679 [255, "ibm866"],
680]);
681
682const RTF_CODE_PAGES = new Map([
683 [0, "windows-1252"],
684 [866, "ibm866"],
685 [874, "windows-874"],
686 [932, "shift_jis"],
687 [936, "gbk"],
688 [949, "euc-kr"],
689 [950, "big5"],
690 [10000, "macintosh"],
691 [54936, "gb18030"],
692 [65001, "utf-8"],
693]);
694
695const rtfCodePage = (value: number) =>
696 RTF_CODE_PAGES.get(value) ?? (value >= 1250 && value <= 1258 ? `windows-${value}` : undefined);
697
698function* rtf(source: string): Generator<string, void> {
699 if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document");
700 let state = {
701 skip: false,
702 deleted: false,
703 hiddenText: false,
704 uc: 1,
705 font: 0,
706 fontTable: false,
707 fontFile: false,
708 decoder: new TextDecoder("windows-1252"),
709 };
710 const stack: Array<typeof state> = [];
711 // A font's \cpg, else its \fcharset, not the document code page, encodes the bytes written in
712 // that font. A \cpg inside \fontfile encodes the font's file name instead.
713 const fonts = new Map<number, typeof state.decoder>();
714 let defaultFont = 0;
715 const decoder = () => fonts.get(state.font) ?? state.decoder;
716 const hidden = () => state.skip || state.deleted || state.hiddenText;
717 let encoded: Uint8Array | undefined;
718 let encodedLength = 0;
719 function* flushBytes(): Generator<string, void> {
720 if (!encodedLength) return;
721 const chunk = encoded!.subarray(0, encodedLength);
722 encodedLength = 0;
723 yield decoder().decode(chunk);
724 }
725 function* emitByte(byte: number): Generator<string, void> {
726 // No supported multibyte code page uses bytes below 0x30 as trail bytes.
727 if ((!encodedLength && byte < 128) || (encodedLength && byte < 0x30)) {
728 yield* flushBytes();
729 yield String.fromCharCode(byte);
730 return;
731 }
732 // GB18030 spends up to 4 bytes per UTF-16 unit, so a full buffer decodes past MAX_OUTPUT.
733 encoded ??= new Uint8Array(Math.min(source.length, MAX_OUTPUT * 4 + 4));
734 if (encodedLength === encoded.length) yield* flushBytes();
735 encoded[encodedLength++] = byte;
736 }
737 const symbols = new Map([
738 ["endash", "–"],
739 ["emdash", characterEntities.mdash],
740 ["enspace", "\u2002"],
741 ["emspace", "\u2003"],
742 ["qmspace", "\u2005"],
743 ["lquote", "‘"],
744 ["rquote", "’"],
745 ["ldblquote", "“"],
746 ["rdblquote", "”"],
747 ["bullet", "•"],
748 ["zwj", "\u200d"],
749 ["zwnj", "\u200c"],
750 ["ltrmark", "\u200e"],
751 ["rtlmark", "\u200f"],
752 ["~", "\u00a0"],
753 ["_", "\u2011"],
754 ["-", ""],
755 ]);
756 let fallback = 0;
757 for (let i = 0; i < source.length; i++) {
758 const char = source[i]!;
759 if (char === "{" || char === "}") {
760 yield* flushBytes();
761 fallback = 0;
762 }
763 if (char === "{") {
764 stack.push({ ...state });
765 if (stack.length > 128) throw new Truncation("RTF depth limit");
766 } else if (char === "}") state = stack.pop() ?? state;
767 else if (char === "\\") {
768 const rest = source.slice(i + 1, i + 80);
769 const hex = /^'([0-9a-f]{2})/i.exec(rest);
770 const word = /^([a-z]+)(-?\d+)? ?/i.exec(rest);
771 if (hex) {
772 if (fallback) fallback--;
773 else if (!hidden()) yield* emitByte(Number.parseInt(hex[1]!, 16));
774 i += 3;
775 } else if (word) {
776 i += word[0].length;
777 const control = word[1]!;
778 const value = Number(word[2]);
779 if (control === "bin") {
780 if (!Number.isSafeInteger(value) || value < 0)
781 throw new Error("Invalid RTF binary length");
782 i += value;
783 }
784 if (fallback) {
785 fallback--;
786 continue;
787 }
788 yield* flushBytes();
789 if (
790 [
791 "fonttbl",
792 "colortbl",
793 "stylesheet",
794 "info",
795 "pict",
796 "object",
797 "fldinst",
798 "header",
799 "headerf",
800 "headerl",
801 "headerr",
802 "footer",
803 "footerf",
804 "footerl",
805 "footerr",
806 ].includes(control)
807 )
808 state.skip = true;
809 if (control === "fonttbl") state.fontTable = true;
810 else if (control === "fontfile") state.fontFile = true;
811 else if (control === "deff") state.font = defaultFont = value;
812 else if (control === "f") {
813 state.font = value;
814 if (state.fontTable) fonts.delete(value);
815 } else if (control === "fcharset" && state.fontTable) {
816 const codePage = FONT_CODE_PAGES.get(value);
817 if (value === 1) fonts.delete(state.font);
818 else if (codePage) fonts.set(state.font, new TextDecoder(codePage));
819 } else if (control === "cpg" && state.fontTable && !state.fontFile) {
820 const codePage = rtfCodePage(value);
821 if (codePage) fonts.set(state.font, new TextDecoder(codePage));
822 }
823 if (control === "deleted") state.deleted = value !== 0;
824 else if (control === "v") state.hiddenText = value !== 0;
825 else if (control === "plain") {
826 state.deleted = false;
827 state.hiddenText = false;
828 state.font = defaultFont;
829 }
830 if (control === "mac") state.decoder = new TextDecoder("macintosh");
831 else if (control === "ansicpg") {
832 const label = rtfCodePage(value);
833 if (!label) throw new Error("Unsupported RTF code page");
834 state.decoder = new TextDecoder(label);
835 } else if (control === "uc") {
836 if (!Number.isSafeInteger(value) || value < 0)
837 throw new Error("Invalid RTF fallback count");
838 state.uc = value;
839 } else if (control === "u") {
840 if (!hidden()) yield String.fromCharCode(value < 0 ? value + 65536 : value);
841 fallback = state.uc;
842 } else if (!hidden() && ["par", "line", "sect", "page", "column"].includes(control))
843 yield "\n";
844 else if (!hidden() && control === "tab") yield "\t";
845 // Table structure survives tracked deletions; only the deleted cell text is dropped.
846 else if (!state.skip && control === "row") yield "\n";
847 else if (!state.skip && control === "cell") yield "\t";
848 else if (!hidden() && symbols.has(control)) yield symbols.get(control)!;
849 } else {
850 i++;
851 if (fallback) fallback--;
852 else if (!hidden() && ["\\", "{", "}"].includes(rest[0]!))
853 yield* emitByte(rest[0]!.charCodeAt(0));
854 else {
855 yield* flushBytes();
856 if (rest[0] === "*") state.skip = true;
857 // A backslash before a line break is \par; TextEdit ends paragraphs this way.
858 else if (!hidden() && (rest[0] === "\n" || rest[0] === "\r")) yield "\n";
859 else if (!hidden() && symbols.has(rest[0]!)) yield symbols.get(rest[0]!)!;
860 }
861 }
862 } else if (char !== "\n" && char !== "\r") {
863 if (fallback) fallback--;
864 else if (!hidden()) yield* emitByte(char.charCodeAt(0));
865 }
866 }
867 yield* flushBytes();
868}
869
870async function* document(path: string, extension: string): AsyncGenerator<TextPart, void> {
871 if ((await NodeFSP.stat(path)).size > MAX_INPUT) throw new Truncation("Input byte limit");
872 if (extension === ".ipynb") yield* notebook(await NodeFSP.readFile(path, "utf8"));
873 else if (extension === ".rtf") yield* rtf((await NodeFSP.readFile(path)).toString("latin1"));
874 else {
875 const files = await archive(path);
876 // OPC part names compare case-insensitively for ASCII letters; exact names win.
877 const foldAscii = (name: string) => name.replaceAll(/[A-Z]/gu, (char) => char.toLowerCase());
878 const folded = new Map<string, string>();
879 for (const name of files.keys())
880 if (!folded.has(foldAscii(name))) folded.set(foldAscii(name), name);
881 const part = (name: string) => (files.has(name) ? name : (folded.get(foldAscii(name)) ?? name));
882 const has = (name: string) => files.has(part(name));
883 const notes: string[] = [];
884 const skip = (name: string) =>
885 notes.push(`\n[Skipped document part: ${name} (missing or invalid XML).]\n`);
886 const read = (name: string): XmlNode => {
887 try {
888 const data = files.get(part(name));
889 if (!data) throw new Error("Missing document part");
890 return xml(data, extension);
891 } catch (error) {
892 if (error instanceof Truncation) throw error;
893 skip(name);
894 return { name: "root", attrs: {}, children: [] };
895 }
896 };
897 const partRels = (name: string) =>
898 NodePath.posix.join(
899 NodePath.posix.dirname(name),
900 "_rels",
901 `${NodePath.posix.basename(name)}.rels`,
902 );
903 const relations = (name: string) =>
904 new Map(
905 [...all(read(name), "Relationship")]
906 .filter((rel) => rel.attrs.TargetMode !== "External")
907 .map((rel) => [rel.attrs.Id, rel.attrs]),
908 );
909 // The package relationship names the main part; Word for the web saves word/document2.xml.
910 const mainPart = (fallback: string) => {
911 const target = has("_rels/.rels")
912 ? [...all(read("_rels/.rels"), "Relationship")].find(
913 (rel) =>
914 rel.attrs.Type?.endsWith("/officeDocument") && rel.attrs.TargetMode !== "External",
915 )?.attrs.Target
916 : undefined;
917 const main = target && NodePath.posix.normalize(target).replace(/^\//, "");
918 return main && has(main) ? main : fallback;
919 };
920 if (extension === ".docx") {
921 yield* paragraphs(read(mainPart("word/document.xml")));
922 } else if ([".odt", ".ods", ".odp"].includes(extension)) {
923 const content = read("content.xml");
924 if (extension === ".odt")
925 yield* paragraphs(
926 children(children(content)[0]).find((child) => child.name === "body") ?? content,
927 );
928 else {
929 let index = 0;
930 for (const part of all(content, extension === ".ods" ? "table" : "page")) {
931 yield extension === ".ods"
932 ? `\n\n## Sheet: ${part.attrs.name ?? "Untitled"}\n`
933 : `\n\n## Slide ${++index}\n`;
934 if (extension === ".ods") {
935 yield* table(part);
936 continue;
937 }
938 const notes = children(part).find((child) => child.name === "notes");
939 yield* paragraphs({
940 ...part,
941 children: part.children.filter((child) => child !== notes),
942 });
943 if (notes && hasCellText(notes)) {
944 yield "\nNotes:\n";
945 yield* paragraphs(notes);
946 }
947 }
948 }
949 } else if (extension === ".xlsx") {
950 const workbookPath = mainPart("xl/workbook.xml");
951 const workbookDir = NodePath.posix.dirname(workbookPath);
952 const resolveWorkbookPart = (target: string) =>
953 NodePath.posix.resolve(`/${workbookDir}`, target).slice(1);
954 const workbook = read(workbookPath);
955 const rels = relations(partRels(workbookPath));
956 const workbookRelations = [...rels.values()];
957 const workbookPartPath = (part: string) => {
958 const target = workbookRelations.find((rel) => rel.Type?.endsWith(`/${part}`))?.Target;
959 return resolveWorkbookPart(target || `${part}.xml`);
960 };
961 const dateSystem = ["1", "true"].includes(
962 all(workbook, "workbookPr").next().value?.attrs.date1904 ?? "",
963 )
964 ? "1904"
965 : "1900";
966 const stylesPath = workbookPartPath("styles");
967 const styles = has(stylesPath) ? read(stylesPath) : undefined;
968 const customFormats = new Map(
969 styles
970 ? [...all(styles, "numFmt")].map((node) => [node.attrs.numFmtId, node.attrs.formatCode])
971 : [],
972 );
973 const cellFormats = styles ? all(styles, "cellXfs").next().value : undefined;
974 const formats = cellFormats ? children(cellFormats) : [];
975 const sharedPath = workbookPartPath("sharedStrings");
976 const strings = has(sharedPath) ? [...all(read(sharedPath), "si")] : [];
977 const populatedStrings = strings.map(hasCellText);
978 for (const sheet of all(workbook, "sheet")) {
979 yield `\n## Sheet: ${sheet.attrs.name}\n`;
980 const target = rels.get(sheet.attrs["r:id"] ?? sheet.attrs.id)?.Target;
981 if (!target) {
982 skip(`sheet relationship ${sheet.attrs.name}`);
983 continue;
984 }
985 const name = resolveWorkbookPart(target);
986 const populated = (cell: XmlNode) => {
987 const value = all(cell, "v").next().value;
988 if (cell.attrs.t === "s") {
989 const raw = value?.children.find((child) => typeof child === "string")?.trim();
990 return !!raw && !!populatedStrings[Number(raw)];
991 }
992 if (cell.attrs.t === "inlineStr") return hasCellText(cell);
993 if (value && hasCellText(value)) return true;
994 for (const formula of all(cell, "f")) if (hasCellText(formula)) return true;
995 return false;
996 };
997 let rowCount = 0;
998 for (const row of all(read(name), "row")) {
999 const cells: Array<XmlNode | undefined> = [];
1000 let nextColumn = 0;
1001 let columnsTruncated = false;
1002 for (const cell of children(row).filter((node) => node.name === "c")) {
1003 const letters = cell.attrs.r?.match(/^[A-Z]+/)?.[0];
1004 const column = letters
1005 ? [...letters].reduce((n, char) => n * 26 + char.charCodeAt(0) - 64, 0) - 1
1006 : nextColumn;
1007 nextColumn = column + 1;
1008 if (!populated(cell)) continue;
1009 if (column >= 512) {
1010 columnsTruncated = true;
1011 continue;
1012 }
1013 cells[column] = cell;
1014 }
1015 if (!cells.length && !columnsTruncated) continue;
1016 if (++rowCount > 10_000) throw new Truncation("Row limit");
1017 for (const [column, cell] of cells.entries()) {
1018 if (column) yield "\t";
1019 if (!cell) continue;
1020 const value = all(cell, "v").next().value;
1021 const raw = value?.children.find((child) => typeof child === "string") ?? "";
1022 if (cell.attrs.t === "s") {
1023 const shared = strings[Number(raw)];
1024 if (shared) yield* inCell(xstringText(shared));
1025 } else if (cell.attrs.t === "inlineStr") yield* inCell(xstringText(cell));
1026 else if (cell.attrs.t === "b" && (raw.trim() === "0" || raw.trim() === "1"))
1027 yield* inCell([raw.trim() === "1" ? "true" : "false"]);
1028 else {
1029 if (value && hasCellText(value)) yield* inCell(xstringText(value));
1030 else for (const formula of all(cell, "f")) yield* inCell(text(formula));
1031 const formatId = formats[Number(cell.attrs.s ?? 0)]?.attrs.numFmtId;
1032 const format = formatId ? customFormats.get(formatId) : undefined;
1033 if (
1034 (cell.attrs.t === undefined || cell.attrs.t === "n") &&
1035 raw.trim() &&
1036 formatId &&
1037 formatId !== "0"
1038 )
1039 yield ` [Excel numFmtId=${formatId}${format ? `; format=${format}` : ""}; date system ${dateSystem}]`;
1040 }
1041 }
1042 yield "\n";
1043 if (columnsTruncated) throw new Truncation("Column limit");
1044 }
1045 }
1046 } else if (extension === ".pptx") {
1047 const presentationPath = mainPart("ppt/presentation.xml");
1048 const presentationDir = NodePath.posix.dirname(presentationPath);
1049 const rels = relations(partRels(presentationPath));
1050 const [presentation] = children(read(presentationPath));
1051 const slideList = children(presentation).find((node) => node.name === "sldIdLst");
1052 const inheritedAttributes = { ...presentation?.attrs, ...slideList?.attrs };
1053 let index = 0;
1054 for (const slide of children(slideList).filter((node) => node.name === "sldId")) {
1055 yield `\n\n## Slide ${++index}\n`;
1056 const target = rels.get(slideRelationshipId(slide, inheritedAttributes))?.Target;
1057 if (!target) {
1058 skip(`slide relationship ${index}`);
1059 continue;
1060 }
1061 const name = NodePath.posix.resolve(`/${presentationDir}`, target).slice(1);
1062 yield* paragraphs(read(name));
1063 const slideRels = partRels(name);
1064 if (!has(slideRels)) continue;
1065 for (const rel of all(read(slideRels), "Relationship")) {
1066 const target = rel.attrs.Target;
1067 if (
1068 !rel.attrs.Type?.endsWith("/notesSlide") ||
1069 rel.attrs.TargetMode === "External" ||
1070 !target
1071 )
1072 continue;
1073 const notesPage = withoutNotesPagePlaceholders(
1074 read(
1075 target.startsWith("/")
1076 ? target.slice(1)
1077 : NodePath.posix.join(NodePath.posix.dirname(name), target),
1078 ),
1079 );
1080 if (!hasCellText(notesPage)) continue;
1081 yield "Notes:\n";
1082 yield* paragraphs(notesPage);
1083 }
1084 }
1085 } else if (extension === ".epub") {
1086 let rootfile = all(read("META-INF/container.xml"), "rootfile").next().value?.attrs[
1087 "full-path"
1088 ];
1089 if (!rootfile) {
1090 if (!notes.length) skip("EPUB package");
1091 yield* notes;
1092 return;
1093 }
1094 try {
1095 const decoded = decodeURIComponent(rootfile);
1096 if (files.has(decoded)) rootfile = decoded;
1097 } catch {}
1098 const packageXml = read(rootfile);
1099 const items = new Map(
1100 [...all(packageXml, "item")].map((item) => [item.attrs.id, item.attrs.href]),
1101 );
1102 let index = 0;
1103 for (const item of all(packageXml, "itemref")) {
1104 yield `\n\n## Chapter ${++index}\n`;
1105 const href = items.get(item.attrs.idref);
1106 if (!href) {
1107 skip(`chapter ${index}`);
1108 continue;
1109 }
1110 let decoded: string;
1111 try {
1112 decoded = decodeURIComponent(href.split(/[?#]/, 1)[0]!);
1113 } catch {
1114 skip(`chapter ${index}`);
1115 continue;
1116 }
1117 const name = NodePath.posix.normalize(
1118 NodePath.posix.join(NodePath.posix.dirname(rootfile), decoded),
1119 );
1120 yield* paragraphs(read(name));
1121 }
1122 } else throw new Error("Unsupported document");
1123 yield* notes;
1124 }
1125}
1126
1127// Undefined when the text holds only spaces and tabs, so the line state carries over.
1128function endsMidLine(text: string) {
1129 let index = text.length - 1;
1130 while (text[index] === " " || text[index] === "\t") index--;
1131 return index < 0 ? undefined : text[index] !== "\n";
1132}
1133
1134export async function extractDocumentText(path: string, extension: string): Promise<string> {
1135 let result = "";
1136 let remaining = MAX_OUTPUT;
1137 let cellDepth = 0;
1138 let started = false;
1139 let space = false;
1140 let midLine = false;
1141 let pendingThematicBreak: string | undefined;
1142 let endsWithWord = false;
1143 let afterImageDescription = false;
1144 let truncated = false;
1145 try {
1146 // Charge raw text before normalization so repeated whitespace also exhausts the budget.
1147 for await (let part of document(path, extension)) {
1148 if (part === CELL_START) {
1149 if (cellDepth++ === 0) {
1150 started = false;
1151 space = false;
1152 } else if (started) space = true;
1153 continue;
1154 }
1155 if (part === CELL_END) {
1156 remaining -= pendingThematicBreak?.length ?? 0;
1157 pendingThematicBreak = undefined;
1158 cellDepth--;
1159 if (cellDepth > 0 && started) space = true;
1160 continue;
1161 }
1162 if (part === THEMATIC_BREAK) {
1163 if (midLine) pendingThematicBreak ??= "";
1164 continue;
1165 }
1166 if (part === LINE_START) {
1167 // A list starts its own line unless the text before it already ended one.
1168 if (!midLine) continue;
1169 part = "\n";
1170 }
1171 let raw: string;
1172 let isImageDescription = false;
1173 if (typeof part === "string") raw = part;
1174 else if ("imageDescription" in part) {
1175 raw = part.imageDescription;
1176 isImageDescription = true;
1177 } else {
1178 if (started) continue;
1179 raw = part.fallback;
1180 }
1181 if (pendingThematicBreak !== undefined) {
1182 const next = pendingThematicBreak + raw;
1183 const hasContent = /[^ \t]/u.test(raw);
1184 // Inline markup can split significant indentation across chunks.
1185 if (!hasContent && next.length < remaining) {
1186 pendingThematicBreak = next;
1187 continue;
1188 }
1189 raw = hasContent && !/^[ \t]*\n/u.test(raw) ? "\n" + next : next;
1190 pendingThematicBreak = undefined;
1191 }
1192 // Resolve image boundaries here, after inline markup has been flattened.
1193 // Pending cell whitespace has already used its share of the output budget.
1194 if (
1195 (isImageDescription || afterImageDescription) &&
1196 endsWithWord &&
1197 !(cellDepth > 0 && started && space) &&
1198 /^\u00ad*[\p{L}\p{M}\p{N}_]/u.test(raw)
1199 )
1200 raw = " " + raw;
1201 let value = raw.slice(0, remaining).replaceAll("\0", "");
1202 remaining -= Math.min(raw.length, remaining);
1203 if (cellDepth) {
1204 value = value.replaceAll(/\s+/g, " ");
1205 const trimmed = value.trim();
1206 if (trimmed) {
1207 const separator = started && (space || value.startsWith(" ")) ? " " : "";
1208 started = true;
1209 midLine = true;
1210 space = value.endsWith(" ");
1211 value = separator + trimmed;
1212 } else {
1213 space = value.endsWith(" ") || (!value && space);
1214 value = "";
1215 }
1216 } else {
1217 midLine = endsMidLine(value) ?? midLine;
1218 }
1219 result += value;
1220 if (extension === ".epub") {
1221 // Soft hyphens stay in the output but do not decide where a visible word ends.
1222 let end = value.length;
1223 while (value[end - 1] === "\u00ad") end--;
1224 if (end > 0) {
1225 endsWithWord = /[\p{L}\p{M}\p{N}_]$/u.test(value.slice(Math.max(0, end - 2), end));
1226 afterImageDescription = isImageDescription;
1227 }
1228 }
1229 if (remaining === 0) throw new Truncation("Output budget");
1230 }
1231 } catch (error) {
1232 if (!(error instanceof Truncation)) throw error;
1233 truncated = true;
1234 }
1235 result = result.replaceAll(/\n(?:[ \t]*\n){2,}/g, "\n\n").trim();
1236 if (!result && !truncated) throw new Error("No text extracted");
1237 return truncated ? result.replace(/[\uD800-\uDBFF]$/, "").trimEnd() + TRUNCATED : result;
1238}