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 yield THEMATIC_BREAK;
338 const style =
339 all(child, "pStyle", ["pPrChange", "txbxContent"]).next().value?.attrs.val ?? "";
340 const level =
341 child.name === "h"
342 ? Number(child.attrs["outline-level"]) || 1
343 : /^h[1-6]$/.test(child.name)
344 ? Number(child.name[1])
345 : Number(style.match(/^Heading([1-6])$/i)?.[1]) || 0;
346 if (level) yield `${"#".repeat(Math.min(6, level))} `;
347 yield* text(child);
348 yield "\n";
349 } else if (
350 ["blockquote", "figcaption", "aside", "address"].includes(child.name) &&
351 child.hasText
352 ) {
353 yield LINE_START;
354 yield* paragraphs(child);
355 yield LINE_START;
356 } else {
357 if (["ol", "ul", "dl"].includes(child.name)) {
358 if (!child.hasText) continue;
359 yield LINE_START;
360 }
361 const block = ["li", "div", "section", "dt", "dd"].includes(child.name);
362 // Like a thematic break, a nested block starts a new line once its content arrives.
363 if (block) yield THEMATIC_BREAK;
364 yield* paragraphs(child);
365 if (block) yield "\n";
366 }
367 }
368}
369// A notes page also holds the slide image, slide number, date, header and footer placeholders.
370const NOTES_PAGE_PLACEHOLDERS = new Set(["sldImg", "sldNum", "dt", "hdr", "ftr"]);
371const isNotesPagePlaceholder = (node: XmlNode) =>
372 node.name === "sp" && NOTES_PAGE_PLACEHOLDERS.has(all(node, "ph").next().value?.attrs.type ?? "");
373function withoutNotesPagePlaceholders(node: XmlNode): XmlNode {
374 return {
375 ...node,
376 children: node.children
377 .filter((child) => typeof child === "string" || !isNotesPagePlaceholder(child))
378 .map((child) => (typeof child === "string" ? child : withoutNotesPagePlaceholders(child))),
379 };
380}
381function* inCell(parts: Iterable<TextPart>): Generator<TextPart, void> {
382 yield CELL_START;
383 yield* parts;
384 yield CELL_END;
385}
386function repeatCount(value: string | undefined): number {
387 if (value === undefined) return 1;
388 if (!/^[0-9]+$/.test(value) || Number(value) < 1) throw new Error("Invalid repeat count");
389 return Number(value);
390}
391function odfValue(cell: XmlNode): string {
392 const type = cell.attrs["office:value-type"] ?? cell.attrs["value-type"];
393 const attr = (name: string) => cell.attrs[`office:${name}`] ?? cell.attrs[name] ?? "";
394 switch (type) {
395 case "void":
396 return "";
397 case "string":
398 return attr("string-value");
399 case "boolean":
400 return attr("boolean-value");
401 case "date":
402 return attr("date-value");
403 case "time":
404 return attr("time-value");
405 case "currency":
406 return attr("value").trim() ? `${attr("value")} ${attr("currency")}`.trim() : "";
407 case "percentage":
408 return attr("value").trim() ? `${attr("value")} [ODF value-type=percentage]` : "";
409 default:
410 return attr("value");
411 }
412}
413const covered = (cell: XmlNode) => cell.name === "covered-table-cell";
414function hasCellText(cell: XmlNode): boolean {
415 if (covered(cell)) return false;
416 if (cell.imageDescription !== undefined || odfValue(cell).trim() || cell.name === "noBreakHyphen")
417 return true;
418 // Space markers can have enormous repeat counts; emptiness never requires expanding them.
419 if (HIDDEN.has(cell.name) || cell.spaceCount !== undefined) return false;
420 return cell.children.some((child) =>
421 typeof child === "string" ? !!child.trim() : hasCellText(child),
422 );
423}
424function epubSpan(value: string | undefined) {
425 const digits = value?.match(/^[\t\n\f\r ]*\+?([0-9]+)/)?.[1];
426 return digits === undefined ? 1 : Number(digits);
427}
428
429function* epubTable(node: XmlNode): Generator<TextPart, void> {
430 const occupiedUntil = new Uint32Array(512);
431 let rowIndex = 0;
432 let rowCount = 0;
433 for (const part of children(node)) {
434 const rowGroup = ["thead", "tbody", "tfoot"].includes(part.name);
435 if (!rowGroup && part.name !== "tr") continue;
436 if (rowGroup) occupiedUntil.fill(0);
437 for (const row of rowGroup ? children(part) : [part]) {
438 if (row.name !== "tr") continue;
439 rowIndex++;
440 const cells = children(row)
441 .filter((cell) => cell.name === "td" || cell.name === "th")
442 .map((cell) => ({ cell, rowSpan: epubSpan(cell.attrs.rowspan) }));
443 const lastText = cells.findLastIndex(({ cell }) => hasCellText(cell));
444 if (lastText >= 0 && ++rowCount > 10_000) throw new Truncation("Row limit");
445 if (lastText >= 0 && rowCount === 1) yield LINE_START;
446 // An empty cell can still reserve columns in later rows.
447 const lastCell = Math.max(
448 lastText,
449 cells.findLastIndex(({ rowSpan }) => rowSpan !== 1),
450 );
451 let column = 0;
452 let lastColumn = 0;
453 for (let index = 0; index <= lastCell; index++) {
454 const { cell, rowSpan } = cells[index]!;
455 while ((occupiedUntil[column] ?? 0) > rowIndex) column++;
456 const width = Math.max(1, Math.min(1000, epubSpan(cell.attrs.colspan)));
457 const endColumn = column + width;
458 const inBounds = column < occupiedUntil.length;
459 if (!inBounds && hasCellText(cell)) throw new Truncation("Column limit");
460 if (rowSpan !== 1) {
461 // A zero row span covers the rest of the row group.
462 const endRow = rowSpan === 0 ? 0xffffffff : rowIndex + Math.min(65_534, rowSpan);
463 const trackedEnd = Math.min(endColumn, occupiedUntil.length);
464 for (let slot = column; slot < trackedEnd; slot++) {
465 occupiedUntil[slot] = Math.max(occupiedUntil[slot]!, endRow);
466 }
467 }
468 if (inBounds && index <= lastText) {
469 if (column > lastColumn) yield "\t".repeat(column - lastColumn);
470 yield CELL_START;
471 yield* paragraphs(cell);
472 yield { fallback: odfValue(cell) };
473 yield CELL_END;
474 lastColumn = column;
475 }
476 column = endColumn;
477 }
478 if (lastText >= 0) yield "\n";
479 }
480 if (rowGroup) occupiedUntil.fill(0);
481 }
482}
483
484function* table(node: XmlNode): Generator<TextPart, void> {
485 for (const caption of children(node)) {
486 if (caption.name !== "caption") continue;
487 yield LINE_START;
488 yield* paragraphs(caption);
489 yield LINE_START;
490 }
491 if (node.epubTable) {
492 yield* epubTable(node);
493 return;
494 }
495 let rowCount = 0;
496 for (const row of all(node, ["tr", "table-row"], ["caption"])) {
497 // Word nests a cell inside w:sdt when a content control wraps the whole cell.
498 const cells = [...all(row, ["tc", "table-cell", "covered-table-cell", "td", "th"])];
499 // ODS writers pad sheets with repeated empty rows and trailing cells.
500 while (cells.length && !hasCellText(cells.at(-1)!)) cells.pop();
501 if (!cells.length) continue;
502 const repeat = repeatCount(row.attrs["number-rows-repeated"]);
503 // Word emits no cells for the grid columns w:gridBefore skips at the start of a row.
504 const trPr = row.name === "tr" ? children(row).find((c) => c.name === "trPr") : undefined;
505 const before = trPr && children(trPr).find((c) => c.name === "gridBefore")?.attrs.val;
506 const skipped = before ? Math.max(0, Number.parseInt(before, 10) || 0) : 0;
507 for (let index = 0; index < repeat; index++) {
508 if (++rowCount > 10_000) throw new Truncation("Row limit");
509 let column = skipped;
510 let gap = skipped;
511 for (const cell of cells) {
512 const count = repeatCount(cell.attrs["number-columns-repeated"]);
513 // Word emits no cell for columns covered by w:gridSpan; pad before the next cell.
514 const tcPr = cell.name === "tc" ? children(cell).find((c) => c.name === "tcPr") : undefined;
515 const val = tcPr && children(tcPr).find((c) => c.name === "gridSpan")?.attrs.val;
516 const span = val ? Math.max(1, Number.parseInt(val, 10) || 1) : 1;
517 for (let i = 0; i < count; i++) {
518 column += span;
519 if (column > 512) throw new Truncation("Column limit");
520 if (gap) yield "\t".repeat(gap);
521 gap = span;
522 // LibreOffice hides the contents a merge covers; the cell still holds its column.
523 if (covered(cell)) continue;
524 yield CELL_START;
525 yield* paragraphs(cell);
526 yield { fallback: odfValue(cell) };
527 yield CELL_END;
528 }
529 }
530 yield "\n";
531 }
532 }
533}
534
535async function archive(path: string): Promise<Map<string, string>> {
536 const zip = await new Promise<Yauzl.ZipFile>((resolve, reject) =>
537 Yauzl.open(
538 path,
539 { lazyEntries: true, validateEntrySizes: true, strictFileNames: true },
540 (error, result) => (error || !result ? reject(error) : resolve(result)),
541 ),
542 );
543 const files = new Map<string, string>();
544 let expanded = 0;
545 let count = 0;
546 try {
547 await new Promise<void>((resolve, reject) => {
548 zip.on("error", reject);
549 zip.on("end", resolve);
550 zip.on("entry", (entry: Yauzl.Entry) => {
551 if (++count > 2048 || zip.entryCount > 2048) {
552 reject(new Truncation("Archive limit"));
553 return;
554 }
555 if (entry.generalPurposeBitFlag & 1) {
556 reject(new Error("Encrypted archive"));
557 return;
558 }
559 if (!/\.(xml|rels|xhtml|html|htm|opf|svg)$/i.test(entry.fileName)) {
560 zip.readEntry();
561 return;
562 }
563 if (
564 entry.uncompressedSize > MAX_EXPANDED ||
565 entry.uncompressedSize > Math.max(1024, entry.compressedSize * 200)
566 ) {
567 reject(new Truncation("Archive limit"));
568 return;
569 }
570 expanded += entry.uncompressedSize;
571 if (expanded > MAX_EXPANDED) {
572 reject(new Truncation("Expanded byte limit"));
573 return;
574 }
575 zip.openReadStream(entry, (error, stream) => {
576 if (error || !stream) {
577 reject(error);
578 return;
579 }
580 const buffers: Buffer[] = [];
581 let size = 0;
582 stream.on("error", reject);
583 stream.on("data", (chunk: Buffer) => {
584 size += chunk.length;
585 if (size > entry.uncompressedSize || size > MAX_EXPANDED) {
586 stream.destroy(new Truncation("Entry byte limit"));
587 return;
588 }
589 buffers.push(chunk);
590 });
591 stream.on("end", () => {
592 const data = Buffer.concat(buffers);
593 // XML's BOM and initial '<' bytes distinguish both UTF-16 byte orders.
594 const encoding =
595 (data[0] === 0xff && data[1] === 0xfe) || (data[0] === 0x3c && data[1] === 0)
596 ? "utf-16le"
597 : (data[0] === 0xfe && data[1] === 0xff) || (data[0] === 0 && data[1] === 0x3c)
598 ? "utf-16be"
599 : "utf-8";
600 files.set(entry.fileName, new TextDecoder(encoding).decode(data));
601 zip.readEntry();
602 });
603 });
604 });
605 zip.readEntry();
606 });
607 } finally {
608 zip.close();
609 }
610 return files;
611}
612
613const NOTEBOOK_CELL_TYPES = ["code", "markdown", "raw"];
614
615function* notebook(source: string): Generator<string, void> {
616 const book: unknown = JSON.parse(source);
617 if (!book || typeof book !== "object" || !("cells" in book) || !Array.isArray(book.cells))
618 throw new Error("Invalid notebook");
619 function* lines(value: unknown): Generator<string, void> {
620 if (typeof value === "string") yield value;
621 else if (Array.isArray(value))
622 for (const line of value) {
623 if (typeof line === "string") yield line;
624 }
625 }
626 function outputText(value: unknown, stream = false): string {
627 // Notebook fragments can split a terminal escape sequence or a CRLF pair.
628 const plain = NodeUtil.stripVTControlCharacters([...lines(value)].join(""));
629 return stream ? terminalOutputCollapseRedraws(plain) : plain;
630 }
631 for (const [index, cell] of book.cells.entries()) {
632 if (index >= 10_000) throw new Truncation("Notebook cell limit");
633 if (!cell || typeof cell !== "object") continue;
634 const cellType = "cell_type" in cell ? cell.cell_type : undefined;
635 const kind = NOTEBOOK_CELL_TYPES.find((type) => type === cellType) ?? "markdown";
636 yield `## Cell ${index + 1} (${kind})\n`;
637 if ("source" in cell) yield* lines(cell.source);
638 if ("outputs" in cell && Array.isArray(cell.outputs) && cell.outputs.length > 0) {
639 yield "\nOutput:\n";
640 for (const output of cell.outputs) {
641 if (!output || typeof output !== "object") continue;
642 if ("text" in output)
643 yield outputText(output.text, "output_type" in output && output.output_type === "stream");
644 else if (
645 "data" in output &&
646 output.data &&
647 typeof output.data === "object" &&
648 ("text/plain" in output.data || "text/markdown" in output.data)
649 ) {
650 const plain = outputText(
651 "text/plain" in output.data ? output.data["text/plain"] : undefined,
652 );
653 yield "text/markdown" in output.data && !plain.replaceAll("\0", "").trim()
654 ? outputText(output.data["text/markdown"])
655 : plain;
656 } else if ("output_type" in output && output.output_type === "error") {
657 if ("ename" in output) yield* lines(output.ename);
658 if ("evalue" in output) {
659 yield ": ";
660 yield* lines(output.evalue);
661 }
662 yield "\n";
663 if ("traceback" in output)
664 for (const line of lines(output.traceback)) {
665 yield NodeUtil.stripVTControlCharacters(line);
666 yield "\n";
667 }
668 }
669 yield "\n";
670 }
671 }
672 yield "\n\n";
673 }
674}
675
676const FONT_CODE_PAGES = new Map([
677 [0, "windows-1252"],
678 [77, "macintosh"],
679 [128, "shift_jis"],
680 [129, "euc-kr"],
681 [134, "gbk"],
682 [136, "big5"],
683 [161, "windows-1253"],
684 [162, "windows-1254"],
685 [163, "windows-1258"],
686 [177, "windows-1255"],
687 [178, "windows-1256"],
688 [186, "windows-1257"],
689 [204, "windows-1251"],
690 [222, "windows-874"],
691 [238, "windows-1250"],
692 [255, "ibm866"],
693]);
694
695const RTF_CODE_PAGES = new Map([
696 [0, "windows-1252"],
697 [866, "ibm866"],
698 [874, "windows-874"],
699 [932, "shift_jis"],
700 [936, "gbk"],
701 [949, "euc-kr"],
702 [950, "big5"],
703 [10000, "macintosh"],
704 [54936, "gb18030"],
705 [65001, "utf-8"],
706]);
707
708const rtfCodePage = (value: number) =>
709 RTF_CODE_PAGES.get(value) ?? (value >= 1250 && value <= 1258 ? `windows-${value}` : undefined);
710
711function* rtf(source: string): Generator<string, void> {
712 if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document");
713 let state = {
714 skip: false,
715 deleted: false,
716 hiddenText: false,
717 uc: 1,
718 font: 0,
719 fontTable: false,
720 fontFile: false,
721 decoder: new TextDecoder("windows-1252"),
722 };
723 const stack: Array<typeof state> = [];
724 // A font's \cpg, else its \fcharset, not the document code page, encodes the bytes written in
725 // that font. A \cpg inside \fontfile encodes the font's file name instead.
726 const fonts = new Map<number, typeof state.decoder>();
727 let defaultFont = 0;
728 const decoder = () => fonts.get(state.font) ?? state.decoder;
729 const hidden = () => state.skip || state.deleted || state.hiddenText;
730 let encoded: Uint8Array | undefined;
731 let encodedLength = 0;
732 function* flushBytes(): Generator<string, void> {
733 if (!encodedLength) return;
734 const chunk = encoded!.subarray(0, encodedLength);
735 encodedLength = 0;
736 yield decoder().decode(chunk);
737 }
738 function* emitByte(byte: number): Generator<string, void> {
739 // No supported multibyte code page uses bytes below 0x30 as trail bytes.
740 if ((!encodedLength && byte < 128) || (encodedLength && byte < 0x30)) {
741 yield* flushBytes();
742 yield String.fromCharCode(byte);
743 return;
744 }
745 // GB18030 spends up to 4 bytes per UTF-16 unit, so a full buffer decodes past MAX_OUTPUT.
746 encoded ??= new Uint8Array(Math.min(source.length, MAX_OUTPUT * 4 + 4));
747 if (encodedLength === encoded.length) yield* flushBytes();
748 encoded[encodedLength++] = byte;
749 }
750 const symbols = new Map([
751 ["endash", "–"],
752 ["emdash", characterEntities.mdash],
753 ["enspace", "\u2002"],
754 ["emspace", "\u2003"],
755 ["qmspace", "\u2005"],
756 ["lquote", "‘"],
757 ["rquote", "’"],
758 ["ldblquote", "“"],
759 ["rdblquote", "”"],
760 ["bullet", "•"],
761 ["zwj", "\u200d"],
762 ["zwnj", "\u200c"],
763 ["ltrmark", "\u200e"],
764 ["rtlmark", "\u200f"],
765 ["~", "\u00a0"],
766 ["_", "\u2011"],
767 ["-", ""],
768 ]);
769 let fallback = 0;
770 for (let i = 0; i < source.length; i++) {
771 const char = source[i]!;
772 if (char === "{" || char === "}") {
773 yield* flushBytes();
774 fallback = 0;
775 }
776 if (char === "{") {
777 stack.push({ ...state });
778 if (stack.length > 128) throw new Truncation("RTF depth limit");
779 } else if (char === "}") state = stack.pop() ?? state;
780 else if (char === "\\") {
781 const rest = source.slice(i + 1, i + 80);
782 const hex = /^'([0-9a-f]{2})/i.exec(rest);
783 const word = /^([a-z]+)(-?\d+)? ?/i.exec(rest);
784 if (hex) {
785 if (fallback) fallback--;
786 else if (!hidden()) yield* emitByte(Number.parseInt(hex[1]!, 16));
787 i += 3;
788 } else if (word) {
789 i += word[0].length;
790 const control = word[1]!;
791 const value = Number(word[2]);
792 if (control === "bin") {
793 if (!Number.isSafeInteger(value) || value < 0)
794 throw new Error("Invalid RTF binary length");
795 i += value;
796 }
797 if (fallback) {
798 fallback--;
799 continue;
800 }
801 yield* flushBytes();
802 if (
803 [
804 "fonttbl",
805 "colortbl",
806 "stylesheet",
807 "info",
808 "pict",
809 "object",
810 "fldinst",
811 "header",
812 "headerf",
813 "headerl",
814 "headerr",
815 "footer",
816 "footerf",
817 "footerl",
818 "footerr",
819 ].includes(control)
820 )
821 state.skip = true;
822 if (control === "fonttbl") state.fontTable = true;
823 else if (control === "fontfile") state.fontFile = true;
824 else if (control === "deff") state.font = defaultFont = value;
825 else if (control === "f") {
826 state.font = value;
827 if (state.fontTable) fonts.delete(value);
828 } else if (control === "fcharset" && state.fontTable) {
829 const codePage = FONT_CODE_PAGES.get(value);
830 if (value === 1) fonts.delete(state.font);
831 else if (codePage) fonts.set(state.font, new TextDecoder(codePage));
832 } else if (control === "cpg" && state.fontTable && !state.fontFile) {
833 const codePage = rtfCodePage(value);
834 if (codePage) fonts.set(state.font, new TextDecoder(codePage));
835 }
836 if (control === "deleted") state.deleted = value !== 0;
837 else if (control === "v") state.hiddenText = value !== 0;
838 else if (control === "plain") {
839 state.deleted = false;
840 state.hiddenText = false;
841 state.font = defaultFont;
842 }
843 if (control === "mac") state.decoder = new TextDecoder("macintosh");
844 else if (control === "ansicpg") {
845 const label = rtfCodePage(value);
846 if (!label) throw new Error("Unsupported RTF code page");
847 state.decoder = new TextDecoder(label);
848 } else if (control === "uc") {
849 if (!Number.isSafeInteger(value) || value < 0)
850 throw new Error("Invalid RTF fallback count");
851 state.uc = value;
852 } else if (control === "u") {
853 if (!hidden()) yield String.fromCharCode(value < 0 ? value + 65536 : value);
854 fallback = state.uc;
855 } else if (!hidden() && ["par", "line", "sect", "page", "column"].includes(control))
856 yield "\n";
857 else if (!hidden() && control === "tab") yield "\t";
858 // Table structure survives tracked deletions; only the deleted cell text is dropped.
859 else if (!state.skip && control === "row") yield "\n";
860 else if (!state.skip && control === "cell") yield "\t";
861 else if (!hidden() && symbols.has(control)) yield symbols.get(control)!;
862 } else {
863 i++;
864 if (fallback) fallback--;
865 else if (!hidden() && ["\\", "{", "}"].includes(rest[0]!))
866 yield* emitByte(rest[0]!.charCodeAt(0));
867 else {
868 yield* flushBytes();
869 if (rest[0] === "*") state.skip = true;
870 // A backslash before a line break is \par; TextEdit ends paragraphs this way.
871 else if (!hidden() && (rest[0] === "\n" || rest[0] === "\r")) yield "\n";
872 else if (!hidden() && symbols.has(rest[0]!)) yield symbols.get(rest[0]!)!;
873 }
874 }
875 } else if (char !== "\n" && char !== "\r") {
876 if (fallback) fallback--;
877 else if (!hidden()) yield* emitByte(char.charCodeAt(0));
878 }
879 }
880 yield* flushBytes();
881}
882
883async function* document(path: string, extension: string): AsyncGenerator<TextPart, void> {
884 if ((await NodeFSP.stat(path)).size > MAX_INPUT) throw new Truncation("Input byte limit");
885 if (extension === ".ipynb") yield* notebook(await NodeFSP.readFile(path, "utf8"));
886 else if (extension === ".rtf") yield* rtf((await NodeFSP.readFile(path)).toString("latin1"));
887 else {
888 const files = await archive(path);
889 // OPC part names compare case-insensitively for ASCII letters; exact names win.
890 const foldAscii = (name: string) => name.replaceAll(/[A-Z]/gu, (char) => char.toLowerCase());
891 const folded = new Map<string, string>();
892 for (const name of files.keys())
893 if (!folded.has(foldAscii(name))) folded.set(foldAscii(name), name);
894 const part = (name: string) => (files.has(name) ? name : (folded.get(foldAscii(name)) ?? name));
895 const has = (name: string) => files.has(part(name));
896 const notes: string[] = [];
897 const skip = (name: string) =>
898 notes.push(`\n[Skipped document part: ${name} (missing or invalid XML).]\n`);
899 const read = (name: string): XmlNode => {
900 try {
901 const data = files.get(part(name));
902 if (!data) throw new Error("Missing document part");
903 return xml(data, extension);
904 } catch (error) {
905 if (error instanceof Truncation) throw error;
906 skip(name);
907 return { name: "root", attrs: {}, children: [] };
908 }
909 };
910 const partRels = (name: string) =>
911 NodePath.posix.join(
912 NodePath.posix.dirname(name),
913 "_rels",
914 `${NodePath.posix.basename(name)}.rels`,
915 );
916 const relations = (name: string) =>
917 new Map(
918 [...all(read(name), "Relationship")]
919 .filter((rel) => rel.attrs.TargetMode !== "External")
920 .map((rel) => [rel.attrs.Id, rel.attrs]),
921 );
922 // The package relationship names the main part; Word for the web saves word/document2.xml.
923 const mainPart = (fallback: string) => {
924 const target = has("_rels/.rels")
925 ? [...all(read("_rels/.rels"), "Relationship")].find(
926 (rel) =>
927 rel.attrs.Type?.endsWith("/officeDocument") && rel.attrs.TargetMode !== "External",
928 )?.attrs.Target
929 : undefined;
930 const main = target && NodePath.posix.normalize(target).replace(/^\//, "");
931 return main && has(main) ? main : fallback;
932 };
933 if (extension === ".docx") {
934 yield* paragraphs(read(mainPart("word/document.xml")));
935 } else if ([".odt", ".ods", ".odp"].includes(extension)) {
936 const content = read("content.xml");
937 if (extension === ".odt")
938 yield* paragraphs(
939 children(children(content)[0]).find((child) => child.name === "body") ?? content,
940 );
941 else {
942 let index = 0;
943 for (const part of all(content, extension === ".ods" ? "table" : "page")) {
944 yield extension === ".ods"
945 ? `\n\n## Sheet: ${part.attrs.name ?? "Untitled"}\n`
946 : `\n\n## Slide ${++index}\n`;
947 if (extension === ".ods") {
948 yield* table(part);
949 continue;
950 }
951 const notes = children(part).find((child) => child.name === "notes");
952 yield* paragraphs({
953 ...part,
954 children: part.children.filter((child) => child !== notes),
955 });
956 if (notes && hasCellText(notes)) {
957 yield "\nNotes:\n";
958 yield* paragraphs(notes);
959 }
960 }
961 }
962 } else if (extension === ".xlsx") {
963 const workbookPath = mainPart("xl/workbook.xml");
964 const workbookDir = NodePath.posix.dirname(workbookPath);
965 const resolveWorkbookPart = (target: string) =>
966 NodePath.posix.resolve(`/${workbookDir}`, target).slice(1);
967 const workbook = read(workbookPath);
968 const rels = relations(partRels(workbookPath));
969 const workbookRelations = [...rels.values()];
970 const workbookPartPath = (part: string) => {
971 const target = workbookRelations.find((rel) => rel.Type?.endsWith(`/${part}`))?.Target;
972 return resolveWorkbookPart(target || `${part}.xml`);
973 };
974 const dateSystem = ["1", "true"].includes(
975 all(workbook, "workbookPr").next().value?.attrs.date1904 ?? "",
976 )
977 ? "1904"
978 : "1900";
979 const stylesPath = workbookPartPath("styles");
980 const styles = has(stylesPath) ? read(stylesPath) : undefined;
981 const customFormats = new Map(
982 styles
983 ? [...all(styles, "numFmt")].map((node) => [node.attrs.numFmtId, node.attrs.formatCode])
984 : [],
985 );
986 const cellFormats = styles ? all(styles, "cellXfs").next().value : undefined;
987 const formats = cellFormats ? children(cellFormats) : [];
988 const sharedPath = workbookPartPath("sharedStrings");
989 const strings = has(sharedPath) ? [...all(read(sharedPath), "si")] : [];
990 const populatedStrings = strings.map(hasCellText);
991 for (const sheet of all(workbook, "sheet")) {
992 yield `\n## Sheet: ${sheet.attrs.name}\n`;
993 const target = rels.get(sheet.attrs["r:id"] ?? sheet.attrs.id)?.Target;
994 if (!target) {
995 skip(`sheet relationship ${sheet.attrs.name}`);
996 continue;
997 }
998 const name = resolveWorkbookPart(target);
999 const populated = (cell: XmlNode) => {
1000 const value = all(cell, "v").next().value;
1001 if (cell.attrs.t === "s") {
1002 const raw = value?.children.find((child) => typeof child === "string")?.trim();
1003 return !!raw && !!populatedStrings[Number(raw)];
1004 }
1005 if (cell.attrs.t === "inlineStr") return hasCellText(cell);
1006 if (value && hasCellText(value)) return true;
1007 for (const formula of all(cell, "f")) if (hasCellText(formula)) return true;
1008 return false;
1009 };
1010 let rowCount = 0;
1011 for (const row of all(read(name), "row")) {
1012 const cells: Array<XmlNode | undefined> = [];
1013 let nextColumn = 0;
1014 let columnsTruncated = false;
1015 for (const cell of children(row).filter((node) => node.name === "c")) {
1016 const letters = cell.attrs.r?.match(/^[A-Z]+/)?.[0];
1017 const column = letters
1018 ? [...letters].reduce((n, char) => n * 26 + char.charCodeAt(0) - 64, 0) - 1
1019 : nextColumn;
1020 nextColumn = column + 1;
1021 if (!populated(cell)) continue;
1022 if (column >= 512) {
1023 columnsTruncated = true;
1024 continue;
1025 }
1026 cells[column] = cell;
1027 }
1028 if (!cells.length && !columnsTruncated) continue;
1029 if (++rowCount > 10_000) throw new Truncation("Row limit");
1030 for (const [column, cell] of cells.entries()) {
1031 if (column) yield "\t";
1032 if (!cell) continue;
1033 const value = all(cell, "v").next().value;
1034 const raw = value?.children.find((child) => typeof child === "string") ?? "";
1035 if (cell.attrs.t === "s") {
1036 const shared = strings[Number(raw)];
1037 if (shared) yield* inCell(xstringText(shared));
1038 } else if (cell.attrs.t === "inlineStr") yield* inCell(xstringText(cell));
1039 else if (cell.attrs.t === "b" && (raw.trim() === "0" || raw.trim() === "1"))
1040 yield* inCell([raw.trim() === "1" ? "true" : "false"]);
1041 else {
1042 if (value && hasCellText(value)) yield* inCell(xstringText(value));
1043 else for (const formula of all(cell, "f")) yield* inCell(text(formula));
1044 const formatId = formats[Number(cell.attrs.s ?? 0)]?.attrs.numFmtId;
1045 const format = formatId ? customFormats.get(formatId) : undefined;
1046 if (
1047 (cell.attrs.t === undefined || cell.attrs.t === "n") &&
1048 raw.trim() &&
1049 formatId &&
1050 formatId !== "0"
1051 )
1052 yield ` [Excel numFmtId=${formatId}${format ? `; format=${format}` : ""}; date system ${dateSystem}]`;
1053 }
1054 }
1055 yield "\n";
1056 if (columnsTruncated) throw new Truncation("Column limit");
1057 }
1058 }
1059 } else if (extension === ".pptx") {
1060 const presentationPath = mainPart("ppt/presentation.xml");
1061 const presentationDir = NodePath.posix.dirname(presentationPath);
1062 const rels = relations(partRels(presentationPath));
1063 const [presentation] = children(read(presentationPath));
1064 const slideList = children(presentation).find((node) => node.name === "sldIdLst");
1065 const inheritedAttributes = { ...presentation?.attrs, ...slideList?.attrs };
1066 let index = 0;
1067 for (const slide of children(slideList).filter((node) => node.name === "sldId")) {
1068 yield `\n\n## Slide ${++index}\n`;
1069 const target = rels.get(slideRelationshipId(slide, inheritedAttributes))?.Target;
1070 if (!target) {
1071 skip(`slide relationship ${index}`);
1072 continue;
1073 }
1074 const name = NodePath.posix.resolve(`/${presentationDir}`, target).slice(1);
1075 yield* paragraphs(read(name));
1076 const slideRels = partRels(name);
1077 if (!has(slideRels)) continue;
1078 for (const rel of all(read(slideRels), "Relationship")) {
1079 const target = rel.attrs.Target;
1080 if (
1081 !rel.attrs.Type?.endsWith("/notesSlide") ||
1082 rel.attrs.TargetMode === "External" ||
1083 !target
1084 )
1085 continue;
1086 const notesPage = withoutNotesPagePlaceholders(
1087 read(
1088 target.startsWith("/")
1089 ? target.slice(1)
1090 : NodePath.posix.join(NodePath.posix.dirname(name), target),
1091 ),
1092 );
1093 if (!hasCellText(notesPage)) continue;
1094 yield "Notes:\n";
1095 yield* paragraphs(notesPage);
1096 }
1097 }
1098 } else if (extension === ".epub") {
1099 let rootfile = all(read("META-INF/container.xml"), "rootfile").next().value?.attrs[
1100 "full-path"
1101 ];
1102 if (!rootfile) {
1103 if (!notes.length) skip("EPUB package");
1104 yield* notes;
1105 return;
1106 }
1107 try {
1108 const decoded = decodeURIComponent(rootfile);
1109 if (files.has(decoded)) rootfile = decoded;
1110 } catch {}
1111 const packageXml = read(rootfile);
1112 const items = new Map(
1113 [...all(packageXml, "item")].map((item) => [item.attrs.id, item.attrs.href]),
1114 );
1115 let index = 0;
1116 for (const item of all(packageXml, "itemref")) {
1117 yield `\n\n## Chapter ${++index}\n`;
1118 const href = items.get(item.attrs.idref);
1119 if (!href) {
1120 skip(`chapter ${index}`);
1121 continue;
1122 }
1123 let decoded: string;
1124 try {
1125 decoded = decodeURIComponent(href.split(/[?#]/, 1)[0]!);
1126 } catch {
1127 skip(`chapter ${index}`);
1128 continue;
1129 }
1130 const name = NodePath.posix.normalize(
1131 NodePath.posix.join(NodePath.posix.dirname(rootfile), decoded),
1132 );
1133 yield* paragraphs(read(name));
1134 }
1135 } else throw new Error("Unsupported document");
1136 yield* notes;
1137 }
1138}
1139
1140// Undefined when the text holds only spaces and tabs, so the line state carries over.
1141function endsMidLine(text: string) {
1142 let index = text.length - 1;
1143 while (text[index] === " " || text[index] === "\t") index--;
1144 return index < 0 ? undefined : text[index] !== "\n";
1145}
1146
1147export async function extractDocumentText(path: string, extension: string): Promise<string> {
1148 let result = "";
1149 let remaining = MAX_OUTPUT;
1150 let cellDepth = 0;
1151 let started = false;
1152 let space = false;
1153 let midLine = false;
1154 let pendingThematicBreak: string | undefined;
1155 let endsWithWord = false;
1156 let afterImageDescription = false;
1157 let truncated = false;
1158 try {
1159 // Charge raw text before normalization so repeated whitespace also exhausts the budget.
1160 for await (let part of document(path, extension)) {
1161 if (part === CELL_START) {
1162 if (cellDepth++ === 0) {
1163 started = false;
1164 space = false;
1165 } else if (started) space = true;
1166 continue;
1167 }
1168 if (part === CELL_END) {
1169 remaining -= pendingThematicBreak?.length ?? 0;
1170 pendingThematicBreak = undefined;
1171 cellDepth--;
1172 if (cellDepth > 0 && started) space = true;
1173 continue;
1174 }
1175 if (part === THEMATIC_BREAK) {
1176 if (midLine) pendingThematicBreak ??= "";
1177 continue;
1178 }
1179 if (part === LINE_START) {
1180 // A list starts its own line unless the text before it already ended one.
1181 if (!midLine) continue;
1182 part = "\n";
1183 }
1184 let raw: string;
1185 let isImageDescription = false;
1186 if (typeof part === "string") raw = part;
1187 else if ("imageDescription" in part) {
1188 raw = part.imageDescription;
1189 isImageDescription = true;
1190 } else {
1191 if (started) continue;
1192 raw = part.fallback;
1193 }
1194 if (pendingThematicBreak !== undefined) {
1195 const next = pendingThematicBreak + raw;
1196 const hasContent = /[^ \t]/u.test(raw);
1197 // Inline markup can split significant indentation across chunks.
1198 if (!hasContent && next.length < remaining) {
1199 pendingThematicBreak = next;
1200 continue;
1201 }
1202 raw = hasContent && !/^[ \t]*\n/u.test(raw) ? "\n" + next : next;
1203 pendingThematicBreak = undefined;
1204 }
1205 // Resolve image boundaries here, after inline markup has been flattened.
1206 // Pending cell whitespace has already used its share of the output budget.
1207 if (
1208 (isImageDescription || afterImageDescription) &&
1209 endsWithWord &&
1210 !(cellDepth > 0 && started && space) &&
1211 /^\u00ad*[\p{L}\p{M}\p{N}_]/u.test(raw)
1212 )
1213 raw = " " + raw;
1214 let value = raw.slice(0, remaining).replaceAll("\0", "");
1215 remaining -= Math.min(raw.length, remaining);
1216 if (cellDepth) {
1217 value = value.replaceAll(/\s+/g, " ");
1218 const trimmed = value.trim();
1219 if (trimmed) {
1220 const separator = started && (space || value.startsWith(" ")) ? " " : "";
1221 started = true;
1222 midLine = true;
1223 space = value.endsWith(" ");
1224 value = separator + trimmed;
1225 } else {
1226 space = value.endsWith(" ") || (!value && space);
1227 value = "";
1228 }
1229 } else {
1230 midLine = endsMidLine(value) ?? midLine;
1231 }
1232 result += value;
1233 if (extension === ".epub") {
1234 // Soft hyphens stay in the output but do not decide where a visible word ends.
1235 let end = value.length;
1236 while (value[end - 1] === "\u00ad") end--;
1237 if (end > 0) {
1238 endsWithWord = /[\p{L}\p{M}\p{N}_]$/u.test(value.slice(Math.max(0, end - 2), end));
1239 afterImageDescription = isImageDescription;
1240 }
1241 }
1242 if (remaining === 0) throw new Truncation("Output budget");
1243 }
1244 } catch (error) {
1245 if (!(error instanceof Truncation)) throw error;
1246 truncated = true;
1247 }
1248 result = result.replaceAll(/\n(?:[ \t]*\n){2,}/g, "\n\n").trim();
1249 if (!result && !truncated) throw new Error("No text extracted");
1250 return truncated ? result.replace(/[\uD800-\uDBFF]$/, "").trimEnd() + TRUNCATED : result;
1251}