Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

userInputAttachments.test.ts

1,490 lines75.8 KB

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 Queue from "effect/Queue";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as TestClock from "effect/testing/TestClock";
14import { vi } from "vite-plus/test";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import * as ServerConfig from "../config.ts";
17import * as DocumentText from "./DocumentText.ts";
18import { extractDocumentText } from "./documentTextWorker.ts";
19import * as Cleanup from "../orchestration-v2/ResourceCleanupService.ts";
20import * as DeviceService from "../device/DeviceService.ts";
21import * as TerminalManager from "../terminal/Manager.ts";
22import * as PreviewManager from "../preview/Manager.ts";
23import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
24import * as NodeZlib from "node:zlib";
25import { appendUserInputAttachmentPaths } from "./userInputAttachments.ts";
26​
27vi.mock("node:child_process", { spy: true });
28​
29const layer = Layer.merge(
30 ServerConfig.layerTest(process.cwd(), { prefix: "t3-answer-paths-" }),
31 DocumentText.layer,
32).pipe(Layer.provideMerge(NodeServices.layer));
33const attachment = {
34 type: "file" as const,
35 id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
36 name: 'spec "final".txt',
37 mimeType: "text/plain",
38 sizeBytes: 4,
39};
40describe("question answer paths", () => {
41 it.effect.each([false, true])(
42 "keeps unrelated files available during extraction (failure: %s)",
43 (failure) =>
44 Effect.gen(function* () {
45 const config = yield* ServerConfig.ServerConfig;
46 const fs = yield* FileSystem.FileSystem;
47 const path = NodePath.join(config.attachmentsDir, "blocked.rtf");
48 const cached = NodePath.join(config.attachmentsDir, "cached.rtf");
49 NodeFS.writeFileSync(path, failure ? "invalid document" : String.raw`{\rtf1 Available}`);
50 NodeFS.writeFileSync(cached + ".txt", "Cached text");
51 const started = yield* Deferred.make<void>();
52 const release = yield* Deferred.make<void>();
53 let reads = 0;
54 yield* Effect.gen(function* () {
55 const documents = yield* DocumentText.DocumentText;
56 const extraction = yield* documents.ensure(path).pipe(Effect.forkChild);
57 yield* Deferred.await(started);
58 const duplicate = yield* documents.ensure(path).pipe(Effect.forkChild);
59 expect(yield* documents.ensure(path + ".png")).toBeUndefined();
60 expect(yield* documents.ensure(path + ".pdf")).toBeUndefined();
61 expect(yield* documents.ensure(cached)).toBe(cached + ".txt");
62 expect(NodeFS.readFileSync(cached + ".txt", "utf8")).toBe("Cached text");
63 yield* Deferred.succeed(release, undefined);
64 const expected = failure ? undefined : path + ".txt";
65 expect(yield* Fiber.join(extraction)).toBe(expected);
66 expect(yield* Fiber.join(duplicate)).toBe(expected);
67 expect(yield* documents.ensure(path)).toBe(expected);
68 expect(reads).toBe(1);
69 if (failure) {
70 NodeFS.writeFileSync(path + ".txt", "Recovered text");
71 expect(yield* documents.ensure(path)).toBe(path + ".txt");
72 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Recovered text");
73 } else expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Available");
74 }).pipe(
75 Effect.provide(Layer.fresh(DocumentText.layer)),
76 Effect.provideService(FileSystem.FileSystem, {
77 ...fs,
78 stat: (file) =>
79 file === path
80 ? Effect.gen(function* () {
81 reads++;
82 yield* Deferred.succeed(started, undefined);
83 yield* Deferred.await(release);
84 return yield* fs.stat(file);
85 })
86 : fs.stat(file),
87 }),
88 );
89 }).pipe(Effect.provide(layer)),
90 );
91​
92 it.effect.each(["interrupted", "failed"])(
93 "extracts two documents at once and frees a slot when one is %s",
94 (outcome) =>
95 Effect.gen(function* () {
96 const config = yield* ServerConfig.ServerConfig;
97 const fs = yield* FileSystem.FileSystem;
98 const [first, second, third] = ["first", "second", "third"].map((name) =>
99 NodePath.join(config.attachmentsDir, `${name}.rtf`),
100 );
101 NodeFS.writeFileSync(first!, String.raw`{\rtf1 First}`);
102 NodeFS.writeFileSync(second!, "invalid document");
103 NodeFS.writeFileSync(third!, String.raw`{\rtf1 Third}`);
104 const started = yield* Queue.unbounded<string>();
105 const releases = new Map<string, Deferred.Deferred<void>>();
106 for (const path of [first!, second!, third!])
107 releases.set(path, yield* Deferred.make<void>());
108 yield* Effect.gen(function* () {
109 const documents = yield* DocumentText.DocumentText;
110 const leaving = yield* documents.ensure(first!).pipe(Effect.forkChild);
111 const staying = yield* documents.ensure(first!).pipe(Effect.forkChild);
112 const freed = yield* documents.ensure(second!).pipe(Effect.forkChild);
113 expect(new Set([yield* Queue.take(started), yield* Queue.take(started)])).toEqual(
114 new Set([first, second]),
115 );
116 const waiting = yield* documents.ensure(third!).pipe(Effect.forkChild);
117 yield* Fiber.interrupt(leaving);
118 if (outcome === "interrupted") yield* Fiber.interrupt(freed);
119 else {
120 yield* Deferred.succeed(releases.get(second!)!, undefined);
121 expect(yield* Fiber.join(freed)).toBeUndefined();
122 }
123 expect(yield* Queue.take(started)).toBe(third);
124 yield* Deferred.succeed(releases.get(first!)!, undefined);
125 yield* Deferred.succeed(releases.get(third!)!, undefined);
126 expect(yield* Fiber.join(staying)).toBe(first + ".txt");
127 expect(yield* Fiber.join(waiting)).toBe(third + ".txt");
128 expect(yield* Queue.size(started)).toBe(0);
129 expect(NodeFS.existsSync(second + ".txt")).toBe(false);
130 expect(
131 NodeFS.readdirSync(config.attachmentsDir).filter((file) => file.endsWith(".part")),
132 ).toEqual([]);
133 }).pipe(
134 Effect.provide(Layer.fresh(DocumentText.layer)),
135 Effect.provideService(FileSystem.FileSystem, {
136 ...fs,
137 // An async probe can let `staying` join only after `leaving` cancelled the lookup.
138 exists: (file) => Effect.sync(() => NodeFS.existsSync(file)),
139 stat: (file) =>
140 Effect.gen(function* () {
141 yield* Queue.offer(started, file);
142 yield* Deferred.await(releases.get(file)!);
143 return yield* fs.stat(file);
144 }),
145 }),
146 );
147 }).pipe(Effect.provide(layer)),
148 );
149​
150 it.effect("retries a document while its cancelled extraction is still publishing", () =>
151 Effect.gen(function* () {
152 const config = yield* ServerConfig.ServerConfig;
153 const fs = yield* FileSystem.FileSystem;
154 const path = NodePath.join(config.attachmentsDir, "retried.rtf");
155 NodeFS.writeFileSync(path, String.raw`{\rtf1 Retried}`);
156 const writing = yield* Deferred.make<void>();
157 const writeReleased = yield* Deferred.make<void>();
158 const renaming = yield* Deferred.make<void>();
159 const renameReleased = yield* Deferred.make<void>();
160 let writes = 0;
161 let renames = 0;
162 yield* Effect.gen(function* () {
163 const documents = yield* DocumentText.DocumentText;
164 const cancelled = yield* documents.ensure(path).pipe(Effect.forkChild);
165 yield* Deferred.await(writing);
166 const interrupting = yield* Fiber.interrupt(cancelled).pipe(Effect.forkChild);
167 const retry = yield* documents.ensure(path).pipe(Effect.forkChild);
168 yield* Deferred.await(renaming);
169 yield* Deferred.succeed(writeReleased, undefined);
170 yield* Fiber.join(interrupting);
171 yield* Deferred.succeed(renameReleased, undefined);
172 expect(yield* Fiber.join(retry)).toBe(path + ".txt");
173 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Retried");
174 expect(
175 NodeFS.readdirSync(config.attachmentsDir).filter((file) => file.endsWith(".part")),
176 ).toEqual([]);
177 }).pipe(
178 Effect.provide(Layer.fresh(DocumentText.layer)),
179 Effect.provideService(FileSystem.FileSystem, {
180 ...fs,
181 writeFileString: (file, data) =>
182 Effect.gen(function* () {
183 if (++writes === 1) {
184 yield* Deferred.succeed(writing, undefined);
185 yield* Deferred.await(writeReleased);
186 }
187 return yield* fs.writeFileString(file, data);
188 }),
189 rename: (from, to) =>
190 Effect.gen(function* () {
191 if (++renames === 1) {
192 yield* Deferred.succeed(renaming, undefined);
193 yield* Deferred.await(renameReleased);
194 }
195 return yield* fs.rename(from, to);
196 }),
197 }),
198 );
199 }).pipe(Effect.provide(layer)),
200 );
201​
202 it.effect.each(["spawn", "read"])("retries after a transient %s failure expires", (failure) =>
203 Effect.acquireUseRelease(
204 Effect.promise(async () => {
205 const { execFile } = await vi.importActual<typeof NodeChildProcess>("node:child_process");
206 const worker = vi.spyOn(NodeChildProcess, "execFile");
207 worker.mockImplementationOnce(((
208 file: string,
209 args: readonly string[],
210 options: NodeChildProcess.ExecFileOptionsWithStringEncoding,
211 callback: (
212 error: NodeChildProcess.ExecFileException | null,
213 stdout: string,
214 stderr: string,
215 ) => void,
216 ) => {
217 if (failure === "spawn") {
218 throw Object.assign(new Error("spawn EAGAIN"), { code: "EAGAIN" });
219 }
220 const preload = `import fs from 'node:fs/promises';
221 import { syncBuiltinESMExports } from 'node:module';
222 fs.readFile = async () => { throw Object.assign(new Error('read EAGAIN'), { code: 'EAGAIN' }); };
223 syncBuiltinESMExports();`;
224 return execFile(
225 file,
226 ["--import", `data:text/javascript,${encodeURIComponent(preload)}`, ...args],
227 options,
228 callback,
229 );
230 }) as typeof NodeChildProcess.execFile);
231 return worker;
232 }),
233 (worker) =>
234 Effect.gen(function* () {
235 const config = yield* ServerConfig.ServerConfig;
236 const path = NodePath.join(config.attachmentsDir, "retry.rtf");
237 NodeFS.writeFileSync(path, String.raw`{\rtf1 Available}`);
238 const documents = yield* DocumentText.DocumentText;
239 expect(yield* documents.ensure(path)).toBeUndefined();
240 expect(yield* documents.ensure(path)).toBeUndefined();
241 expect(worker).toHaveBeenCalledTimes(1);
242 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
243 yield* TestClock.adjust("1 second");
244 expect(yield* documents.ensure(path)).toBe(path + ".txt");
245 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Available");
246 expect(worker).toHaveBeenCalledTimes(2);
247 expect(yield* documents.ensure(path)).toBe(path + ".txt");
248 expect(worker).toHaveBeenCalledTimes(2);
249 }).pipe(Effect.provide(layer)),
250 (worker) => Effect.sync(() => worker.mockRestore()),
251 ),
252 );
253​
254 it.effect.each([
255 ["ipynb", "{"],
256 ["rtf", "invalid document"],
257 ["rtf", String.raw`{\rtf1}`],
258 ["rtf", String.raw`{\rtf1\ansi\ansicpg99999 Unsupported}`],
259 ] as const)("caches unchanged document rejections: %s %s", ([extension, source]) =>
260 Effect.acquireUseRelease(
261 Effect.sync(() => vi.spyOn(NodeChildProcess, "execFile")),
262 (worker) =>
263 Effect.gen(function* () {
264 const config = yield* ServerConfig.ServerConfig;
265 const path = NodePath.join(config.attachmentsDir, `invalid.${extension}`);
266 NodeFS.writeFileSync(path, source);
267 const documents = yield* DocumentText.DocumentText;
268 for (const seconds of [0, 1, 60]) {
269 yield* TestClock.adjust(`${seconds} seconds`);
270 expect(yield* documents.ensure(path)).toBeUndefined();
271 expect(worker).toHaveBeenCalledTimes(1);
272 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
273 }
274 }).pipe(Effect.provide(layer)),
275 (worker) => Effect.sync(() => worker.mockRestore()),
276 ),
277 );
278​
279 it.effect.each([
280 [
281 "page-specific headers and footers",
282 String.raw`{\rtf1\ansi\facingp\sectd\titlepg
283{\headerf First-page header}{\headerl Left-page header}{\headerr Right-page header}
284{\footerf First-page footer}{\footerl Left-page footer}{\footerr Right-page footer}
285\pard Approved delivery date: 24 November.\par
286}`,
287 "Approved delivery date: 24 November.",
288 ],
289 [
290 "text symbols",
291 String.raw`{\rtf1\ansi Pages 1\endash 5\emdash\lquote left\rquote\ldblquote right\rdblquote\bullet\b End\b0\unknown{\*\secret\bullet hidden}}`,
292 "Pages 1–5—‘left’“right”•End",
293 ],
294 [
295 "space and hyphen symbols",
296 String.raw`{\rtf1\ansi A\enspace B\emspace C\qmspace D\~E\_F\-G}`,
297 "A\u2002B\u2003C\u2005D\u00a0E\u2011FG",
298 ],
299 [
300 "joiner and direction marks",
301 String.raw`{\rtf1\ansi A\zwj B\zwnj C\ltrmark D\rtlmark E}`,
302 "A\u200dB\u200cC\u200eD\u200fE",
303 ],
304 [
305 "text symbol fallback",
306 String.raw`{\rtf1\ansi\uc10\u945\endash\emdash\enspace\emspace\qmspace\lquote\rquote\ldblquote\rdblquote\bullet Z}`,
307 "αZ",
308 ],
309 ["hyphen symbol fallback", String.raw`{\rtf1\ansi\uc3\u945\~\_\-Z}`, "αZ"],
310 ["control word", String.raw`{\rtf1\ansi A\u9\tab X}`, "A\tX"],
311 ["line break paragraphs", "{\\rtf1\\ansi First\\\nSecond\\\r\nThird}", "First\nSecond\nThird"],
312 [
313 "tracked deletion",
314 String.raw`{\rtf1\ansi The fee is {\deleted\revauthdel1\revdttmdel1 $500}{\revised\revauth1 $700}.}`,
315 "The fee is $700.",
316 ],
317 [
318 "tracked deletion end",
319 String.raw`{\rtf1\ansi{\header Header\plain Plain}A\deleted B\deleted0 C\deleted D\plain E}`,
320 "ACE",
321 ],
322 [
323 "tracked deletion fallback",
324 String.raw`{\rtf1\ansi A{\deleted\uc1\u945\deleted0 B}\deleted\u946?\deleted0 C}`,
325 "AC",
326 ],
327 [
328 "tracked deletion table",
329 String.raw`{\rtf1\ansi\trowd\cellx1000\cellx2000\intbl A\deleted\cell\deleted0 B\cell\deleted\row\deleted0 C\cell}`,
330 "A\tB\t\nC",
331 ],
332 [
333 "document breaks",
334 String.raw`{\rtf1\ansi\sectd\cols2\pard North quota: 120\column South quota: 240\page East quota: 360\sect\sectd\pard West quota: 480\par}`,
335 "North quota: 120\nSouth quota: 240\nEast quota: 360\nWest quota: 480",
336 ],
337 ["group close", String.raw`{\rtf1\ansi{\u945}Z}`, "αZ"],
338 ["group open", String.raw`{\rtf1\ansi\u945{Z}}`, "αZ"],
339 ["hex byte", String.raw`{\rtf1\ansi\u945\'3fZ}`, "αZ"],
340 ["escaped symbol", String.raw`{\rtf1\ansi\u945\{Z}`, "αZ"],
341 ["Macintosh text", String.raw`{\rtf1\mac Caf\'8e Cr\'8fme}`, "Café Crème"],
342 [
343 "explicit Macintosh code page",
344 String.raw`{\rtf1\mac\ansicpg10000 Caf\'8e Cr\'8fme}`,
345 "Café Crème",
346 ],
347 [
348 "font character set",
349 String.raw`{\rtf1\ansi\ansicpg1252\deff1{\fonttbl\f0\fnil\fcharset178 GeezaPro;\f1\fnil\fcharset0 LucidaGrande;}
350\f0 \'e3\'e1\'c7\'cd\'d9\'c9\f1 : caf\'e9, \f0\plain\'c7a}`,
351 "ملاحظة: café, Ça",
352 ],
353 [
354 "font character set outside the font table",
355 String.raw`{\rtf1\ansi{\fonttbl{\f0\fcharset178 A;}{\f0\fcharset0 B;}{\f1\fcharset0 C;}{\f2\fcharset178 D;}{\f2 E;}}{\stylesheet{\s0\f1\fcharset178 N;}}\f0 \'e3\f1\'e3\f2\'e3}`,
356 "ããã",
357 ],
358 ["destination symbol", String.raw`{\rtf1\ansi\u945\*Z}`, "αZ"],
359 ["multiple units", String.raw`{\rtf1\ansi\uc4\u945?\tab\'3f\~Z}`, "αZ"],
360 ["binary unit", String.raw`{\rtf1\ansi\u945\bin3 abcZ}`, "αZ"],
361 ["large fallback", String.raw`{\rtf1\ansi\uc20\u945????????????????????Z}`, "αZ"],
362 ["no fallback", String.raw`{\rtf1\ansi\uc0\u945Z}`, "αZ"],
363 ["scoped count", String.raw`{\rtf1\ansi{\uc2\u945??}\u946?Z}`, "αβZ"],
364 ] as const)("extracts RTF text: %s", ([name, source, expected]) =>
365 Effect.gen(function* () {
366 const config = yield* ServerConfig.ServerConfig;
367 const path = NodePath.join(config.attachmentsDir, `${name}.rtf`);
368 NodeFS.writeFileSync(path, source);
369 expect(yield* Effect.promise(() => extractDocumentText(path, ".rtf"))).toBe(expected);
370 expect(yield* (yield* DocumentText.DocumentText).ensure(path)).toBe(path + ".txt");
371 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(expected);
372 }).pipe(Effect.provide(layer)),
373 );
374​
375 it.effect.each([false, true])("limits the child heap for standalone=%s", (standalone) =>
376 Effect.acquireUseRelease(
377 Effect.promise(async () => {
378 const { execFile } = await vi.importActual<typeof NodeChildProcess>("node:child_process");
379 const probe = vi.spyOn(NodeChildProcess, "execFile");
380 probe.mockImplementation(((
381 file: string,
382 _args: readonly string[],
383 options: NodeChildProcess.ExecFileOptionsWithStringEncoding,
384 callback: (
385 error: NodeChildProcess.ExecFileException | null,
386 stdout: string,
387 stderr: string,
388 ) => void,
389 ) =>
390 execFile(
391 file,
392 [
393 "-e",
394 'process.stdout.write(String(require("node:v8").getHeapStatistics().heap_size_limit))',
395 ],
396 options,
397 callback,
398 )) as typeof NodeChildProcess.execFile);
399 return probe;
400 }),
401 () =>
402 Effect.gen(function* () {
403 const config = yield* ServerConfig.ServerConfig;
404 const path = NodePath.join(config.attachmentsDir, "heap.rtf");
405 NodeFS.writeFileSync(path, String.raw`{\rtf1 hello}`);
406 const extracted = yield* Effect.gen(function* () {
407 return yield* (yield* DocumentText.DocumentText).ensure(path);
408 }).pipe(
409 Effect.provide(Layer.fresh(DocumentText.layer)),
410 Effect.provideService(HostProcess.IsExecutable, standalone),
411 Effect.provideService(HostProcess.Environment, {
412 ...process.env,
413 NODE_OPTIONS: "--max-old-space-size=1024",
414 }),
415 );
416 expect(extracted).toBe(path + ".txt");
417 const heapLimit = Number(NodeFS.readFileSync(path + ".txt", "utf8"));
418 expect(heapLimit).toBeGreaterThan(192 * 1024 * 1024);
419 // Newer V8 versions reserve up to 192 MiB for the young generation as well.
420 expect(heapLimit).toBeLessThanOrEqual(384 * 1024 * 1024);
421 }).pipe(Effect.provide(layer)),
422 (probe) => Effect.sync(() => probe.mockRestore()),
423 ),
424 );
425​
426 it.effect("extracts notebook cells and outputs once and keeps both readable paths", () =>
427 Effect.gen(function* () {
428 const config = yield* ServerConfig.ServerConfig;
429 const file = {
430 ...attachment,
431 id: attachment.id.replace(/txt$/, "ipynb"),
432 name: "survey.ipynb",
433 mimeType: "application/x-ipynb+json",
434 };
435 const path = NodePath.join(config.attachmentsDir, `${file.id}.ipynb`);
436 const rawSource = String.raw`\begin{tabular}{lr} North & 120 \\ \end{tabular}`;
437 const notebook = JSON.stringify({
438 cells: [
439 { cell_type: "markdown", source: ["# Survey\n", "Vessel: Larkspur"] },
440 {
441 cell_type: "code",
442 source: ["print(43 * 7)"],
443 outputs: [
444 { output_type: "stream", name: "stdout", text: "\u001b[32m301\u001b[0m\n" },
445 {
446 output_type: "display_data",
447 data: { "text/plain": ["\u001b[", "33m42\u001b[0m\n", "Next line"] },
448 metadata: {},
449 },
450 {
451 output_type: "error",
452 ename: "ZeroDivisionError",
453 evalue: "division by zero",
454 traceback: [
455 "\u001b[32mCell In[1], line 1\u001b[0m",
456 "\u001b[31m----> 1 1 / 0\u001b[0m",
457 "ZeroDivisionError: division by zero",
458 ],
459 },
460 ],
461 },
462 { cell_type: "raw", source: [rawSource] },
463 ],
464 });
465 NodeFS.writeFileSync(path, notebook);
466 const answers = yield* appendUserInputAttachmentPaths({
467 answers: { q: "Read this" },
468 attachmentsDir: config.attachmentsDir,
469 attachmentsByQuestionId: { q: [file] },
470 });
471 expect(answers.q).toContain(`text extracted to: ${JSON.stringify(path + ".txt")}`);
472 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("Vessel: Larkspur");
473 const extracted = NodeFS.readFileSync(`${path}.txt`, "utf8");
474 expect(extracted).toContain("Output:\n301\n");
475 expect(extracted).toContain("42\nNext line");
476 expect(extracted).toContain(`## Cell 3 (raw)\n${rawSource}`);
477 expect(extracted).toContain(
478 "ZeroDivisionError: division by zero\nCell In[1], line 1\n----> 1 1 / 0\nZeroDivisionError: division by zero",
479 );
480 expect(extracted).not.toContain("\u001b");
481 expect(NodeFS.readFileSync(path, "utf8")).toBe(notebook);
482 const before = NodeFS.statSync(path + ".txt").mtimeMs;
483 // A changed binary would fail parsing if the cached extraction were not reused.
484 NodeFS.writeFileSync(path, "invalid notebook");
485 const documents = yield* DocumentText.DocumentText;
486 const results = yield* Effect.all([documents.ensure(path), documents.ensure(path)], {
487 concurrency: "unbounded",
488 });
489 expect(results).toEqual([path + ".txt", path + ".txt"]);
490 expect(NodeFS.statSync(path + ".txt").mtimeMs).toBe(before);
491 yield* Effect.gen(function* () {
492 const cleanup = yield* Cleanup.ResourceCleanupService;
493 yield* cleanup.cleanupAttachments([file.id]);
494 expect(NodeFS.existsSync(path)).toBe(false);
495 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
496 NodeFS.writeFileSync(path + ".txt", "orphaned extraction");
497 yield* cleanup.cleanupAttachments([file.id]);
498 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
499 }).pipe(
500 Effect.provide(
501 Cleanup.layer.pipe(
502 Layer.provide(
503 Layer.mergeAll(
504 Layer.mock(TerminalManager.TerminalManager)({}),
505 Layer.mock(PreviewManager.PreviewManager)({}),
506 Layer.mock(DeviceService.DeviceService)({}),
507 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
508 ),
509 ),
510 ),
511 ),
512 );
513 }).pipe(Effect.provide(layer)),
514 );
515​
516 it.effect(
517 "preserves corrupt documents, PDFs and unknown binaries without an extracted path",
518 () =>
519 Effect.gen(function* () {
520 const config = yield* ServerConfig.ServerConfig;
521 for (const extension of ["docx", "ipynb", "zip", "pdf"]) {
522 const file = {
523 ...attachment,
524 id: attachment.id.replace(/txt$/, extension),
525 name: `broken.${extension}`,
526 };
527 const path = NodePath.join(config.attachmentsDir, `${file.id}.${extension}`);
528 NodeFS.writeFileSync(path, "invalid document");
529 const answers = yield* appendUserInputAttachmentPaths({
530 answers: {},
531 attachmentsDir: config.attachmentsDir,
532 attachmentsByQuestionId: { q: [file] },
533 });
534 expect(answers.q).toContain(JSON.stringify(path));
535 expect(answers.q).not.toContain("text extracted");
536 expect(NodeFS.existsSync(`${path}.txt`)).toBe(false);
537 expect(NodeFS.readFileSync(path, "utf8")).toBe("invalid document");
538 }
539 }).pipe(Effect.provide(layer)),
540 );
541​
542 it.effect("preserves office structure and EPUB reading order with bounded archives", () =>
543 Effect.gen(function* () {
544 const config = yield* ServerConfig.ServerConfig;
545 const cases = [
546 // Word stores object layout and field data outside the visible document text.
547 {
548 ext: "docx",
549 bounded: true,
550 parts: {
551 "word/document.xml":
552 '<w:document xmlns:w="urn:w" xmlns:wp="urn:wp" xmlns:wp14="urn:wp14" xmlns:mc="urn:mc"><w:body><w:p><w:r><w:t>Total cost is </w:t><w:drawing><wp:anchor><wp:positionH><wp:posOffset>1905000</wp:posOffset></wp:positionH><wp:positionV><wp:posOffset>-635</wp:posOffset></wp:positionV><wp14:sizeRelH><wp14:pctWidth>0</wp14:pctWidth></wp14:sizeRelH><wp14:sizeRelV><wp14:pctHeight>0</wp14:pctHeight></wp14:sizeRelV></wp:anchor></w:drawing><w:t>42 EUR.</w:t></w:r></w:p></w:body></w:document>',
553 },
554 expected: ["Total cost is 42 EUR."],
555 absent: ["1905000", "-635", "0042"],
556 },
557 {
558 ext: "docx",
559 bounded: true,
560 parts: {
561 "word/document.xml":
562 '<w:document xmlns:w="urn:w" xmlns:wp="urn:wp" xmlns:wp14="urn:wp14" xmlns:mc="urn:mc"><w:body><w:p><mc:AlternateContent><mc:Choice Requires="cx"><w:drawing><wp:anchor><wp:positionH><wp:posOffset>1905000</wp:posOffset></wp:positionH><wp:positionV><wp:posOffset>-635</wp:posOffset></wp:positionV><wp14:sizeRelH><wp14:pctWidth>0</wp14:pctWidth></wp14:sizeRelH><wp14:sizeRelV><wp14:pctHeight>0</wp14:pctHeight></wp14:sizeRelV></wp:anchor></w:drawing><cx:chart/></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:p></w:body></w:document>',
563 },
564 expected: ["Chart caption"],
565 absent: ["1905000", "-635"],
566 },
567 {
568 ext: "docx",
569 bounded: true,
570 parts: {
571 "word/document.xml":
572 '<w:document xmlns:w="urn:w" xmlns:wp="urn:wp" xmlns:wp14="urn:wp14" xmlns:mc="urn:mc"><w:body><w:p><w:r><w:t>As shown </w:t><w:fldChar><w:fldData>RU5ETk9URQ==</w:fldData></w:fldChar><w:t>(Smith 2020) earlier.</w:t></w:r></w:p></w:body></w:document>',
573 },
574 expected: ["As shown (Smith 2020) earlier."],
575 absent: ["RU5ETk9URQ=="],
576 },
577 {
578 ext: "docx",
579 bounded: true,
580 parts: {
581 "word/document.xml": "<document><p>Readable despite embedded media</p></document>",
582 "word/media/black.bmp": "\0".repeat(64 * 1024),
583 "word/embeddings/unused.bin": "\0".repeat(33 * 1024 * 1024),
584 },
585 expected: ["Readable despite embedded media"],
586 absent: ["[Extracted text truncated"],
587 },
588 ...[false, true].map((deep) => ({
589 ext: "docx",
590 bounded: true,
591 parts: {
592 "word/document.xml": `<document>${deep ? "<div>".repeat(129) + "Lost" + "</div>".repeat(129) : "<p/>".repeat(200_001)}</document>`,
593 },
594 expected: ["[Extracted text truncated at document extraction limits.]"],
595 absent: ["Lost"],
596 })),
597 ...["ods", "odt", "odp", "docx"].flatMap((ext) =>
598 [false, true].map((rows) => ({
599 ext,
600 bounded: true,
601 parts: {
602 [ext === "docx" ? "word/document.xml" : "content.xml"]:
603 `<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>`,
604 },
605 expected: [
606 "Repeated value",
607 "[Extracted text truncated at document extraction limits.]",
608 ],
609 occurrences: { text: "Repeated value", count: rows ? 10_000 : 512 },
610 })),
611 ),
612 ...["ods", "odt", "odp", "docx"].map((ext) => ({
613 ext,
614 bounded: true,
615 parts: {
616 [ext === "docx" ? "word/document.xml" : "content.xml"]:
617 `<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>`,
618 },
619 expected: ["Kept"],
620 absent: ["[Extracted text truncated", "\t"],
621 })),
622 ...["ods", "odt", "odp"].map((ext) => ({
623 ext,
624 bounded: true,
625 parts: {
626 "content.xml": `<document><page><table><table-row>
627 <table-cell office:value-type="string" office:string-value="Harbor"/>
628 <table-cell office:value-type="boolean" office:boolean-value="false"/>
629 <table-cell office:value-type="date" office:date-value="2026-10-20"/>
630 <table-cell office:value-type="time" office:time-value="PT2H30M"/>
631 <table-cell office:value-type="currency" office:value="125.50" office:currency="USD"/>
632 <table-cell office:value-type="percentage" office:value="0.25"/>
633 <table-cell office:value-type="float" office:value="0"/>
634 <table-cell office:value-type="string" office:string-value="Fallback"><p> \n </p></table-cell>
635 <table-cell office:value-type="string" office:string-value="Unshown"><p>Displayed</p></table-cell>
636 <table-cell office:value-type="void" office:value="Unshown"/>
637 <table-cell office:value-type="currency" office:value=" " office:currency="Unshown"/>
638 <table-cell office:value-type="percentage" office:value=" "/>
639 </table-row></table></page></document>`,
640 },
641 expected: [
642 "Harbor\tfalse\t2026-10-20\tPT2H30M\t125.50 USD\t0.25 [ODF value-type=percentage]\t0\tFallback\tDisplayed",
643 ],
644 absent: ["Unshown", "[Extracted text truncated"],
645 })),
646 ...[false, true].map((rows) => ({
647 ext: "xlsx",
648 bounded: true,
649 parts: {
650 "xl/workbook.xml": '<workbook><sheet name="Limited" r:id="a"/></workbook>',
651 "xl/_rels/workbook.xml.rels":
652 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
653 "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>`,
654 },
655 expected: ["7", "[Extracted text truncated at document extraction limits.]"],
656 absent: ["Beyond"],
657 })),
658 {
659 ext: "xlsx",
660 bounded: true,
661 parts: {
662 "xl/workbook.xml": '<workbook><sheet name="Padding" r:id="a"/></workbook>',
663 "xl/_rels/workbook.xml.rels":
664 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
665 "xl/sharedStrings.xml": "<sst><si><t> \n </t></si><si><t>Present</t></si></sst>",
666 "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>`,
667 },
668 expected: ["Present"],
669 absent: ["[Extracted text truncated"],
670 },
671 {
672 ext: "epub",
673 parts: {
674 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
675 "book.opf":
676 '<package><item id="bad" href="ch%ZZ.xhtml"/><item id="good" href="good.svg"/><itemref idref="bad"/><itemref idref="good"/></package>',
677 "good.svg":
678 '<svg xmlns="http://www.w3.org/2000/svg"><text>Readable SVG chapter</text></svg>',
679 },
680 expected: [
681 "Readable SVG chapter",
682 "[Skipped document part: chapter 1 (missing or invalid XML).]",
683 ],
684 absent: ["[Extracted text truncated"],
685 },
686 ...[false, true].flatMap((bom) =>
687 [false, true].map((bigEndian) => {
688 const encode = (source: string) => {
689 const data = Buffer.from(`${bom ? "\ufeff" : ""}${source}`, "utf16le");
690 return bigEndian ? data.swap16() : data;
691 };
692 return {
693 ext: "epub",
694 parts: {
695 "META-INF/container.xml": encode(
696 '<?xml version="1.0" encoding="UTF-16"?><container><rootfile full-path="book.opf"/></container>',
697 ),
698 "book.opf": encode(
699 '<?xml version="1.0" encoding="UTF-16"?><package><item id="a" href="a.xhtml"/><itemref idref="a"/></package>',
700 ),
701 "a.xhtml": encode(
702 '<?xml version="1.0" encoding="UTF-16"?><html><p>UTF-16 chapter: café 日本語</p></html>',
703 ),
704 },
705 expected: ["UTF-16 chapter: café 日本語"],
706 absent: ["[Skipped document part", "[Extracted text truncated"],
707 };
708 }),
709 ),
710 {
711 ext: "epub",
712 bounded: true,
713 parts: {
714 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
715 "book.opf":
716 '<package><item id="bad" href="bad.xhtml"/><item id="good" href="good.xhtml"/><itemref idref="bad"/><itemref idref="good"/></package>',
717 "bad.xhtml": "<html><p>Discard this broken chapter</html>",
718 "good.xhtml":
719 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><p>North&nbsp;Harbor &NotEqualTilde; &CounterClockwiseContourIntegral; &amp; &lt;tag&gt; &quot;quoted&quot;</p><p><![CDATA[Literal &nbsp;]]></p><table><tr><td>&nbsp; </td></tr><tr><td>Kept&nbsp;cell</td></tr></table></html>',
720 },
721 expected: [
722 "## Chapter 2",
723 'North\u00a0Harbor ≂̸ ∳ & <tag> "quoted"',
724 "Literal &nbsp;",
725 "Kept cell",
726 "[Skipped document part: bad.xhtml (missing or invalid XML).]",
727 ],
728 absent: ["Discard this broken chapter", "[Extracted text truncated"],
729 },
730 ...["pptx", "xlsx"].map((ext) => ({
731 ext,
732 bounded: true,
733 parts:
734 ext === "pptx"
735 ? {
736 "ppt/presentation.xml":
737 '<presentation><sldIdLst><sldId r:id="bad"/><sldId r:id="good"/></sldIdLst></presentation>',
738 "ppt/_rels/presentation.xml.rels":
739 '<Relationships><Relationship Id="bad" Target="bad.xml"/><Relationship Id="good" Target="good.xml"/></Relationships>',
740 "ppt/bad.xml": "<slide><p>Discard</slide>",
741 "ppt/good.xml": "<slide><p>Healthy part</p></slide>",
742 }
743 : {
744 "xl/workbook.xml":
745 '<workbook><sheet name="Bad" r:id="bad"/><sheet name="Good" r:id="good"/></workbook>',
746 "xl/_rels/workbook.xml.rels":
747 '<Relationships><Relationship Id="bad" Target="bad.xml"/><Relationship Id="good" Target="good.xml"/></Relationships>',
748 "xl/bad.xml": "<worksheet><row>Discard</worksheet>",
749 "xl/good.xml":
750 '<worksheet><row><c t="inlineStr"><is><t>Healthy part</t></is></c></row></worksheet>',
751 },
752 expected: [
753 "Healthy part",
754 `[Skipped document part: ${ext === "pptx" ? "ppt" : "xl"}/bad.xml (missing or invalid XML).]`,
755 ],
756 absent: ["Discard", "[Extracted text truncated"],
757 })),
758 {
759 ext: "odt",
760 bounded: true,
761 parts: { "content.xml": '<document><p>Start<s c="1000001"/>Unneeded</p></document>' },
762 expected: ["Start", "[Extracted text truncated at document extraction limits.]"],
763 absent: ["Unneeded"],
764 },
765 {
766 ext: "docx",
767 bounded: true,
768 parts: {
769 "word/document.xml":
770 '<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>',
771 },
772 expected: ["Body\nCallout box"],
773 occurrences: { text: "Callout box", count: 1 },
774 },
775 {
776 ext: "docx",
777 bounded: true,
778 parts: {
779 "word/document.xml":
780 '<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>',
781 },
782 expected: ["Chart caption"],
783 },
784 {
785 ext: "docx",
786 bounded: true,
787 parts: {
788 "word/document.xml":
789 '<w:document xmlns:w="urn:w"><w:body><w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr><w:r><w:t>Report &amp; 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:sdt><w:sdtPr><w:alias w:val="Title"/></w:sdtPr><w:sdtContent><w:tc><w:p><w:r><w:t>Annual report</w:t></w:r></w:p></w:tc></w:sdtContent></w:sdt><w:tc><w:p><w:r><w:t>Draft</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:tc><w:p><w:r><w:noBreakHyphen/></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:noBreakHyphen/></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>',
790 },
791 expected: [
792 "## Report & totals",
793 "North\t12 34",
794 "Annual report\tDraft",
795 "Before Inner After\tNeighbor\t\u2011\n\u2011",
796 ],
797 },
798 {
799 ext: "docx",
800 bounded: true,
801 parts: {
802 "word/document.xml": [
803 '<w:document xmlns:w="urn:w" xmlns:mc="urn:mc"><w:body>',
804 '<w:p><w:r><w:t>First</w:t><w:cr/><w:t>Second</w:t><w:br/><w:t>Third</w:t><w:noBreakHyphen/><w:t>party</w:t><mc:AlternateContent><mc:Choice Requires="w"><w:noBreakHyphen/></mc:Choice><mc:Fallback><w:t>‑</w:t></mc:Fallback></mc:AlternateContent><w:t>End</w:t></w:r></w:p>',
805 '<w:p><w:r><w:t>Invoice 104</w:t><w:ptab w:alignment="right" w:relativeTo="margin" w:leader="none"/><w:t>$700.00</w:t></w:r></w:p>',
806 '<w:p><w:r><w:t>Invoice 105</w:t><mc:AlternateContent><mc:Choice Requires="w"><w:ptab w:alignment="right" w:relativeTo="margin" w:leader="none"/></mc:Choice><mc:Fallback><w:tab/></mc:Fallback></mc:AlternateContent><w:t>$800.00</w:t></w:r></w:p>',
807 '<w:p><w:r><w:t>Invoice 106</w:t><mc:AlternateContent><mc:Choice Requires="w"><w:ptab w:alignment="right" w:relativeTo="margin" w:leader="none"/></mc:Choice><mc:Fallback><w:t xml:space="preserve"> total </w:t></mc:Fallback></mc:AlternateContent><w:t>$900.00</w:t></w:r></w:p>',
808 "</w:body></w:document>",
809 ].join(""),
810 },
811 expected: [
812 "First\nSecond\nThird\u2011party\u2011End\nInvoice 104\t$700.00\nInvoice 105\t$800.00\nInvoice 106 total $900.00",
813 ],
814 },
815 {
816 ext: "docx",
817 bounded: true,
818 parts: {
819 "word/document.xml":
820 '<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:noBreakHyphen/></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>',
821 },
822 expected: ["Intro 3\nFee $700\tdue"],
823 absent: ["PAGEREF", "$500", "Moved", "\u2011"],
824 },
825 {
826 ext: "odt",
827 bounded: true,
828 parts: {
829 "content.xml":
830 "<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>",
831 },
832 expected: ["Fee $700"],
833 absent: ["Reviewer", "$500"],
834 },
835 {
836 ext: "odt",
837 bounded: true,
838 parts: {
839 "content.xml":
840 '<document><text><p>Fee <office:annotation><dc:creator>Reviewer</dc:creator><dc:date>2026-01-01T00:00:00</dc:date><initials>JR</initials><p>Check</p></office:annotation>$700</p><table><table-row><table-cell office:value-type="float" office:value="150"><office:annotation><p>was 120</p></office:annotation></table-cell></table-row></table><p>Formula <math:math><math:semantics><math:mrow>x+y</math:mrow><math:annotation encoding="application/x-tex">x+y</math:annotation></math:semantics></math:math></p></text></document>',
841 },
842 expected: ["Fee $700\n150\nFormula x+yx+y"],
843 absent: ["Reviewer", "2026-01-01", "JR", "Check", "was 120"],
844 },
845 {
846 ext: "docx",
847 bounded: true,
848 parts: {
849 "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>`,
850 },
851 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
852 },
853 {
854 ext: "xlsx",
855 bounded: true,
856 parts: {
857 "xl/workbook.xml": '<workbook><sheet name="Formulas" r:id="a"/></workbook>',
858 "xl/_rels/workbook.xml.rels":
859 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
860 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="9"/></cellXfs></styleSheet>',
861 "xl/worksheets/a.xml":
862 "<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>",
863 },
864 expected: [
865 "SUM(11,22)\nSUM(33,44)\nSUM(55,66)",
866 "33 [Excel numFmtId=9; date system 1900]\t0 [Excel numFmtId=9; date system 1900]",
867 ],
868 absent: ["SUM(0,0)", "[Extracted text truncated"],
869 },
870 {
871 ext: "xlsx",
872 bounded: true,
873 parts: {
874 "xl/workbook.xml": '<workbook><sheet name="Flags" r:id="a"/></workbook>',
875 "xl/_rels/workbook.xml.rels":
876 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
877 "xl/worksheets/a.xml":
878 '<worksheet><row><c r="A1" t="b"><v>1</v></c><c r="B1" t="b"><v>0</v></c><c r="C1" t="n"><v>1</v></c><c r="D1" t="b"><v>2</v></c></row></worksheet>',
879 },
880 expected: ["true\tfalse\t1\t2"],
881 },
882 {
883 ext: "xlsx",
884 parts: {
885 "xl/workbook.xml":
886 '<workbook><sheets><sheet name="Inventory" r:id="a"/><sheet name="Budget" r:id="b"/></sheets></workbook>',
887 "xl/_rels/workbook.xml.rels":
888 '<Relationships><Relationship Id="a" Target="worksheets/second.xml"/><Relationship Id="b" Target="worksheets/first.xml"/></Relationships>',
889 "xl/sharedStrings.xml": "<sst><si><t>Lantern</t></si></sst>",
890 "xl/styles.xml":
891 '<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>',
892 "xl/worksheets/second.xml":
893 '<worksheet><sheetData><row><c r="A1" t="s"><v>0</v></c><c r="C1"><v>37</v></c></row></sheetData></worksheet>',
894 "xl/worksheets/first.xml":
895 '<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>',
896 },
897 expected: [
898 "## Sheet: Inventory",
899 "Lantern\t\t37",
900 "## Sheet: Budget",
901 "Ferry\t628",
902 "45292 [Excel numFmtId=14; date system 1900]",
903 "0.25 [Excel numFmtId=9; date system 1900]",
904 "45293 [Excel numFmtId=164; format=yyyy-mm-dd; date system 1900]",
905 ],
906 },
907 {
908 ext: "xlsx",
909 bounded: true,
910 parts: {
911 "xl/workbook.xml": '<workbook><sheet name="Phonetics" r:id="a"/></workbook>',
912 "xl/_rels/workbook.xml.rels":
913 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
914 "xl/sharedStrings.xml":
915 '<sst><si><t>東京</t><rPh sb="0" eb="2"><t>とうきょう</t></rPh></si></sst>',
916 "xl/worksheets/a.xml":
917 '<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>',
918 },
919 expected: ["## Sheet: Phonetics", "東京\t東京"],
920 absent: ["とうきょう"],
921 },
922 {
923 ext: "xlsx",
924 bounded: true,
925 parts: {
926 "xl/workbook.xml": '<workbook><sheet name="Escapes" r:id="a"/></workbook>',
927 "xl/_rels/workbook.xml.rels":
928 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
929 "xl/sharedStrings.xml":
930 "<sst><si><t>first_x000D_\nsecond</t></si><si><t>_x005F_x0041_</t></si><si><t>_x005F_x005F_x0041_</t></si><si><r><t>Bold_x000D_</t></r><r><t>_x005F_x000D_</t></r></si><si><t>&amp;_xnothex_ cap_X0041_ _x000d_ tail</t></si></sst>",
931 "xl/worksheets/a.xml":
932 '<worksheet><row><c t="s"><v>0</v></c><c t="s"><v>1</v></c><c t="s"><v>2</v></c><c t="s"><v>3</v></c><c t="s"><v>4</v></c></row><row><c t="inlineStr"><is><t>_x005F_x005F_</t></is></c><c t="inlineStr"><is><t>first_x000D_second</t></is></c><c t="str"><f>A1</f><v>Total_x000D_due</v></c></row></worksheet>',
933 },
934 expected: [
935 "## Sheet: Escapes\nfirst second\t_x0041_\t_x005F_x0041_\tBold _x000D_\t&_xnothex_ cap_X0041_ tail\n_x005F_\tfirst second\tTotal due",
936 ],
937 },
938 {
939 ext: "xlsx",
940 bounded: true,
941 parts: {
942 "xl/workbook.xml":
943 '<workbook><workbookPr date1904="true"/><sheets><sheet name="Dates" r:id="a"/></sheets></workbook>',
944 "xl/_rels/workbook.xml.rels":
945 '<Relationships><Relationship Id="a" Target="worksheets/dates.xml"/></Relationships>',
946 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="14"/></cellXfs></styleSheet>',
947 "xl/worksheets/dates.xml":
948 "<worksheet><sheetData><row><c><v>1</v></c></row></sheetData></worksheet>",
949 },
950 expected: ["## Sheet: Dates", "1 [Excel numFmtId=14; date system 1904]"],
951 },
952 {
953 ext: "xlsx",
954 bounded: true,
955 parts: {
956 "xl/workbook.xml":
957 '<workbook><sheets><sheet name="Repeated" r:id="a"/><sheet name="Unneeded" r:id="missing"/></sheets></workbook>',
958 "xl/_rels/workbook.xml.rels":
959 '<Relationships><Relationship Id="a" Target="worksheets/repeated.xml"/></Relationships>',
960 "xl/sharedStrings.xml": `<sst><si><t>${"A".repeat(1_000_000 - "## Sheet: Repeated\n".length)}</t></si></sst>`,
961 "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>`,
962 },
963 expected: [
964 "## Sheet: Repeated",
965 "A".repeat(32),
966 "[Extracted text truncated at document extraction limits.]",
967 ],
968 },
969 {
970 ext: "pptx",
971 bounded: true,
972 parts: {
973 "ppt/presentation.xml": `<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"
974 xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
975 xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main">
976 <p:sldIdLst><p:sldId id="256" r:id="b"/><p:sldId id="257" r:id="a"/></p:sldIdLst>
977 <p:extLst><p:ext uri="{521415D9-36F7-43E2-AB2F-B90AF26B5E84}"><p14:sectionLst>
978 <p14:section name="Schedule" id="{01F07B81-39E6-4BBB-9B89-66EA253FBD29}">
979 <p14:sldIdLst><p14:sldId id="256"/><p14:sldId id="257"/></p14:sldIdLst>
980 </p14:section>
981 </p14:sectionLst></p:ext></p:extLst>
982 </p:presentation>`,
983 "ppt/_rels/presentation.xml.rels":
984 '<Relationships><Relationship Id="a" Target="slides/slide1.xml"/><Relationship Id="b" Target="slides/slide2.xml"/></Relationships>',
985 "ppt/slides/slide1.xml": "<p:sld><a:p><a:r><a:t>Departure</a:t></a:r></a:p></p:sld>",
986 "ppt/slides/slide2.xml": "<p:sld><a:p><a:r><a:t>Juniper Pier</a:t></a:r></a:p></p:sld>",
987 "ppt/slides/_rels/slide2.xml.rels":
988 '<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>',
989 "ppt/slides/_rels/slide1.xml.rels":
990 '<Relationships><Relationship Type="http://purl.oclc.org/ooxml/officeDocument/relationships/notesSlide" Target="/ppt/notesSlides/notes3.xml"/></Relationships>',
991 "ppt/notesSlides/notes7.xml":
992 '<p:notes><p:cSld><p:spTree><p:sp><p:nvSpPr><p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr></p:sp><p:sp><p:nvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:txBody><a:p><a:r><a:t>evacuation code ORCHID-81</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:nvPr><p:ph type="hdr" sz="quarter"/></p:nvPr></p:nvSpPr><p:txBody><a:p><a:r><a:t>Harbor briefing</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:nvPr><p:ph type="dt" idx="1"/></p:nvPr></p:nvSpPr><p:txBody><a:p><a:fld type="datetime1"><a:t>11/21/2026</a:t></a:fld></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:nvPr><p:ph type="ftr" sz="quarter" idx="4"/></p:nvPr></p:nvSpPr><p:txBody><a:p><a:r><a:t>Crew only</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:nvPr><p:ph type="sldNum" sz="quarter" idx="5"/></p:nvPr></p:nvSpPr><p:txBody><a:p><a:fld type="slidenum"><a:t>57</a:t></a:fld></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:notes>',
993 "ppt/notesSlides/notes3.xml":
994 "<p:notes><a:p><a:r><a:t>Board at gate 4</a:t></a:r></a:p></p:notes>",
995 "ppt/notesSlides/ignored.xml": "<p:notes><a:p>Unrelated notes</a:p></p:notes>",
996 },
997 expected: [
998 "## Slide 1",
999 "Juniper Pier\nNotes:\nevacuation code ORCHID-81",
1000 "## Slide 2",
1001 "Departure\nNotes:\nBoard at gate 4",
1002 ],
1003 occurrences: { text: "## Slide ", count: 2 },
1004 absent: [
1005 "Unrelated notes",
1006 "Harbor briefing",
1007 "11/21/2026",
1008 "Crew only",
1009 "57",
1010 "[Skipped document part",
1011 "[Extracted text truncated",
1012 ],
1013 },
1015 ext: "pptx",
1016 bounded: true,
1017 parts: {
1018 "ppt/presentation.xml":
1019 '<presentation><sldIdLst><sldId r:id="a"/></sldIdLst></presentation>',
1020 "ppt/_rels/presentation.xml.rels":
1021 '<Relationships><Relationship Id="a" Target="slides/a.xml"/></Relationships>',
1022 "ppt/slides/a.xml": "<slide><p>Slide text</p></slide>",
1023 "ppt/slides/_rels/a.xml.rels":
1024 '<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/empty.xml"/></Relationships>',
1025 "ppt/notesSlides/empty.xml":
1026 '<p:notes><p:cSld><p:spTree><p:sp><p:nvSpPr><p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr></p:sp><p:sp><p:nvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:txBody><a:p><a:endParaRPr/></a:p></p:txBody></p:sp><p:sp><p:nvSpPr><p:nvPr><p:ph type="sldNum" idx="5"/></p:nvPr></p:nvSpPr><p:txBody><a:p><a:fld type="slidenum"><a:t>57</a:t></a:fld></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:notes>',
1027 },
1028 expected: ["Slide text"],
1029 absent: ["Notes:", "57"],
1030 },
1031 ...[false, true].map((missing) => ({
1032 ext: "pptx",
1033 bounded: true,
1034 parts: {
1035 "ppt/presentation.xml":
1036 '<presentation><sldIdLst><sldId r:id="a"/></sldIdLst></presentation>',
1037 "ppt/_rels/presentation.xml.rels":
1038 '<Relationships><Relationship Id="a" Target="slides/a.xml"/></Relationships>',
1039 "ppt/slides/a.xml": "<slide><p>Slide text</p></slide>",
1040 "ppt/slides/_rels/a.xml.rels": `<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/${missing ? "missing" : "bad"}.xml"/></Relationships>`,
1041 "ppt/notesSlides/bad.xml": "<notes><p>Discard broken notes</notes>",
1042 },
1043 expected: [
1044 "Slide text",
1045 `[Skipped document part: ppt/notesSlides/${missing ? "missing" : "bad"}.xml (missing or invalid XML).]`,
1046 ],
1047 absent: ["Discard broken notes", "[Extracted text truncated"],
1048 })),
1050 ext: "pptx",
1051 bounded: true,
1052 parts: {
1053 "ppt/presentation.xml":
1054 '<presentation><sldIdLst><sldId r:id="a"/><sldId r:id="b"/></sldIdLst></presentation>',
1055 "ppt/_rels/presentation.xml.rels":
1056 '<Relationships><Relationship Id="a" Target="slides/a.xml"/><Relationship Id="b" Target="slides/b.xml"/></Relationships>',
1057 "ppt/slides/a.xml": `<slide><p>${"A".repeat(600_000)}</p></slide>`,
1058 "ppt/slides/b.xml": "<slide><p>Unneeded slide</p></slide>",
1059 "ppt/slides/_rels/a.xml.rels":
1060 '<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/a.xml"/></Relationships>',
1061 "ppt/notesSlides/a.xml": `<notes><p>evacuation code ORCHID-81 ${"B".repeat(600_000)} Unneeded notes</p></notes>`,
1062 },
1063 expected: [
1064 "## Slide 1",
1065 "A".repeat(32),
1066 "Notes:\nevacuation code ORCHID-81",
1067 "B".repeat(32),
1068 "[Extracted text truncated at document extraction limits.]",
1069 ],
1070 absent: ["Unneeded notes", "Unneeded slide", "## Slide 2"],
1071 },
1073 ext: "odt",
1074 parts: {
1075 "content.xml":
1076 '<office:document><text:h text:outline-level="2">\n Orchard\n</text:h><text:p>19<text:s text:c="3"/>violet<text:s/>crates <text:span>\n\t shipped</text:span> today<text:tab/>Dock<text:line-break/>Gate\u00a0B </text:p><text:p>Second</text:p><text:p>A<text:span><text:script>console.log(1);\n</text:script></text:span> B</text:p>' +
1078 "table-of-content",
1079 "illustration-index",
1080 "table-index",
1081 "object-index",
1082 "user-index",
1083 "alphabetical-index",
1084 "bibliography",
1086 .map(
1087 (name) =>
1088 `<text:${name}><text:${name}-source><text:index-title-template>Contents</text:index-title-template><text:${name}-entry-template><text:index-entry-span>: </text:index-entry-span></text:${name}-entry-template></text:${name}-source><text:index-body><text:index-title><text:p>Contents</text:p></text:index-title><text:p>Orchard 1</text:p></text:index-body></text:${name}>`,
1090 .join("") +
1091 "</office:document>",
1092 },
1093 expected: [
1094 `## Orchard\n19 violet crates shipped today\tDock\nGate\u00a0B\nSecond\nA B${"\nContents\nOrchard 1".repeat(7)}`,
1095 ],
1096 },
1098 ext: "ods",
1099 parts: {
1100 "content.xml":
1101 '<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>',
1102 },
1103 expected: ["## Sheet: Cargo", "Violet\t19\t27"],
1104 },
1106 ext: "ods",
1107 bounded: true,
1108 parts: {
1109 "content.xml":
1110 '<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>',
1111 },
1112 expected: ["## Sheet: Padded rows", "Left\t\t\tRight"],
1113 absent: ["[Extracted text truncated"],
1114 },
1116 ext: "ods",
1117 bounded: true,
1118 parts: {
1119 "content.xml":
1120 '<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>',
1121 },
1122 expected: ["## Sheet: Padded", "Populated"],
1123 absent: ["[Extracted text truncated", "\t"],
1124 },
1126 ext: "ods",
1127 bounded: true,
1128 parts: {
1129 "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>`,
1130 },
1131 expected: [
1132 "## Sheet: Repeated",
1133 "Lead ",
1134 " Tail\tLead ",
1135 "[Extracted text truncated at document extraction limits.]",
1136 ],
1137 },
1139 ext: "odp",
1140 parts: {
1141 "content.xml":
1142 "<office:document><draw:page><draw:frame><draw:text-box><text:p>\n First\n\t slide </text:p></draw:text-box></draw:frame></draw:page><draw:page><text:p>Second</text:p></draw:page></office:document>",
1143 },
1144 expected: ["## Slide 1\nFirst slide\n\n## Slide 2\nSecond"],
1145 },
1147 ext: "ods",
1148 bounded: true,
1149 parts: {
1150 "content.xml": `<office:document>${Array.from(
1151 { length: 256 },
1152 (_, index) =>
1153 `<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>`,
1154 ).join("")}</office:document>`,
1155 },
1156 expected: [
1157 "## Sheet: Shared",
1158 "B".repeat(32),
1159 "[Extracted text truncated at document extraction limits.]",
1160 ],
1161 absent: ["## Sheet: Unneeded"],
1162 },
1164 ext: "odt",
1165 bounded: true,
1166 parts: {
1167 "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>`,
1168 },
1169 expected: ["Before whitespace", "Unneeded"],
1170 absent: ["[Extracted text truncated"],
1171 },
1172 ...["odt", "odp", "ods"].flatMap((ext) =>
1173 [false, true].map((rows) => ({
1174 ext,
1175 bounded: true,
1176 parts: {
1177 "content.xml": `<office:document><draw:page>${Array.from(
1178 { length: 256 },
1179 () =>
1180 `<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>`,
1181 ).join(
1182 "",
1183 )}</draw:page><draw:page><text:p>Unneeded</text:p></draw:page></office:document>`,
1184 },
1185 expected: ["Budget ", "[Extracted text truncated at document extraction limits.]"],
1186 absent: ["Unneeded"],
1187 })),
1188 ),
1190 ext: "docx",
1191 bounded: true,
1192 parts: {
1193 "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>`,
1194 },
1195 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
1196 absent: ["Unneeded"],
1197 },
1199 ext: "pptx",
1200 bounded: true,
1201 parts: {
1202 "ppt/presentation.xml":
1203 '<p:presentation><p:sldIdLst><p:sldId r:id="a"/><p:sldId r:id="missing"/></p:sldIdLst></p:presentation>',
1204 "ppt/_rels/presentation.xml.rels":
1205 '<Relationships><Relationship Id="a" Target="slides/slide.xml"/></Relationships>',
1206 "ppt/slides/slide.xml": `<p:sld><a:p><a:t>${"A".repeat(1_000_100)}</a:t></a:p></p:sld>`,
1207 },
1208 expected: [
1209 "## Slide 1",
1210 "A".repeat(32),
1211 "[Extracted text truncated at document extraction limits.]",
1212 ],
1213 absent: ["## Slide 2"],
1214 },
1216 ext: "epub",
1217 bounded: true,
1218 parts: {
1219 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
1220 "book.opf":
1221 '<package><item id="a" href="a.xhtml"/><itemref idref="a"/><itemref idref="missing"/></package>',
1222 "a.xhtml": `<html><body><p>${"A".repeat(1_000_100)}</p></body></html>`,
1223 },
1224 expected: [
1225 "## Chapter 1",
1226 "A".repeat(32),
1227 "[Extracted text truncated at document extraction limits.]",
1228 ],
1229 absent: ["## Chapter 2"],
1230 },
1232 ext: "epub",
1233 parts: {
1234 "META-INF/container.xml":
1235 '<container><rootfile full-path="OEBPS/book.opf"/></container>',
1236 "OEBPS/book.opf":
1237 '<package><manifest><item id="a" href="a.xhtml"/><item id="b" href="b.xhtml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
1238 "OEBPS/a.xhtml":
1239 '<!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 <del>old</del></p></body></html>',
1240 "OEBPS/b.xhtml":
1241 '<!DOCTYPE html><html><head><title>My Novel</title><meta name="author" content="Hidden Author"/></head><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>',
1242 },
1243 expected: [
1244 "## Chapter 1",
1245 "\n# First chapter",
1246 "Larkspur",
1247 "Direct div",
1248 "Direct section",
1249 "Direct item emphasis trailing",
1250 "Account: A\nBalance: 731\nCurrency: USD",
1251 "Heading\tTotal",
1252 "Important value\t731",
1253 "Before Inner After\tNeighbor",
1254 "## Chapter 2",
1255 "Last chapter",
1256 "Price 10 8 old",
1257 ],
1258 absent: ["My Novel", "Hidden Author"],
1259 },
1260 ];
1261 for (const [caseIndex, item] of cases.entries()) {
1262 const local: Buffer[] = [];
1263 const central: Buffer[] = [];
1264 let offset = 0;
1265 for (const [name, content] of Object.entries(item.parts)) {
1266 const data = Buffer.from(content!);
1267 const compressed = /\.(bmp|bin)$/.test(name) ? NodeZlib.deflateRawSync(data) : data;
1268 const filename = Buffer.from(name);
1269 const header = Buffer.alloc(30);
1270 header.writeUInt32LE(0x04034b50);
1271 header.writeUInt16LE(20, 4);
1272 header.writeUInt16LE(compressed === data ? 0 : 8, 8);
1273 header.writeUInt32LE(NodeZlib.crc32(data), 14);
1274 header.writeUInt32LE(compressed.length, 18);
1275 header.writeUInt32LE(data.length, 22);
1276 header.writeUInt16LE(filename.length, 26);
1277 const directory = Buffer.alloc(46);
1278 directory.writeUInt32LE(0x02014b50);
1279 directory.writeUInt16LE(20, 4);
1280 directory.writeUInt16LE(20, 6);
1281 directory.writeUInt16LE(compressed === data ? 0 : 8, 10);
1282 directory.writeUInt32LE(NodeZlib.crc32(data), 16);
1283 directory.writeUInt32LE(compressed.length, 20);
1284 directory.writeUInt32LE(data.length, 24);
1285 directory.writeUInt16LE(filename.length, 28);
1286 directory.writeUInt32LE(offset, 42);
1287 local.push(header, filename, compressed);
1288 central.push(directory, filename);
1289 offset += header.length + filename.length + compressed.length;
1291 const end = Buffer.alloc(22);
1292 end.writeUInt32LE(0x06054b50);
1293 end.writeUInt16LE(central.length / 2, 8);
1294 end.writeUInt16LE(central.length / 2, 10);
1295 end.writeUInt32LE(Buffer.concat(central).length, 12);
1296 end.writeUInt32LE(offset, 16);
1297 const path = NodePath.join(config.attachmentsDir, `structure-${caseIndex}.${item.ext}`);
1298 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1299 const extracted = yield* Effect.promise(() => extractDocumentText(path, `.${item.ext}`));
1300 let previous = -1;
1301 for (const expected of item.expected) {
1302 const index = extracted.indexOf(expected);
1303 expect(index, `${item.ext}: ${expected} in ${extracted.slice(0, 500)}`).toBeGreaterThan(
1304 previous,
1305 );
1306 previous = index;
1308 if ("occurrences" in item)
1309 expect(extracted.split(item.occurrences.text).length - 1).toBe(item.occurrences.count);
1310 if ("absent" in item)
1311 for (const absent of item.absent) expect(extracted).not.toContain(absent);
1312 if (("bounded" in item && item.bounded) || item.ext === "epub") {
1313 expect(extracted.length).toBeLessThan(1_000_100);
1314 expect(extracted.match(/\[Extracted text truncated/g)?.length ?? 0).toBeLessThanOrEqual(
1315 1,
1316 );
1317 const documents = yield* DocumentText.DocumentText;
1318 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1319 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(extracted);
1321 if (item.ext === "docx") {
1322 end.writeUInt16LE(2049, 8);
1323 end.writeUInt16LE(2049, 10);
1324 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1325 yield* Effect.promise(async () => {
1326 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
1327 });
1328 end.writeUInt16LE(central.length / 2, 8);
1329 end.writeUInt16LE(central.length / 2, 10);
1330 central[0]!.writeUInt16LE(8, 10);
1331 central[0]!.writeUInt32LE(33 * 1024 * 1024, 24);
1332 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1333 yield* Effect.promise(async () => {
1334 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
1335 });
1338 const path = NodePath.join(config.attachmentsDir, "unicode.rtf");
1339 NodeFS.writeFileSync(
1340 path,
1341 String.raw`{\rtf1\ansi{\fonttbl hidden}Hello\tab world\par Unicode \u945?{\*\secret hidden}}`,
1342 );
1343 const extracted = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1344 expect(extracted).toContain("Hello\tworld\nUnicode α");
1345 expect(extracted).not.toContain("hidden");
1346​
1347 for (const [name, content, expected] of [
1349 "cyrillic-escaped",
1350 String.raw`{\rtf1\ansi\ansicpg1251 \'cf\'f0\'e8\'e2\'e5\'f2 {\ansicpg1252 \'e9} \'cc\'ee\'f1\'ea\'e2\'e0}`,
1351 "Привет é Москва",
1352 ],
1354 "cyrillic-raw",
1355 Buffer.concat([
1356 Buffer.from(String.raw`{\rtf1\ansi\ansicpg1251 `),
1357 Buffer.from([0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]),
1358 Buffer.from("}"),
1359 ]),
1360 "Привет",
1361 ],
1362 ] as const) {
1363 const encodedPath = NodePath.join(config.attachmentsDir, `${name}.rtf`);
1364 NodeFS.writeFileSync(encodedPath, content);
1365 expect(yield* Effect.promise(() => extractDocumentText(encodedPath, ".rtf"))).toBe(
1366 expected,
1367 );
1368 const documents = yield* DocumentText.DocumentText;
1369 expect(yield* documents.ensure(encodedPath)).toBe(encodedPath + ".txt");
1370 expect(NodeFS.readFileSync(encodedPath + ".txt", "utf8")).toBe(expected);
1372 const notebookPath = NodePath.join(config.attachmentsDir, "limited.ipynb");
1373 NodeFS.writeFileSync(
1374 notebookPath,
1375 JSON.stringify({ cells: Array.from({ length: 10_001 }, () => ({ source: "Kept" })) }),
1376 );
1377 const notebookLimited = yield* Effect.promise(() =>
1378 extractDocumentText(notebookPath, ".ipynb"),
1379 );
1380 expect(notebookLimited).toContain("## Cell 10000");
1381 expect(notebookLimited).not.toContain("## Cell 10001");
1382 expect(notebookLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1383 expect(yield* (yield* DocumentText.DocumentText).ensure(notebookPath)).toBe(
1384 notebookPath + ".txt",
1385 );
1386 expect(NodeFS.readFileSync(notebookPath + ".txt", "utf8")).toBe(notebookLimited);
1387 const errorPath = NodePath.join(config.attachmentsDir, "limited-error.ipynb");
1388 NodeFS.writeFileSync(
1389 errorPath,
1390 JSON.stringify({
1391 cells: [
1393 cell_type: "code",
1394 source: "1 / 0",
1395 outputs: [
1397 output_type: "error",
1398 ename: "ZeroDivisionError",
1399 evalue: "division by zero",
1400 traceback: ["\u001b[31m" + "trace".repeat(250_000) + "\u001b[0m", "After limit"],
1401 },
1402 ],
1403 },
1404 ],
1405 }),
1406 );
1407 const errorLimited = yield* Effect.promise(() => extractDocumentText(errorPath, ".ipynb"));
1408 expect(errorLimited).toContain("ZeroDivisionError: division by zero\ntrace");
1409 expect(errorLimited.length).toBeLessThan(1_000_100);
1410 expect(errorLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1411 expect(errorLimited).not.toContain("After limit");
1412 expect(errorLimited).not.toContain("\u001b");
1413 const deepPath = NodePath.join(config.attachmentsDir, "deep.rtf");
1414 NodeFS.writeFileSync(
1415 deepPath,
1416 String.raw`{\rtf1 Kept` + "{".repeat(128) + "Lost" + "}".repeat(129),
1417 );
1418 const deepLimited = yield* Effect.promise(() => extractDocumentText(deepPath, ".rtf"));
1419 expect(deepLimited).toBe("Kept\n\n[Extracted text truncated at document extraction limits.]");
1420 const unsupportedPath = NodePath.join(config.attachmentsDir, "unsupported-codepage.rtf");
1421 NodeFS.writeFileSync(unsupportedPath, String.raw`{\rtf1\ansi\ansicpg932 \'82\'a0}`);
1422 yield* Effect.promise(async () => {
1423 await expect(extractDocumentText(unsupportedPath, ".rtf")).rejects.toThrow(
1424 "Unsupported RTF code page",
1425 );
1426 });
1427 expect(yield* (yield* DocumentText.DocumentText).ensure(unsupportedPath)).toBeUndefined();
1428 expect(NodeFS.existsSync(unsupportedPath + ".txt")).toBe(false);
1429 NodeFS.writeFileSync(
1430 path,
1431 String.raw`{\rtf1 ` + "x".repeat(999_999) + String.raw`\u-10179?\u-8576? After}`,
1432 );
1433 const unicodeTruncated = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1434 expect(unicodeTruncated).toContain("[Extracted text truncated");
1435 expect(unicodeTruncated.isWellFormed()).toBe(true);
1436 expect(unicodeTruncated.startsWith("x".repeat(999_999))).toBe(true);
1437 NodeFS.writeFileSync(path, String.raw`{\rtf1 First` + " ".repeat(1_000_100) + "Last}");
1438 const whitespaceTruncated = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1439 expect(whitespaceTruncated).toBe(
1440 "First\n\n[Extracted text truncated at document extraction limits.]",
1441 );
1442 const documents = yield* DocumentText.DocumentText;
1443 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1444 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(whitespaceTruncated);
1445 NodeFS.truncateSync(path, 17 * 1024 * 1024);
1446 yield* Effect.promise(async () => {
1447 expect(await extractDocumentText(path, ".rtf")).toContain("[Extracted text truncated");
1448 });
1449 }).pipe(Effect.provide(layer)),
1450 );
1451 it.effect("keeps selected values intact and appends an actual readable server path", () =>
1452 Effect.gen(function* () {
1453 const config = yield* ServerConfig.ServerConfig;
1454 const path = NodePath.join(config.attachmentsDir, `${attachment.id}.txt`);
1455 NodeFS.writeFileSync(path, "spec");
1456 const original = { q: ["First", "Second"], other: "No file" };
1457 const answers = yield* appendUserInputAttachmentPaths({
1458 answers: original,
1459 attachmentsDir: config.attachmentsDir,
1460 attachmentsByQuestionId: { q: [attachment] },
1461 });
1462 expect(answers.q).toEqual([
1463 "First",
1464 "Second",
1465 `Attached file "spec \\"final\\".txt": ${JSON.stringify(path)}`,
1466 ]);
1467 expect(answers.other).toBe("No file");
1468 expect(original.q).toEqual(["First", "Second"]);
1469 expect(NodeFS.readFileSync(path, "utf8")).toBe("spec");
1470 const specialKey = yield* appendUserInputAttachmentPaths({
1471 answers: {},
1472 attachmentsDir: config.attachmentsDir,
1473 attachmentsByQuestionId: { ["__proto__"]: [attachment] },
1474 });
1475 expect(Object.keys(specialKey)).toEqual(["__proto__"]);
1476 expect(specialKey["__proto__"]).toContain(JSON.stringify(path));
1477 }).pipe(Effect.provide(layer)),
1478 );
1479 it.effect("does not send an unavailable attachment path", () =>
1480 Effect.gen(function* () {
1481 const config = yield* ServerConfig.ServerConfig;
1482 const result = yield* appendUserInputAttachmentPaths({
1483 answers: { q: "" },
1484 attachmentsDir: config.attachmentsDir,
1485 attachmentsByQuestionId: { q: [attachment] },
1486 }).pipe(Effect.result);
1487 expect(result._tag).toBe("Failure");
1488 }).pipe(Effect.provide(layer)),
1489 );
1490});