Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { describe, expect, it } from "@effect/vitest";
7import * as Effect from "effect/Effect";
8import * as Deferred from "effect/Deferred";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as TestClock from "effect/testing/TestClock";
13import { vi } from "vite-plus/test";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import * as ServerConfig from "../config.ts";
16import * as DocumentText from "./DocumentText.ts";
17import { extractDocumentText } from "./documentTextWorker.ts";
18import * as Cleanup from "../orchestration-v2/ResourceCleanupService.ts";
19import * as TerminalManager from "../terminal/Manager.ts";
20import * as PreviewManager from "../preview/Manager.ts";
21import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
22import * as NodeZlib from "node:zlib";
23import { appendUserInputAttachmentPaths } from "./userInputAttachments.ts";
24
25vi.mock("node:child_process", { spy: true });
26
27const layer = Layer.merge(
28 ServerConfig.layerTest(process.cwd(), { prefix: "t3-answer-paths-" }),
29 DocumentText.layer,
30).pipe(Layer.provideMerge(NodeServices.layer));
31const attachment = {
32 type: "file" as const,
33 id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
34 name: 'spec "final".txt',
35 mimeType: "text/plain",
36 sizeBytes: 4,
37};
38describe("question answer paths", () => {
39 it.effect.each([false, true])(
40 "keeps unrelated files available during extraction (failure: %s)",
41 (failure) =>
42 Effect.gen(function* () {
43 const config = yield* ServerConfig.ServerConfig;
44 const fs = yield* FileSystem.FileSystem;
45 const path = NodePath.join(config.attachmentsDir, "blocked.rtf");
46 const cached = NodePath.join(config.attachmentsDir, "cached.rtf");
47 NodeFS.writeFileSync(path, failure ? "invalid document" : String.raw`{\rtf1 Available}`);
48 NodeFS.writeFileSync(cached + ".txt", "Cached text");
49 const started = yield* Deferred.make<void>();
50 const release = yield* Deferred.make<void>();
51 let reads = 0;
52 yield* Effect.gen(function* () {
53 const documents = yield* DocumentText.DocumentText;
54 const extraction = yield* documents.ensure(path).pipe(Effect.forkChild);
55 yield* Deferred.await(started);
56 const duplicate = yield* documents.ensure(path).pipe(Effect.forkChild);
57 expect(yield* documents.ensure(path + ".png")).toBeUndefined();
58 expect(yield* documents.ensure(path + ".pdf")).toBeUndefined();
59 expect(yield* documents.ensure(cached)).toBe(cached + ".txt");
60 expect(NodeFS.readFileSync(cached + ".txt", "utf8")).toBe("Cached text");
61 yield* Deferred.succeed(release, undefined);
62 const expected = failure ? undefined : path + ".txt";
63 expect(yield* Fiber.join(extraction)).toBe(expected);
64 expect(yield* Fiber.join(duplicate)).toBe(expected);
65 expect(yield* documents.ensure(path)).toBe(expected);
66 expect(reads).toBe(1);
67 if (failure) {
68 NodeFS.writeFileSync(path + ".txt", "Recovered text");
69 expect(yield* documents.ensure(path)).toBe(path + ".txt");
70 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Recovered text");
71 } else expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Available");
72 }).pipe(
73 Effect.provide(Layer.fresh(DocumentText.layer)),
74 Effect.provideService(FileSystem.FileSystem, {
75 ...fs,
76 stat: (file) =>
77 file === path
78 ? Effect.gen(function* () {
79 reads++;
80 yield* Deferred.succeed(started, undefined);
81 yield* Deferred.await(release);
82 return yield* fs.stat(file);
83 })
84 : fs.stat(file),
85 }),
86 );
87 }).pipe(Effect.provide(layer)),
88 );
89
90 it.effect.each(["spawn", "read"])("retries after a transient %s failure expires", (failure) =>
91 Effect.acquireUseRelease(
92 Effect.promise(async () => {
93 const { execFile } = await vi.importActual<typeof NodeChildProcess>("node:child_process");
94 const worker = vi.spyOn(NodeChildProcess, "execFile");
95 worker.mockImplementationOnce(((
96 file: string,
97 args: readonly string[],
98 options: NodeChildProcess.ExecFileOptionsWithStringEncoding,
99 callback: (
100 error: NodeChildProcess.ExecFileException | null,
101 stdout: string,
102 stderr: string,
103 ) => void,
104 ) => {
105 if (failure === "spawn") {
106 throw Object.assign(new Error("spawn EAGAIN"), { code: "EAGAIN" });
107 }
108 const preload = `import fs from 'node:fs/promises';
109 import { syncBuiltinESMExports } from 'node:module';
110 fs.readFile = async () => { throw Object.assign(new Error('read EAGAIN'), { code: 'EAGAIN' }); };
111 syncBuiltinESMExports();`;
112 return execFile(
113 file,
114 ["--import", `data:text/javascript,${encodeURIComponent(preload)}`, ...args],
115 options,
116 callback,
117 );
118 }) as typeof NodeChildProcess.execFile);
119 return worker;
120 }),
121 (worker) =>
122 Effect.gen(function* () {
123 const config = yield* ServerConfig.ServerConfig;
124 const path = NodePath.join(config.attachmentsDir, "retry.rtf");
125 NodeFS.writeFileSync(path, String.raw`{\rtf1 Available}`);
126 const documents = yield* DocumentText.DocumentText;
127 expect(yield* documents.ensure(path)).toBeUndefined();
128 expect(yield* documents.ensure(path)).toBeUndefined();
129 expect(worker).toHaveBeenCalledTimes(1);
130 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
131 yield* TestClock.adjust("1 second");
132 expect(yield* documents.ensure(path)).toBe(path + ".txt");
133 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Available");
134 expect(worker).toHaveBeenCalledTimes(2);
135 expect(yield* documents.ensure(path)).toBe(path + ".txt");
136 expect(worker).toHaveBeenCalledTimes(2);
137 }).pipe(Effect.provide(layer)),
138 (worker) => Effect.sync(() => worker.mockRestore()),
139 ),
140 );
141
142 it.effect.each([
143 ["ipynb", "{"],
144 ["rtf", "invalid document"],
145 ["rtf", String.raw`{\rtf1}`],
146 ["rtf", String.raw`{\rtf1\ansi\ansicpg99999 Unsupported}`],
147 ] as const)("caches unchanged document rejections: %s %s", ([extension, source]) =>
148 Effect.acquireUseRelease(
149 Effect.sync(() => vi.spyOn(NodeChildProcess, "execFile")),
150 (worker) =>
151 Effect.gen(function* () {
152 const config = yield* ServerConfig.ServerConfig;
153 const path = NodePath.join(config.attachmentsDir, `invalid.${extension}`);
154 NodeFS.writeFileSync(path, source);
155 const documents = yield* DocumentText.DocumentText;
156 for (const seconds of [0, 1, 60]) {
157 yield* TestClock.adjust(`${seconds} seconds`);
158 expect(yield* documents.ensure(path)).toBeUndefined();
159 expect(worker).toHaveBeenCalledTimes(1);
160 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
161 }
162 }).pipe(Effect.provide(layer)),
163 (worker) => Effect.sync(() => worker.mockRestore()),
164 ),
165 );
166
167 it.effect.each([
168 [
169 "text symbols",
170 String.raw`{\rtf1\ansi Pages 1\endash 5\emdash\lquote left\rquote\ldblquote right\rdblquote\bullet\b End\b0\unknown{\*\secret\bullet hidden}}`,
171 "Pages 1–5—‘left’“right”•End",
172 ],
173 [
174 "space and hyphen symbols",
175 String.raw`{\rtf1\ansi A\enspace B\emspace C\qmspace D\~E\_F\-G}`,
176 "A\u2002B\u2003C\u2005D\u00a0E\u2011FG",
177 ],
178 [
179 "text symbol fallback",
180 String.raw`{\rtf1\ansi\uc10\u945\endash\emdash\enspace\emspace\qmspace\lquote\rquote\ldblquote\rdblquote\bullet Z}`,
181 "αZ",
182 ],
183 ["hyphen symbol fallback", String.raw`{\rtf1\ansi\uc3\u945\~\_\-Z}`, "αZ"],
184 ["control word", String.raw`{\rtf1\ansi A\u9\tab X}`, "A\tX"],
185 ["line break paragraphs", "{\\rtf1\\ansi First\\\nSecond\\\r\nThird}", "First\nSecond\nThird"],
186 ["group close", String.raw`{\rtf1\ansi{\u945}Z}`, "αZ"],
187 ["group open", String.raw`{\rtf1\ansi\u945{Z}}`, "αZ"],
188 ["hex byte", String.raw`{\rtf1\ansi\u945\'3fZ}`, "αZ"],
189 ["escaped symbol", String.raw`{\rtf1\ansi\u945\{Z}`, "αZ"],
190 ["destination symbol", String.raw`{\rtf1\ansi\u945\*Z}`, "αZ"],
191 ["multiple units", String.raw`{\rtf1\ansi\uc4\u945?\tab\'3f\~Z}`, "αZ"],
192 ["binary unit", String.raw`{\rtf1\ansi\u945\bin3 abcZ}`, "αZ"],
193 ["large fallback", String.raw`{\rtf1\ansi\uc20\u945????????????????????Z}`, "αZ"],
194 ["no fallback", String.raw`{\rtf1\ansi\uc0\u945Z}`, "αZ"],
195 ["scoped count", String.raw`{\rtf1\ansi{\uc2\u945??}\u946?Z}`, "αβZ"],
196 ] as const)("extracts RTF symbols and Unicode fallbacks: %s", ([name, source, expected]) =>
197 Effect.gen(function* () {
198 const config = yield* ServerConfig.ServerConfig;
199 const path = NodePath.join(config.attachmentsDir, `${name}.rtf`);
200 NodeFS.writeFileSync(path, source);
201 expect(yield* Effect.promise(() => extractDocumentText(path, ".rtf"))).toBe(expected);
202 expect(yield* (yield* DocumentText.DocumentText).ensure(path)).toBe(path + ".txt");
203 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(expected);
204 }).pipe(Effect.provide(layer)),
205 );
206
207 it.effect.each([false, true])("limits the child heap for standalone=%s", (standalone) =>
208 Effect.acquireUseRelease(
209 Effect.promise(async () => {
210 const { execFile } = await vi.importActual<typeof NodeChildProcess>("node:child_process");
211 const probe = vi.spyOn(NodeChildProcess, "execFile");
212 probe.mockImplementation(((
213 file: string,
214 _args: readonly string[],
215 options: NodeChildProcess.ExecFileOptionsWithStringEncoding,
216 callback: (
217 error: NodeChildProcess.ExecFileException | null,
218 stdout: string,
219 stderr: string,
220 ) => void,
221 ) =>
222 execFile(
223 file,
224 [
225 "-e",
226 'process.stdout.write(String(require("node:v8").getHeapStatistics().heap_size_limit))',
227 ],
228 options,
229 callback,
230 )) as typeof NodeChildProcess.execFile);
231 return probe;
232 }),
233 () =>
234 Effect.gen(function* () {
235 const config = yield* ServerConfig.ServerConfig;
236 const path = NodePath.join(config.attachmentsDir, "heap.rtf");
237 NodeFS.writeFileSync(path, String.raw`{\rtf1 hello}`);
238 const extracted = yield* Effect.gen(function* () {
239 return yield* (yield* DocumentText.DocumentText).ensure(path);
240 }).pipe(
241 Effect.provide(Layer.fresh(DocumentText.layer)),
242 Effect.provideService(HostProcess.IsExecutable, standalone),
243 Effect.provideService(HostProcess.Environment, {
244 ...process.env,
245 NODE_OPTIONS: "--max-old-space-size=1024",
246 }),
247 );
248 expect(extracted).toBe(path + ".txt");
249 const heapLimit = Number(NodeFS.readFileSync(path + ".txt", "utf8"));
250 expect(heapLimit).toBeGreaterThan(192 * 1024 * 1024);
251 // Newer V8 versions reserve up to 192 MiB for the young generation as well.
252 expect(heapLimit).toBeLessThanOrEqual(384 * 1024 * 1024);
253 }).pipe(Effect.provide(layer)),
254 (probe) => Effect.sync(() => probe.mockRestore()),
255 ),
256 );
257
258 it.effect("extracts notebook cells and outputs once and keeps both readable paths", () =>
259 Effect.gen(function* () {
260 const config = yield* ServerConfig.ServerConfig;
261 const file = {
262 ...attachment,
263 id: attachment.id.replace(/txt$/, "ipynb"),
264 name: "survey.ipynb",
265 mimeType: "application/x-ipynb+json",
266 };
267 const path = NodePath.join(config.attachmentsDir, `${file.id}.ipynb`);
268 const notebook = JSON.stringify({
269 cells: [
270 { cell_type: "markdown", source: ["# Survey\n", "Vessel: Larkspur"] },
271 {
272 cell_type: "code",
273 source: ["print(43 * 7)"],
274 outputs: [
275 { text: ["301\n"] },
276 { data: { "text/plain": ["42"] } },
277 {
278 output_type: "error",
279 ename: "ZeroDivisionError",
280 evalue: "division by zero",
281 traceback: [
282 "\u001b[32mCell In[1], line 1\u001b[0m",
283 "\u001b[31m----> 1 1 / 0\u001b[0m",
284 "ZeroDivisionError: division by zero",
285 ],
286 },
287 ],
288 },
289 ],
290 });
291 NodeFS.writeFileSync(path, notebook);
292 const answers = yield* appendUserInputAttachmentPaths({
293 answers: { q: "Read this" },
294 attachmentsDir: config.attachmentsDir,
295 attachmentsByQuestionId: { q: [file] },
296 });
297 expect(answers.q).toContain(`text extracted to: ${JSON.stringify(path + ".txt")}`);
298 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("Vessel: Larkspur");
299 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("301");
300 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("42");
301 const extracted = NodeFS.readFileSync(`${path}.txt`, "utf8");
302 expect(extracted).toContain(
303 "ZeroDivisionError: division by zero\nCell In[1], line 1\n----> 1 1 / 0\nZeroDivisionError: division by zero",
304 );
305 expect(extracted).not.toContain("\u001b");
306 expect(NodeFS.readFileSync(path, "utf8")).toBe(notebook);
307 const before = NodeFS.statSync(path + ".txt").mtimeMs;
308 // A changed binary would fail parsing if the cached extraction were not reused.
309 NodeFS.writeFileSync(path, "invalid notebook");
310 const documents = yield* DocumentText.DocumentText;
311 const results = yield* Effect.all([documents.ensure(path), documents.ensure(path)], {
312 concurrency: "unbounded",
313 });
314 expect(results).toEqual([path + ".txt", path + ".txt"]);
315 expect(NodeFS.statSync(path + ".txt").mtimeMs).toBe(before);
316 yield* Effect.gen(function* () {
317 const cleanup = yield* Cleanup.ResourceCleanupService;
318 yield* cleanup.cleanupAttachments([file.id]);
319 expect(NodeFS.existsSync(path)).toBe(false);
320 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
321 NodeFS.writeFileSync(path + ".txt", "orphaned extraction");
322 yield* cleanup.cleanupAttachments([file.id]);
323 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
324 }).pipe(
325 Effect.provide(
326 Cleanup.layer.pipe(
327 Layer.provide(
328 Layer.mergeAll(
329 Layer.mock(TerminalManager.TerminalManager)({}),
330 Layer.mock(PreviewManager.PreviewManager)({}),
331 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
332 ),
333 ),
334 ),
335 ),
336 );
337 }).pipe(Effect.provide(layer)),
338 );
339
340 it.effect(
341 "preserves corrupt documents, PDFs and unknown binaries without an extracted path",
342 () =>
343 Effect.gen(function* () {
344 const config = yield* ServerConfig.ServerConfig;
345 for (const extension of ["docx", "ipynb", "zip", "pdf"]) {
346 const file = {
347 ...attachment,
348 id: attachment.id.replace(/txt$/, extension),
349 name: `broken.${extension}`,
350 };
351 const path = NodePath.join(config.attachmentsDir, `${file.id}.${extension}`);
352 NodeFS.writeFileSync(path, "invalid document");
353 const answers = yield* appendUserInputAttachmentPaths({
354 answers: {},
355 attachmentsDir: config.attachmentsDir,
356 attachmentsByQuestionId: { q: [file] },
357 });
358 expect(answers.q).toContain(JSON.stringify(path));
359 expect(answers.q).not.toContain("text extracted");
360 expect(NodeFS.existsSync(`${path}.txt`)).toBe(false);
361 expect(NodeFS.readFileSync(path, "utf8")).toBe("invalid document");
362 }
363 }).pipe(Effect.provide(layer)),
364 );
365
366 it.effect("preserves office structure and EPUB reading order with bounded archives", () =>
367 Effect.gen(function* () {
368 const config = yield* ServerConfig.ServerConfig;
369 const cases = [
370 {
371 ext: "docx",
372 bounded: true,
373 parts: {
374 "word/document.xml": "<document><p>Readable despite embedded media</p></document>",
375 "word/media/black.bmp": "\0".repeat(64 * 1024),
376 "word/embeddings/unused.bin": "\0".repeat(33 * 1024 * 1024),
377 },
378 expected: ["Readable despite embedded media"],
379 absent: ["[Extracted text truncated"],
380 },
381 ...[false, true].map((deep) => ({
382 ext: "docx",
383 bounded: true,
384 parts: {
385 "word/document.xml": `<document>${deep ? "<div>".repeat(129) + "Lost" + "</div>".repeat(129) : "<p/>".repeat(200_001)}</document>`,
386 },
387 expected: ["[Extracted text truncated at document extraction limits.]"],
388 absent: ["Lost"],
389 })),
390 ...["ods", "odt", "odp", "docx"].flatMap((ext) =>
391 [false, true].map((rows) => ({
392 ext,
393 bounded: true,
394 parts: {
395 [ext === "docx" ? "word/document.xml" : "content.xml"]:
396 `<document><page><table><table-row${rows ? ' number-rows-repeated="10001"' : ""}><table-cell${rows ? "" : ' number-columns-repeated="513"'}><p>Repeated value</p></table-cell></table-row></table></page></document>`,
397 },
398 expected: [
399 "Repeated value",
400 "[Extracted text truncated at document extraction limits.]",
401 ],
402 occurrences: { text: "Repeated value", count: rows ? 10_000 : 512 },
403 })),
404 ),
405 ...["ods", "odt", "odp", "docx"].map((ext) => ({
406 ext,
407 bounded: true,
408 parts: {
409 [ext === "docx" ? "word/document.xml" : "content.xml"]:
410 `<document><page><table><table-row><table-cell><p>Kept</p></table-cell><table-cell number-columns-repeated="16383"> \n <p> \t </p> <s c="1048575"/> </table-cell></table-row><table-row number-rows-repeated="1048575"><table-cell> \n <p> \t </p> </table-cell></table-row></table></page></document>`,
411 },
412 expected: ["Kept"],
413 absent: ["[Extracted text truncated", "\t"],
414 })),
415 ...["ods", "odt", "odp"].map((ext) => ({
416 ext,
417 bounded: true,
418 parts: {
419 "content.xml": `<document><page><table><table-row>
420 <table-cell office:value-type="string" office:string-value="Harbor"/>
421 <table-cell office:value-type="boolean" office:boolean-value="false"/>
422 <table-cell office:value-type="date" office:date-value="2026-10-20"/>
423 <table-cell office:value-type="time" office:time-value="PT2H30M"/>
424 <table-cell office:value-type="currency" office:value="125.50" office:currency="USD"/>
425 <table-cell office:value-type="percentage" office:value="0.25"/>
426 <table-cell office:value-type="float" office:value="0"/>
427 <table-cell office:value-type="string" office:string-value="Fallback"><p> \n </p></table-cell>
428 <table-cell office:value-type="string" office:string-value="Unshown"><p>Displayed</p></table-cell>
429 <table-cell office:value-type="void" office:value="Unshown"/>
430 <table-cell office:value-type="currency" office:value=" " office:currency="Unshown"/>
431 <table-cell office:value-type="percentage" office:value=" "/>
432 </table-row></table></page></document>`,
433 },
434 expected: [
435 "Harbor\tfalse\t2026-10-20\tPT2H30M\t125.50 USD\t0.25 [ODF value-type=percentage]\t0\tFallback\tDisplayed",
436 ],
437 absent: ["Unshown", "[Extracted text truncated"],
438 })),
439 ...[false, true].map((rows) => ({
440 ext: "xlsx",
441 bounded: true,
442 parts: {
443 "xl/workbook.xml": '<workbook><sheet name="Limited" r:id="a"/></workbook>',
444 "xl/_rels/workbook.xml.rels":
445 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
446 "xl/worksheets/a.xml": `<worksheet>${rows ? "<row><c><v>7</v></c></row>".repeat(10_001) : '<row><c r="A1"><v>7</v></c><c r="SS1"><v>Beyond</v></c></row>'}</worksheet>`,
447 },
448 expected: ["7", "[Extracted text truncated at document extraction limits.]"],
449 absent: ["Beyond"],
450 })),
451 {
452 ext: "xlsx",
453 bounded: true,
454 parts: {
455 "xl/workbook.xml": '<workbook><sheet name="Padding" r:id="a"/></workbook>',
456 "xl/_rels/workbook.xml.rels":
457 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
458 "xl/sharedStrings.xml": "<sst><si><t> \n </t></si><si><t>Present</t></si></sst>",
459 "xl/worksheets/a.xml": `<worksheet>${'<row><c t="s"><v>0</v></c><c r="XFD1" t="inlineStr"><is><t> \t </t></is></c></row>'.repeat(10_001)}<row><c t="s"><v>0</v></c><c t="s"><v>1</v></c><c r="XFD2"><v> \n </v></c></row></worksheet>`,
460 },
461 expected: ["Present"],
462 absent: ["[Extracted text truncated"],
463 },
464 {
465 ext: "epub",
466 parts: {
467 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
468 "book.opf":
469 '<package><item id="bad" href="ch%ZZ.xhtml"/><item id="good" href="good.svg"/><itemref idref="bad"/><itemref idref="good"/></package>',
470 "good.svg":
471 '<svg xmlns="http://www.w3.org/2000/svg"><text>Readable SVG chapter</text></svg>',
472 },
473 expected: [
474 "Readable SVG chapter",
475 "[Skipped document part: chapter 1 (missing or invalid XML).]",
476 ],
477 absent: ["[Extracted text truncated"],
478 },
479 ...[false, true].flatMap((bom) =>
480 [false, true].map((bigEndian) => {
481 const encode = (source: string) => {
482 const data = Buffer.from(`${bom ? "\ufeff" : ""}${source}`, "utf16le");
483 return bigEndian ? data.swap16() : data;
484 };
485 return {
486 ext: "epub",
487 parts: {
488 "META-INF/container.xml": encode(
489 '<?xml version="1.0" encoding="UTF-16"?><container><rootfile full-path="book.opf"/></container>',
490 ),
491 "book.opf": encode(
492 '<?xml version="1.0" encoding="UTF-16"?><package><item id="a" href="a.xhtml"/><itemref idref="a"/></package>',
493 ),
494 "a.xhtml": encode(
495 '<?xml version="1.0" encoding="UTF-16"?><html><p>UTF-16 chapter: café 日本語</p></html>',
496 ),
497 },
498 expected: ["UTF-16 chapter: café 日本語"],
499 absent: ["[Skipped document part", "[Extracted text truncated"],
500 };
501 }),
502 ),
503 {
504 ext: "epub",
505 bounded: true,
506 parts: {
507 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
508 "book.opf":
509 '<package><item id="bad" href="bad.xhtml"/><item id="good" href="good.xhtml"/><itemref idref="bad"/><itemref idref="good"/></package>',
510 "bad.xhtml": "<html><p>Discard this broken chapter</html>",
511 "good.xhtml":
512 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><p>North Harbor ≂̸ ∳ & <tag> "quoted"</p><p><![CDATA[Literal ]]></p><table><tr><td> </td></tr><tr><td>Kept cell</td></tr></table></html>',
513 },
514 expected: [
515 "## Chapter 2",
516 'North\u00a0Harbor ≂̸ ∳ & <tag> "quoted"',
517 "Literal ",
518 "Kept cell",
519 "[Skipped document part: bad.xhtml (missing or invalid XML).]",
520 ],
521 absent: ["Discard this broken chapter", "[Extracted text truncated"],
522 },
523 ...["pptx", "xlsx"].map((ext) => ({
524 ext,
525 bounded: true,
526 parts:
527 ext === "pptx"
528 ? {
529 "ppt/presentation.xml":
530 '<presentation><sldId r:id="bad"/><sldId r:id="good"/></presentation>',
531 "ppt/_rels/presentation.xml.rels":
532 '<Relationships><Relationship Id="bad" Target="bad.xml"/><Relationship Id="good" Target="good.xml"/></Relationships>',
533 "ppt/bad.xml": "<slide><p>Discard</slide>",
534 "ppt/good.xml": "<slide><p>Healthy part</p></slide>",
535 }
536 : {
537 "xl/workbook.xml":
538 '<workbook><sheet name="Bad" r:id="bad"/><sheet name="Good" r:id="good"/></workbook>',
539 "xl/_rels/workbook.xml.rels":
540 '<Relationships><Relationship Id="bad" Target="bad.xml"/><Relationship Id="good" Target="good.xml"/></Relationships>',
541 "xl/bad.xml": "<worksheet><row>Discard</worksheet>",
542 "xl/good.xml":
543 '<worksheet><row><c t="inlineStr"><is><t>Healthy part</t></is></c></row></worksheet>',
544 },
545 expected: [
546 "Healthy part",
547 `[Skipped document part: ${ext === "pptx" ? "ppt" : "xl"}/bad.xml (missing or invalid XML).]`,
548 ],
549 absent: ["Discard", "[Extracted text truncated"],
550 })),
551 {
552 ext: "odt",
553 bounded: true,
554 parts: { "content.xml": '<document><p>Start<s c="1000001"/>Unneeded</p></document>' },
555 expected: ["Start", "[Extracted text truncated at document extraction limits.]"],
556 absent: ["Unneeded"],
557 },
558 {
559 ext: "docx",
560 bounded: true,
561 parts: {
562 "word/document.xml":
563 '<w:document xmlns:w="urn:w" xmlns:mc="urn:mc"><w:body><w:p><w:r><w:t>Body</w:t></w:r></w:p><w:p><w:r><mc:AlternateContent><mc:Choice Requires="wps"><w:drawing><wps:wsp><wps:txbx><w:txbxContent><w:p><w:r><w:t>Callout box</w:t></w:r></w:p></w:txbxContent></wps:txbx></wps:wsp></w:drawing></mc:Choice><mc:Fallback><w:pict><v:shape><v:textbox><w:txbxContent><w:p><w:r><w:t>Callout box</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape></w:pict></mc:Fallback></mc:AlternateContent></w:r></w:p></w:body></w:document>',
564 },
565 expected: ["Body\nCallout box"],
566 occurrences: { text: "Callout box", count: 1 },
567 },
568 {
569 ext: "docx",
570 bounded: true,
571 parts: {
572 "word/document.xml":
573 '<w:document xmlns:w="urn:w" xmlns:mc="urn:mc"><w:body><w:p><w:r><mc:AlternateContent><mc:Choice Requires="cx"><w:drawing><cx:chart/></w:drawing></mc:Choice><mc:Fallback><w:pict><v:shape><v:textbox><w:txbxContent><w:p><w:r><w:t>Chart caption</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape></w:pict></mc:Fallback></mc:AlternateContent></w:r></w:p></w:body></w:document>',
574 },
575 expected: ["Chart caption"],
576 },
577 {
578 ext: "docx",
579 bounded: true,
580 parts: {
581 "word/document.xml":
582 '<w:document xmlns:w="urn:w"><w:body><w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr><w:r><w:t>Report & totals</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:p><w:r><w:t>North</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>12</w:t></w:r></w:p><w:p><w:r><w:t>34</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:t>Before</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:p><w:r><w:t>Inner</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p><w:r><w:t>After</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>Neighbor</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>',
583 },
584 expected: ["## Report & totals", "North\t12 34", "Before Inner After\tNeighbor"],
585 },
586 {
587 ext: "docx",
588 bounded: true,
589 parts: {
590 "word/document.xml":
591 '<w:document xmlns:w="urn:w"><w:body><w:p><w:r><w:t>First</w:t><w:cr/><w:t>Second</w:t><w:br/><w:t>Third</w:t></w:r></w:p></w:body></w:document>',
592 },
593 expected: ["First\nSecond\nThird"],
594 },
595 {
596 ext: "docx",
597 bounded: true,
598 parts: {
599 "word/document.xml":
600 '<w:document xmlns:w="urn:w"><w:body><w:p><w:r><w:t>Intro</w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGEREF _Toc1 \\h </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t> 3</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p><w:p><w:pPr><w:tabs><w:tab w:val="right" w:pos="9350"/></w:tabs></w:pPr><w:r><w:t xml:space="preserve">Fee </w:t></w:r><w:del><w:r><w:delText>$500</w:delText></w:r></w:del><w:ins><w:r><w:t>$700</w:t></w:r></w:ins><w:moveFrom><w:r><w:t>Moved</w:t></w:r></w:moveFrom><w:r><w:tab/><w:t>due</w:t></w:r></w:p></w:body></w:document>',
601 },
602 expected: ["Intro 3\nFee $700\tdue"],
603 absent: ["PAGEREF", "$500", "Moved"],
604 },
605 {
606 ext: "odt",
607 bounded: true,
608 parts: {
609 "content.xml":
610 "<document><text><tracked-changes><changed-region><deletion><change-info><creator>Reviewer</creator></change-info><p>$500</p></deletion></changed-region></tracked-changes><p>Fee <change/>$700</p></text></document>",
611 },
612 expected: ["Fee $700"],
613 absent: ["Reviewer", "$500"],
614 },
615 {
616 ext: "docx",
617 bounded: true,
618 parts: {
619 "word/document.xml": `<w:document><w:body><w:tbl><w:tr><w:tc><w:p><w:r><w:t>${"A".repeat(1_000_000)}</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>Later cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>`,
620 },
621 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
622 },
623 {
624 ext: "xlsx",
625 bounded: true,
626 parts: {
627 "xl/workbook.xml": '<workbook><sheet name="Formulas" r:id="a"/></workbook>',
628 "xl/_rels/workbook.xml.rels":
629 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
630 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="9"/></cellXfs></styleSheet>',
631 "xl/worksheets/a.xml":
632 "<worksheet><row><c><f>SUM(11,22)</f><v/></c></row><row><c><f>SUM(33,44)</f><v> \n </v></c></row><row><c><f>SUM(55,66)</f></c></row><row><c><f>SUM(11,22)</f><v>33</v></c><c><f>SUM(0,0)</f><v>0</v></c></row></worksheet>",
633 },
634 expected: [
635 "SUM(11,22)\nSUM(33,44)\nSUM(55,66)",
636 "33 [Excel numFmtId=9; date system 1900]\t0 [Excel numFmtId=9; date system 1900]",
637 ],
638 absent: ["SUM(0,0)", "[Extracted text truncated"],
639 },
640 {
641 ext: "xlsx",
642 parts: {
643 "xl/workbook.xml":
644 '<workbook><sheets><sheet name="Inventory" r:id="a"/><sheet name="Budget" r:id="b"/></sheets></workbook>',
645 "xl/_rels/workbook.xml.rels":
646 '<Relationships><Relationship Id="a" Target="worksheets/second.xml"/><Relationship Id="b" Target="worksheets/first.xml"/></Relationships>',
647 "xl/sharedStrings.xml": "<sst><si><t>Lantern</t></si></sst>",
648 "xl/styles.xml":
649 '<styleSheet><numFmts><numFmt numFmtId="164" formatCode="yyyy-mm-dd"/></numFmts><cellXfs><xf numFmtId="0"/><xf numFmtId="14"/><xf numFmtId="9"/><xf numFmtId="164"/></cellXfs></styleSheet>',
650 "xl/worksheets/second.xml":
651 '<worksheet><sheetData><row><c r="A1" t="s"><v>0</v></c><c r="C1"><v>37</v></c></row></sheetData></worksheet>',
652 "xl/worksheets/first.xml":
653 '<worksheet><sheetData><row><c t="inlineStr"><is><t>Ferry</t></is></c><c><v>628</v></c><c s="1"><v>45292</v></c><c s="2"><v>0.25</v></c><c s="3"><v>45293</v></c></row></sheetData></worksheet>',
654 },
655 expected: [
656 "## Sheet: Inventory",
657 "Lantern\t\t37",
658 "## Sheet: Budget",
659 "Ferry\t628",
660 "45292 [Excel numFmtId=14; date system 1900]",
661 "0.25 [Excel numFmtId=9; date system 1900]",
662 "45293 [Excel numFmtId=164; format=yyyy-mm-dd; date system 1900]",
663 ],
664 },
665 {
666 ext: "xlsx",
667 bounded: true,
668 parts: {
669 "xl/workbook.xml": '<workbook><sheet name="Phonetics" r:id="a"/></workbook>',
670 "xl/_rels/workbook.xml.rels":
671 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
672 "xl/sharedStrings.xml":
673 '<sst><si><t>東京</t><rPh sb="0" eb="2"><t>とうきょう</t></rPh></si></sst>',
674 "xl/worksheets/a.xml":
675 '<worksheet><row><c t="s"><v>0</v></c><c t="inlineStr"><is><t>東京</t><rPh sb="0" eb="2"><t>とうきょう</t></rPh></is></c></row></worksheet>',
676 },
677 expected: ["## Sheet: Phonetics", "東京\t東京"],
678 absent: ["とうきょう"],
679 },
680 {
681 ext: "xlsx",
682 bounded: true,
683 parts: {
684 "xl/workbook.xml":
685 '<workbook><workbookPr date1904="true"/><sheets><sheet name="Dates" r:id="a"/></sheets></workbook>',
686 "xl/_rels/workbook.xml.rels":
687 '<Relationships><Relationship Id="a" Target="worksheets/dates.xml"/></Relationships>',
688 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="14"/></cellXfs></styleSheet>',
689 "xl/worksheets/dates.xml":
690 "<worksheet><sheetData><row><c><v>1</v></c></row></sheetData></worksheet>",
691 },
692 expected: ["## Sheet: Dates", "1 [Excel numFmtId=14; date system 1904]"],
693 },
694 {
695 ext: "xlsx",
696 bounded: true,
697 parts: {
698 "xl/workbook.xml":
699 '<workbook><sheets><sheet name="Repeated" r:id="a"/><sheet name="Unneeded" r:id="missing"/></sheets></workbook>',
700 "xl/_rels/workbook.xml.rels":
701 '<Relationships><Relationship Id="a" Target="worksheets/repeated.xml"/></Relationships>',
702 "xl/sharedStrings.xml": `<sst><si><t>${"A".repeat(1_000_000 - "## Sheet: Repeated\n".length)}</t></si></sst>`,
703 "xl/worksheets/repeated.xml": `<worksheet><sheetData>${'<row><c t="s"><v>0</v></c><c t="s"><v>0</v></c></row>'.repeat(1_500)}</sheetData></worksheet>`,
704 },
705 expected: [
706 "## Sheet: Repeated",
707 "A".repeat(32),
708 "[Extracted text truncated at document extraction limits.]",
709 ],
710 },
711 {
712 ext: "pptx",
713 bounded: true,
714 parts: {
715 "ppt/presentation.xml":
716 '<p:presentation><p:sldIdLst><p:sldId id="1" r:id="b"/><p:sldId id="2" r:id="a"/></p:sldIdLst></p:presentation>',
717 "ppt/_rels/presentation.xml.rels":
718 '<Relationships><Relationship Id="a" Target="slides/slide1.xml"/><Relationship Id="b" Target="slides/slide2.xml"/></Relationships>',
719 "ppt/slides/slide1.xml": "<p:sld><a:p><a:r><a:t>Departure</a:t></a:r></a:p></p:sld>",
720 "ppt/slides/slide2.xml": "<p:sld><a:p><a:r><a:t>Juniper Pier</a:t></a:r></a:p></p:sld>",
721 "ppt/slides/_rels/slide2.xml.rels":
722 '<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../notesSlides/ignored.xml"/><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" TargetMode="External" Target="https://example.com/notes.xml"/><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/notes7.xml"/></Relationships>',
723 "ppt/slides/_rels/slide1.xml.rels":
724 '<Relationships><Relationship Type="http://purl.oclc.org/ooxml/officeDocument/relationships/notesSlide" Target="/ppt/notesSlides/notes3.xml"/></Relationships>',
725 "ppt/notesSlides/notes7.xml":
726 "<p:notes><a:p><a:r><a:t>evacuation code ORCHID-81</a:t></a:r></a:p></p:notes>",
727 "ppt/notesSlides/notes3.xml":
728 "<p:notes><a:p><a:r><a:t>Board at gate 4</a:t></a:r></a:p></p:notes>",
729 "ppt/notesSlides/ignored.xml": "<p:notes><a:p>Unrelated notes</a:p></p:notes>",
730 },
731 expected: [
732 "## Slide 1",
733 "Juniper Pier\nNotes:\nevacuation code ORCHID-81",
734 "## Slide 2",
735 "Departure\nNotes:\nBoard at gate 4",
736 ],
737 absent: ["Unrelated notes", "[Skipped document part", "[Extracted text truncated"],
738 },
739 ...[false, true].map((missing) => ({
740 ext: "pptx",
741 bounded: true,
742 parts: {
743 "ppt/presentation.xml": '<presentation><sldId r:id="a"/></presentation>',
744 "ppt/_rels/presentation.xml.rels":
745 '<Relationships><Relationship Id="a" Target="slides/a.xml"/></Relationships>',
746 "ppt/slides/a.xml": "<slide><p>Slide text</p></slide>",
747 "ppt/slides/_rels/a.xml.rels": `<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/${missing ? "missing" : "bad"}.xml"/></Relationships>`,
748 "ppt/notesSlides/bad.xml": "<notes><p>Discard broken notes</notes>",
749 },
750 expected: [
751 "Slide text",
752 `[Skipped document part: ppt/notesSlides/${missing ? "missing" : "bad"}.xml (missing or invalid XML).]`,
753 ],
754 absent: ["Discard broken notes", "[Extracted text truncated"],
755 })),
756 {
757 ext: "pptx",
758 bounded: true,
759 parts: {
760 "ppt/presentation.xml":
761 '<presentation><sldId r:id="a"/><sldId r:id="b"/></presentation>',
762 "ppt/_rels/presentation.xml.rels":
763 '<Relationships><Relationship Id="a" Target="slides/a.xml"/><Relationship Id="b" Target="slides/b.xml"/></Relationships>',
764 "ppt/slides/a.xml": `<slide><p>${"A".repeat(600_000)}</p></slide>`,
765 "ppt/slides/b.xml": "<slide><p>Unneeded slide</p></slide>",
766 "ppt/slides/_rels/a.xml.rels":
767 '<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/a.xml"/></Relationships>',
768 "ppt/notesSlides/a.xml": `<notes><p>evacuation code ORCHID-81 ${"B".repeat(600_000)} Unneeded notes</p></notes>`,
769 },
770 expected: [
771 "## Slide 1",
772 "A".repeat(32),
773 "Notes:\nevacuation code ORCHID-81",
774 "B".repeat(32),
775 "[Extracted text truncated at document extraction limits.]",
776 ],
777 absent: ["Unneeded notes", "Unneeded slide", "## Slide 2"],
778 },
779 {
780 ext: "odt",
781 parts: {
782 "content.xml":
783 '<office:document><text:h text:outline-level="2">Orchard</text:h><text:p>19<text:s text:c="3"/>violet<text:s/>crates</text:p></office:document>',
784 },
785 expected: ["## Orchard", "19 violet crates"],
786 },
787 {
788 ext: "ods",
789 parts: {
790 "content.xml":
791 '<office:document><table:table table:name="Cargo"><table:table-row><table:table-cell><text:p>Violet</text:p></table:table-cell><table:table-cell office:value="19"/><table:table-cell office:value="27"><text:p/></table:table-cell></table:table-row></table:table></office:document>',
792 },
793 expected: ["## Sheet: Cargo", "Violet\t19\t27"],
794 },
795 {
796 ext: "ods",
797 bounded: true,
798 parts: {
799 "content.xml":
800 '<office:document><table:table table:name="Padded rows"><table:table-row><table:table-cell><text:p>Left</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell><text:p>Right</text:p></table:table-cell></table:table-row><table:table-row table:number-rows-repeated="1048575"><table:table-cell/></table:table-row></table:table></office:document>',
801 },
802 expected: ["## Sheet: Padded rows", "Left\t\t\tRight"],
803 absent: ["[Extracted text truncated"],
804 },
805 {
806 ext: "ods",
807 bounded: true,
808 parts: {
809 "content.xml":
810 '<office:document><table:table table:name="Padded"><table:table-row><table:table-cell><text:p>Populated</text:p></table:table-cell><table:table-cell table:number-columns-repeated="16383"/></table:table-row><table:table-row table:number-rows-repeated="1048575"><table:table-cell table:number-columns-repeated="16384"><text:p/></table:table-cell></table:table-row></table:table></office:document>',
811 },
812 expected: ["## Sheet: Padded", "Populated"],
813 absent: ["[Extracted text truncated", "\t"],
814 },
815 {
816 ext: "ods",
817 bounded: true,
818 parts: {
819 "content.xml": `<office:document><table:table table:name="Repeated"><table:table-row><table:table-cell table:number-columns-repeated="512"><text:p>Lead ${"a".repeat(600_000)} Tail</text:p></table:table-cell></table:table-row></table:table></office:document>`,
820 },
821 expected: [
822 "## Sheet: Repeated",
823 "Lead ",
824 " Tail\tLead ",
825 "[Extracted text truncated at document extraction limits.]",
826 ],
827 },
828 {
829 ext: "odp",
830 parts: {
831 "content.xml":
832 "<office:document><draw:page><text:p>First</text:p></draw:page><draw:page><text:p>Second</text:p></draw:page></office:document>",
833 },
834 expected: ["## Slide 1", "First", "## Slide 2", "Second"],
835 },
836 {
837 ext: "ods",
838 bounded: true,
839 parts: {
840 "content.xml": `<office:document>${Array.from(
841 { length: 256 },
842 (_, index) =>
843 `<table:table table:name="${index === 0 ? "Shared" : "Unneeded"}"><table:table-row><table:table-cell table:number-columns-repeated="512"><text:p>${"B".repeat(4096)}</text:p></table:table-cell></table:table-row></table:table>`,
844 ).join("")}</office:document>`,
845 },
846 expected: [
847 "## Sheet: Shared",
848 "B".repeat(32),
849 "[Extracted text truncated at document extraction limits.]",
850 ],
851 absent: ["## Sheet: Unneeded"],
852 },
853 {
854 ext: "odt",
855 bounded: true,
856 parts: {
857 "content.xml": `<office:document><text:p>Before whitespace</text:p><table:table><table:table-row table:number-rows-repeated="10000"><table:table-cell table:number-columns-repeated="512"><text:p>${" ".repeat(10_000)}</text:p></table:table-cell></table:table-row></table:table><text:p>Unneeded</text:p></office:document>`,
858 },
859 expected: ["Before whitespace", "Unneeded"],
860 absent: ["[Extracted text truncated"],
861 },
862 ...["odt", "odp", "ods"].flatMap((ext) =>
863 [false, true].map((rows) => ({
864 ext,
865 bounded: true,
866 parts: {
867 "content.xml": `<office:document><draw:page>${Array.from(
868 { length: 256 },
869 () =>
870 `<table:table><table:table-row${rows ? ' table:number-rows-repeated="10000"' : ""}><table:table-cell table:number-columns-repeated="512"><text:p>${"Budget ".repeat(rows ? 160 : 585)}</text:p></table:table-cell></table:table-row></table:table>`,
871 ).join(
872 "",
873 )}</draw:page><draw:page><text:p>Unneeded</text:p></draw:page></office:document>`,
874 },
875 expected: ["Budget ", "[Extracted text truncated at document extraction limits.]"],
876 absent: ["Unneeded"],
877 })),
878 ),
879 {
880 ext: "docx",
881 bounded: true,
882 parts: {
883 "word/document.xml": `<w:document><w:p><w:t>${"A".repeat(1_000_100)}</w:t></w:p><w:p><w:t>Unneeded</w:t></w:p></w:document>`,
884 },
885 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
886 absent: ["Unneeded"],
887 },
888 {
889 ext: "pptx",
890 bounded: true,
891 parts: {
892 "ppt/presentation.xml":
893 '<p:presentation><p:sldId r:id="a"/><p:sldId r:id="missing"/></p:presentation>',
894 "ppt/_rels/presentation.xml.rels":
895 '<Relationships><Relationship Id="a" Target="slides/slide.xml"/></Relationships>',
896 "ppt/slides/slide.xml": `<p:sld><a:p><a:t>${"A".repeat(1_000_100)}</a:t></a:p></p:sld>`,
897 },
898 expected: [
899 "## Slide 1",
900 "A".repeat(32),
901 "[Extracted text truncated at document extraction limits.]",
902 ],
903 absent: ["## Slide 2"],
904 },
905 {
906 ext: "epub",
907 bounded: true,
908 parts: {
909 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
910 "book.opf":
911 '<package><item id="a" href="a.xhtml"/><itemref idref="a"/><itemref idref="missing"/></package>',
912 "a.xhtml": `<html><body><p>${"A".repeat(1_000_100)}</p></body></html>`,
913 },
914 expected: [
915 "## Chapter 1",
916 "A".repeat(32),
917 "[Extracted text truncated at document extraction limits.]",
918 ],
919 absent: ["## Chapter 2"],
920 },
921 {
922 ext: "epub",
923 parts: {
924 "META-INF/container.xml":
925 '<container><rootfile full-path="OEBPS/book.opf"/></container>',
926 "OEBPS/book.opf":
927 '<package><manifest><item id="a" href="a.xhtml"/><item id="b" href="b.xhtml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
928 "OEBPS/a.xhtml":
929 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><body><p>Last chapter</p><p>Price <s>10</s> 8</p></body></html>',
930 "OEBPS/b.xhtml":
931 "<!DOCTYPE html><html><body><h1>First chapter</h1><p>Larkspur</p><div>Direct div<section>Direct section<li>Direct item <em>emphasis</em> trailing</li></section></div><div>Account: A<br/>Balance: 731<line-break/>Currency: USD</div><table><thead><tr><th>Heading</th><th>Total</th></tr></thead><tbody><tr><td>Important value</td><td>731</td></tr><tr><td>Before<table><tr><td>Inner</td></tr></table>After</td><td>Neighbor</td></tr></tbody></table></body></html>",
932 },
933 expected: [
934 "## Chapter 1",
935 "# First chapter",
936 "Larkspur",
937 "Direct div",
938 "Direct section",
939 "Direct item emphasis trailing",
940 "Account: A\nBalance: 731\nCurrency: USD",
941 "Heading\tTotal",
942 "Important value\t731",
943 "Before Inner After\tNeighbor",
944 "## Chapter 2",
945 "Last chapter",
946 "Price 10 8",
947 ],
948 },
949 ];
950 for (const [caseIndex, item] of cases.entries()) {
951 const local: Buffer[] = [];
952 const central: Buffer[] = [];
953 let offset = 0;
954 for (const [name, content] of Object.entries(item.parts)) {
955 const data = Buffer.from(content!);
956 const compressed = /\.(bmp|bin)$/.test(name) ? NodeZlib.deflateRawSync(data) : data;
957 const filename = Buffer.from(name);
958 const header = Buffer.alloc(30);
959 header.writeUInt32LE(0x04034b50);
960 header.writeUInt16LE(20, 4);
961 header.writeUInt16LE(compressed === data ? 0 : 8, 8);
962 header.writeUInt32LE(NodeZlib.crc32(data), 14);
963 header.writeUInt32LE(compressed.length, 18);
964 header.writeUInt32LE(data.length, 22);
965 header.writeUInt16LE(filename.length, 26);
966 const directory = Buffer.alloc(46);
967 directory.writeUInt32LE(0x02014b50);
968 directory.writeUInt16LE(20, 4);
969 directory.writeUInt16LE(20, 6);
970 directory.writeUInt16LE(compressed === data ? 0 : 8, 10);
971 directory.writeUInt32LE(NodeZlib.crc32(data), 16);
972 directory.writeUInt32LE(compressed.length, 20);
973 directory.writeUInt32LE(data.length, 24);
974 directory.writeUInt16LE(filename.length, 28);
975 directory.writeUInt32LE(offset, 42);
976 local.push(header, filename, compressed);
977 central.push(directory, filename);
978 offset += header.length + filename.length + compressed.length;
979 }
980 const end = Buffer.alloc(22);
981 end.writeUInt32LE(0x06054b50);
982 end.writeUInt16LE(central.length / 2, 8);
983 end.writeUInt16LE(central.length / 2, 10);
984 end.writeUInt32LE(Buffer.concat(central).length, 12);
985 end.writeUInt32LE(offset, 16);
986 const path = NodePath.join(config.attachmentsDir, `structure-${caseIndex}.${item.ext}`);
987 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
988 const extracted = yield* Effect.promise(() => extractDocumentText(path, `.${item.ext}`));
989 let previous = -1;
990 for (const expected of item.expected) {
991 const index = extracted.indexOf(expected);
992 expect(index, `${item.ext}: ${expected} in ${extracted.slice(0, 500)}`).toBeGreaterThan(
993 previous,
994 );
995 previous = index;
996 }
997 if ("occurrences" in item)
998 expect(extracted.split(item.occurrences.text).length - 1).toBe(item.occurrences.count);
999 if ("absent" in item)
1000 for (const absent of item.absent) expect(extracted).not.toContain(absent);
1001 if (("bounded" in item && item.bounded) || item.ext === "epub") {
1002 expect(extracted.length).toBeLessThan(1_000_100);
1003 expect(extracted.match(/\[Extracted text truncated/g)?.length ?? 0).toBeLessThanOrEqual(
1004 1,
1005 );
1006 const documents = yield* DocumentText.DocumentText;
1007 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1008 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(extracted);
1009 }
1010 if (item.ext === "docx") {
1011 end.writeUInt16LE(2049, 8);
1012 end.writeUInt16LE(2049, 10);
1013 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1014 yield* Effect.promise(async () => {
1015 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
1016 });
1017 end.writeUInt16LE(central.length / 2, 8);
1018 end.writeUInt16LE(central.length / 2, 10);
1019 central[0]!.writeUInt16LE(8, 10);
1020 central[0]!.writeUInt32LE(33 * 1024 * 1024, 24);
1021 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1022 yield* Effect.promise(async () => {
1023 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
1024 });
1025 }
1026 }
1027 const path = NodePath.join(config.attachmentsDir, "unicode.rtf");
1028 NodeFS.writeFileSync(
1029 path,
1030 String.raw`{\rtf1\ansi{\fonttbl hidden}Hello\tab world\par Unicode \u945?{\*\secret hidden}}`,
1031 );
1032 const extracted = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1033 expect(extracted).toContain("Hello\tworld\nUnicode α");
1034 expect(extracted).not.toContain("hidden");
1035
1036 for (const [name, content, expected] of [
1037 [
1038 "cyrillic-escaped",
1039 String.raw`{\rtf1\ansi\ansicpg1251 \'cf\'f0\'e8\'e2\'e5\'f2 {\ansicpg1252 \'e9} \'cc\'ee\'f1\'ea\'e2\'e0}`,
1040 "Привет é Москва",
1041 ],
1042 [
1043 "cyrillic-raw",
1044 Buffer.concat([
1045 Buffer.from(String.raw`{\rtf1\ansi\ansicpg1251 `),
1046 Buffer.from([0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]),
1047 Buffer.from("}"),
1048 ]),
1049 "Привет",
1050 ],
1051 ] as const) {
1052 const encodedPath = NodePath.join(config.attachmentsDir, `${name}.rtf`);
1053 NodeFS.writeFileSync(encodedPath, content);
1054 expect(yield* Effect.promise(() => extractDocumentText(encodedPath, ".rtf"))).toBe(
1055 expected,
1056 );
1057 const documents = yield* DocumentText.DocumentText;
1058 expect(yield* documents.ensure(encodedPath)).toBe(encodedPath + ".txt");
1059 expect(NodeFS.readFileSync(encodedPath + ".txt", "utf8")).toBe(expected);
1060 }
1061 const notebookPath = NodePath.join(config.attachmentsDir, "limited.ipynb");
1062 NodeFS.writeFileSync(
1063 notebookPath,
1064 JSON.stringify({ cells: Array.from({ length: 10_001 }, () => ({ source: "Kept" })) }),
1065 );
1066 const notebookLimited = yield* Effect.promise(() =>
1067 extractDocumentText(notebookPath, ".ipynb"),
1068 );
1069 expect(notebookLimited).toContain("## Cell 10000");
1070 expect(notebookLimited).not.toContain("## Cell 10001");
1071 expect(notebookLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1072 expect(yield* (yield* DocumentText.DocumentText).ensure(notebookPath)).toBe(
1073 notebookPath + ".txt",
1074 );
1075 expect(NodeFS.readFileSync(notebookPath + ".txt", "utf8")).toBe(notebookLimited);
1076 const errorPath = NodePath.join(config.attachmentsDir, "limited-error.ipynb");
1077 NodeFS.writeFileSync(
1078 errorPath,
1079 JSON.stringify({
1080 cells: [
1081 {
1082 cell_type: "code",
1083 source: "1 / 0",
1084 outputs: [
1085 {
1086 output_type: "error",
1087 ename: "ZeroDivisionError",
1088 evalue: "division by zero",
1089 traceback: ["\u001b[31m" + "trace".repeat(250_000) + "\u001b[0m", "After limit"],
1090 },
1091 ],
1092 },
1093 ],
1094 }),
1095 );
1096 const errorLimited = yield* Effect.promise(() => extractDocumentText(errorPath, ".ipynb"));
1097 expect(errorLimited).toContain("ZeroDivisionError: division by zero\ntrace");
1098 expect(errorLimited.length).toBeLessThan(1_000_100);
1099 expect(errorLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1100 expect(errorLimited).not.toContain("After limit");
1101 expect(errorLimited).not.toContain("\u001b");
1102 const deepPath = NodePath.join(config.attachmentsDir, "deep.rtf");
1103 NodeFS.writeFileSync(
1104 deepPath,
1105 String.raw`{\rtf1 Kept` + "{".repeat(128) + "Lost" + "}".repeat(129),
1106 );
1107 const deepLimited = yield* Effect.promise(() => extractDocumentText(deepPath, ".rtf"));
1108 expect(deepLimited).toBe("Kept\n\n[Extracted text truncated at document extraction limits.]");
1109 const unsupportedPath = NodePath.join(config.attachmentsDir, "unsupported-codepage.rtf");
1110 NodeFS.writeFileSync(unsupportedPath, String.raw`{\rtf1\ansi\ansicpg932 \'82\'a0}`);
1111 yield* Effect.promise(async () => {
1112 await expect(extractDocumentText(unsupportedPath, ".rtf")).rejects.toThrow(
1113 "Unsupported RTF code page",
1114 );
1115 });
1116 expect(yield* (yield* DocumentText.DocumentText).ensure(unsupportedPath)).toBeUndefined();
1117 expect(NodeFS.existsSync(unsupportedPath + ".txt")).toBe(false);
1118 NodeFS.writeFileSync(path, String.raw`{\rtf1 ` + "x".repeat(1_000_100) + "}");
1119 expect(yield* Effect.promise(() => extractDocumentText(path, ".rtf"))).toContain(
1120 "[Extracted text truncated",
1121 );
1122 NodeFS.writeFileSync(path, String.raw`{\rtf1 First` + " ".repeat(1_000_100) + "Last}");
1123 const whitespaceTruncated = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1124 expect(whitespaceTruncated).toBe(
1125 "First\n\n[Extracted text truncated at document extraction limits.]",
1126 );
1127 const documents = yield* DocumentText.DocumentText;
1128 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1129 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(whitespaceTruncated);
1130 NodeFS.truncateSync(path, 17 * 1024 * 1024);
1131 yield* Effect.promise(async () => {
1132 expect(await extractDocumentText(path, ".rtf")).toContain("[Extracted text truncated");
1133 });
1134 }).pipe(Effect.provide(layer)),
1135 );
1136 it.effect("keeps selected values intact and appends an actual readable server path", () =>
1137 Effect.gen(function* () {
1138 const config = yield* ServerConfig.ServerConfig;
1139 const path = NodePath.join(config.attachmentsDir, `${attachment.id}.txt`);
1140 NodeFS.writeFileSync(path, "spec");
1141 const original = { q: ["First", "Second"], other: "No file" };
1142 const answers = yield* appendUserInputAttachmentPaths({
1143 answers: original,
1144 attachmentsDir: config.attachmentsDir,
1145 attachmentsByQuestionId: { q: [attachment] },
1146 });
1147 expect(answers.q).toEqual([
1148 "First",
1149 "Second",
1150 `Attached file "spec \\"final\\".txt": ${JSON.stringify(path)}`,
1151 ]);
1152 expect(answers.other).toBe("No file");
1153 expect(original.q).toEqual(["First", "Second"]);
1154 expect(NodeFS.readFileSync(path, "utf8")).toBe("spec");
1155 const specialKey = yield* appendUserInputAttachmentPaths({
1156 answers: {},
1157 attachmentsDir: config.attachmentsDir,
1158 attachmentsByQuestionId: { ["__proto__"]: [attachment] },
1159 });
1160 expect(Object.keys(specialKey)).toEqual(["__proto__"]);
1161 expect(specialKey["__proto__"]).toContain(JSON.stringify(path));
1162 }).pipe(Effect.provide(layer)),
1163 );
1164 it.effect("does not send an unavailable attachment path", () =>
1165 Effect.gen(function* () {
1166 const config = yield* ServerConfig.ServerConfig;
1167 const result = yield* appendUserInputAttachmentPaths({
1168 answers: { q: "" },
1169 attachmentsDir: config.attachmentsDir,
1170 attachmentsByQuestionId: { q: [attachment] },
1171 }).pipe(Effect.result);
1172 expect(result._tag).toBe("Failure");
1173 }).pipe(Effect.provide(layer)),
1174 );
1175});