llm-large-files 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +319 -1
- package/README.md +10 -8
- package/dist/analyze.d.ts +3 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +109 -14
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +4 -1
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +3 -3
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +72 -17
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +65 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +6 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +5 -1
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +6 -0
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +7 -20
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +49 -751
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +9 -5
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +20 -3
- package/dist/gemini/generate.js.map +1 -1
- package/dist/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +48 -12
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.js.map +1 -1
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +8 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +69 -15
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- package/dist/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.js.map +1 -0
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +15 -1
- package/dist/openai/adapter.js.map +1 -1
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +2 -6
- package/dist/pdf-pages.js.map +1 -1
- package/dist/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.js.map +1 -0
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +1 -1
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.js.map +1 -1
- package/dist/search.d.ts +99 -22
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +744 -140
- package/dist/search.js.map +1 -1
- package/dist/text-index.d.ts +3 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +3 -1
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +27 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +225 -23
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +200 -12
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +3 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- package/docs/README.md +8 -8
- package/docs/getting-started.md +1 -1
- package/docs/guides/costs-and-limits.md +7 -5
- package/docs/guides/deployment.md +95 -29
- package/docs/guides/errors-and-reliability.md +23 -10
- package/docs/guides/pdfs.md +127 -74
- package/docs/guides/storage.md +1 -1
- package/docs/guides/testing.md +5 -1
- package/docs/guides/web-app.md +10 -9
- package/docs/how-it-works.md +73 -50
- package/docs/reference/ask.md +26 -8
- package/docs/reference/errors-and-retries.md +5 -3
- package/docs/reference/events.md +14 -6
- package/docs/reference/gemini.md +6 -2
- package/docs/reference/library.md +205 -74
- package/docs/reference/node.md +200 -22
- package/docs/reference/openai.md +1 -1
- package/docs/reference/tools.md +170 -22
- package/docs/security.md +114 -69
- package/docs/troubleshooting.md +40 -20
- package/package.json +6 -2
- package/src/analyze.ts +117 -13
- package/src/anthropic/adapter.ts +4 -1
- package/src/ask.ts +73 -17
- package/src/decode.ts +89 -0
- package/src/errors.ts +108 -0
- package/src/events.ts +10 -1
- package/src/evidence.ts +6 -0
- package/src/extract.ts +52 -709
- package/src/gemini/adapter.ts +9 -5
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/generate.ts +19 -3
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/index.ts +2 -1
- package/src/library.ts +43 -12
- package/src/limiter.ts +6 -1
- package/src/model.ts +8 -1
- package/src/node/handlers.ts +66 -16
- package/src/node/index.ts +2 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +14 -1
- package/src/pdf-pages.ts +2 -5
- package/src/peers.ts +29 -0
- package/src/plan.ts +2 -0
- package/src/ranged.ts +4 -2
- package/src/search.ts +738 -146
- package/src/text-index.ts +4 -2
- package/src/text.ts +214 -23
- package/src/tools.ts +192 -12
- package/src/types.ts +3 -3
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
package/dist/extract.js
CHANGED
|
@@ -1,767 +1,49 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { decodeText, plainText } from "./decode.js";
|
|
2
|
+
import { html } from "./html.js";
|
|
2
3
|
import { TimeSlicer } from "./pause.js";
|
|
3
4
|
import { layoutPage, plainPageText } from "./pdf-layout.js";
|
|
4
5
|
import { findPicturePages, parsePdf } from "./pdf-pictures.js";
|
|
5
6
|
import { checkPageWork, HeavyPage } from "./pdf-work.js";
|
|
6
7
|
import { formatBytes } from "./plan.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
8
|
+
import { docx, pptx } from "./office.js";
|
|
9
|
+
import { importPeer } from "./peers.js";
|
|
10
|
+
import { plural, utf8Bytes } from "./text.js";
|
|
11
|
+
import { xlsx } from "./xlsx.js";
|
|
12
|
+
export { decodeText };
|
|
13
|
+
export { HIDDEN_SLIDE, HIDDEN_TEXT, officeXmlParagraphs, SPEAKER_NOTES } from "./office.js";
|
|
9
14
|
const EXTENSION_FORMATS = {
|
|
10
15
|
log: "log", out: "log", err: "log",
|
|
11
16
|
md: "markdown", markdown: "markdown",
|
|
12
17
|
json: "json", jsonl: "json", ndjson: "json",
|
|
13
18
|
csv: "csv", tsv: "csv",
|
|
14
|
-
pdf: "pdf", docx: "docx", pptx: "pptx",
|
|
19
|
+
pdf: "pdf", docx: "docx", docm: "docx", pptx: "pptx", pptm: "pptx",
|
|
20
|
+
xlsx: "xlsx", xlsm: "xlsx", xltx: "xlsx", xltm: "xlsx",
|
|
21
|
+
html: "html", htm: "html", xhtml: "html",
|
|
15
22
|
};
|
|
16
23
|
const MIME_FORMATS = {
|
|
17
24
|
"application/pdf": "pdf",
|
|
18
25
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
|
|
19
26
|
"application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
|
|
27
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
|
|
28
|
+
"application/vnd.ms-excel.sheet.macroenabled.12": "xlsx",
|
|
29
|
+
"text/html": "html",
|
|
30
|
+
"application/xhtml+xml": "html",
|
|
20
31
|
"text/markdown": "markdown",
|
|
21
32
|
"application/json": "json",
|
|
22
33
|
"text/csv": "csv",
|
|
23
34
|
};
|
|
24
|
-
/** Picks a format from the file name, then the MIME type. Unknown text-like files are "text". */
|
|
25
|
-
export function detectFormat(name, mimeType) {
|
|
26
|
-
const extension = name.toLowerCase().split(".").at(-1) ?? "";
|
|
27
|
-
return EXTENSION_FORMATS[extension] ?? MIME_FORMATS[mimeType.toLowerCase()] ?? "text";
|
|
28
|
-
}
|
|
29
|
-
const NOT_TEXT = "This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.";
|
|
30
|
-
/**
|
|
31
|
-
* Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs).
|
|
32
|
-
* A file that is not UTF-8 is read in the older encoding it was saved in, or as UTF-8 with its
|
|
33
|
-
* characters that are not valid as U+FFFD (see encoding.ts). Throws a readable error for
|
|
34
|
-
* compressed and other binary files.
|
|
35
|
-
*/
|
|
36
|
-
export function decodeText(bytes) {
|
|
37
|
-
const steps = decodeSteps(bytes);
|
|
38
|
-
let step = steps.next();
|
|
39
|
-
while (!step.done)
|
|
40
|
-
step = steps.next();
|
|
41
|
-
return step.value.text;
|
|
42
|
-
}
|
|
43
|
-
/** `decodeText` in steps: it yields between the steps of a file that is not valid UTF-8. */
|
|
44
|
-
function* decodeSteps(bytes) {
|
|
45
|
-
if (bytes[0] === 0xff && bytes[1] === 0xfe)
|
|
46
|
-
return { text: new TextDecoder("utf-16le").decode(bytes.subarray(2)) };
|
|
47
|
-
if (bytes[0] === 0xfe && bytes[1] === 0xff)
|
|
48
|
-
return { text: new TextDecoder("utf-16be").decode(bytes.subarray(2)) };
|
|
49
|
-
// Rotated logs often arrive as app.log.gz. Compressed bytes have few zeros, so name them here.
|
|
50
|
-
if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
|
|
51
|
-
throw new Error("This file is gzip-compressed. Decompress it, then attach the text file inside.");
|
|
52
|
-
}
|
|
53
|
-
if (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) {
|
|
54
|
-
throw new Error("This file is a ZIP archive. Extract it, then attach the text file you need.");
|
|
55
|
-
}
|
|
56
|
-
const sample = bytes.subarray(0, 8_192);
|
|
57
|
-
let zeros = 0;
|
|
58
|
-
for (const byte of sample)
|
|
59
|
-
if (byte === 0)
|
|
60
|
-
zeros++;
|
|
61
|
-
// UTF-16 without a BOM: about half the bytes of ASCII text are zero.
|
|
62
|
-
if (sample.length > 64 && zeros / sample.length > 0.3) {
|
|
63
|
-
let oddZeros = 0;
|
|
64
|
-
let evenText = 0;
|
|
65
|
-
for (let index = 0; index < sample.length; index++) {
|
|
66
|
-
if (index % 2 === 1 && sample[index] === 0)
|
|
67
|
-
oddZeros++;
|
|
68
|
-
if (index % 2 === 0 && sample[index] !== 0)
|
|
69
|
-
evenText++;
|
|
70
|
-
}
|
|
71
|
-
const half = sample.length / 2;
|
|
72
|
-
if (oddZeros / half > 0.6 && evenText / half > 0.6)
|
|
73
|
-
return { text: new TextDecoder("utf-16le").decode(bytes) };
|
|
74
|
-
}
|
|
75
|
-
if (sample.length > 0 && zeros / sample.length > 0.01)
|
|
76
|
-
throw new Error(NOT_TEXT);
|
|
77
|
-
// Compressed, encrypted, and media files spread control bytes evenly: about 1 byte in 10.
|
|
78
|
-
// Text has almost none, in UTF-8 or in a legacy single-byte encoding. Tab, line breaks, form
|
|
79
|
-
// feed, and ESC (colour codes) do not count.
|
|
80
|
-
let controls = 0;
|
|
81
|
-
for (const byte of sample) {
|
|
82
|
-
if (byte < 0x09 || (byte > 0x0d && byte < 0x20 && byte !== 0x1b) || byte === 0x7f)
|
|
83
|
-
controls++;
|
|
84
|
-
}
|
|
85
|
-
if (sample.length >= 64 && controls / sample.length > 0.03)
|
|
86
|
-
throw new Error(NOT_TEXT);
|
|
87
|
-
try {
|
|
88
|
-
return { text: new TextDecoder("utf-8", { fatal: true }).decode(bytes) };
|
|
89
|
-
}
|
|
90
|
-
catch (error) {
|
|
91
|
-
if (!(error instanceof TypeError))
|
|
92
|
-
throw error;
|
|
93
|
-
}
|
|
94
|
-
// Not valid UTF-8: decoded as it is, the text would be replacement characters.
|
|
95
|
-
return yield* decodeNotUtf8(bytes);
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
* Text files. One that is not UTF-8 is read in the older encoding it was saved in, when that can
|
|
99
|
-
* be recognized, and other requests get a turn while it is read.
|
|
100
|
-
*/
|
|
101
|
-
const plainText = async (bytes, input) => {
|
|
102
|
-
const slicer = new TimeSlicer(input?.signal);
|
|
103
|
-
const steps = decodeSteps(bytes);
|
|
104
|
-
let step = steps.next();
|
|
105
|
-
// Only a file that is not UTF-8 takes steps: its decoding is told as one piece of progress, at the end.
|
|
106
|
-
const stepped = !step.done;
|
|
107
|
-
while (!step.done) {
|
|
108
|
-
await slicer.maybePause();
|
|
109
|
-
step = steps.next();
|
|
110
|
-
}
|
|
111
|
-
if (stepped)
|
|
112
|
-
input?.onProgress?.({ stage: "decode", done: bytes.byteLength, total: bytes.byteLength, unit: "bytes" });
|
|
113
|
-
const { text, encoding, replacedCharacters } = step.value;
|
|
114
|
-
return { text, ...(encoding ? { encoding } : {}), ...(replacedCharacters ? { replacedCharacters } : {}) };
|
|
115
|
-
};
|
|
116
|
-
function decodeXmlEntities(value) {
|
|
117
|
-
return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (match, entity) => {
|
|
118
|
-
const lower = entity.toLowerCase();
|
|
119
|
-
if (lower === "amp")
|
|
120
|
-
return "&";
|
|
121
|
-
if (lower === "lt")
|
|
122
|
-
return "<";
|
|
123
|
-
if (lower === "gt")
|
|
124
|
-
return ">";
|
|
125
|
-
if (lower === "quot")
|
|
126
|
-
return "\"";
|
|
127
|
-
if (lower === "apos")
|
|
128
|
-
return "'";
|
|
129
|
-
const code = lower.startsWith("#x") ? Number.parseInt(lower.slice(2), 16) : Number.parseInt(lower.slice(1), 10);
|
|
130
|
-
return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
/** A tag name is read up to this many characters: the names that matter here are short. */
|
|
134
|
-
const MAX_TAG_NAME = 64;
|
|
135
|
-
/** Paragraphs inside paragraphs, at most. Real files nest two or three: a text box in a paragraph. */
|
|
136
|
-
const MAX_PARAGRAPH_DEPTH = 32;
|
|
137
|
-
/** Paragraphs with text read from one Office file, at most: a document of 10,000 pages has about 300,000. */
|
|
138
|
-
const MAX_OFFICE_PARAGRAPHS = 1_000_000;
|
|
139
|
-
/** Characters of text kept from one Office file, at most, whatever `maxTextBytes` allows: about 10,000 dense pages. */
|
|
140
|
-
const MAX_OFFICE_CHARACTERS = 32_000_000;
|
|
141
|
-
/**
|
|
142
|
-
* The text of an open paragraph is counted as written in the XML, where `"` is six characters
|
|
143
|
-
* for one: past this many times the limit, it is refused before the paragraph closes.
|
|
144
|
-
*/
|
|
145
|
-
const MAX_ENTITY_GROWTH = 6;
|
|
146
|
-
/** Below this length V8 copies a slice of a string; from it on, a slice keeps the whole string it was cut from. */
|
|
147
|
-
const SLICE_COPIED_BELOW = 13;
|
|
148
|
-
/**
|
|
149
|
-
* Written before each line of the text that Word hides (a run marked `<w:vanish/>`), after the text
|
|
150
|
-
* of its paragraph that shows: a person reading the document does not see it. Each line is marked,
|
|
151
|
-
* so hidden text cannot end the mark and pass for text that shows.
|
|
152
|
-
*/
|
|
153
|
-
export const HIDDEN_TEXT = "[Hidden text, not shown in the document]";
|
|
154
|
-
/** Added to the heading of a slide that the slide show skips (`<p:sld show="0">`). */
|
|
155
|
-
export const HIDDEN_SLIDE = "(hidden, not shown in the slide show)";
|
|
156
|
-
/**
|
|
157
|
-
* The one attribute read of `w:vanish` and of `p:sld`, and the values that count:
|
|
158
|
-
* `<w:vanish w:val="0"/>` turns hiding off (`<w:vanish/>` and any other value turn it on), and a
|
|
159
|
-
* slide with `show="0"` is hidden. Letter case counts in the value of `show`, and not in that of
|
|
160
|
-
* `w:val`. It counts in names, as in XML: `W:VAL` is another attribute.
|
|
161
|
-
*/
|
|
162
|
-
const VANISH_OFF = { name: "w:val", values: ["0", "false", "off"], anyCase: true };
|
|
163
|
-
const SLIDE_NOT_SHOWN = { name: "show", values: ["0", "false"], anyCase: false };
|
|
164
|
-
/** Characters kept of an attribute's name and of the value wanted: more than the longest of those above. */
|
|
165
|
-
const MAX_ATTRIBUTE_PART = 6;
|
|
166
|
-
/**
|
|
167
|
-
* A line of hidden text longer than this is cut into pieces, each marked. A mark and its piece then
|
|
168
|
-
* fit on one line, which ingest does not cut: past `MAX_LINE_CHARACTERS` it would put the rest of
|
|
169
|
-
* the hidden line on a line of its own, without the mark.
|
|
170
|
-
*/
|
|
171
|
-
const HIDDEN_PIECE = MAX_LINE_CHARACTERS - HIDDEN_TEXT.length - 1;
|
|
172
|
-
/**
|
|
173
|
-
* What ends a line of hidden text: a line break, a carriage return (ingest makes it one), a U+0085
|
|
174
|
-
* (ingest makes it one in a text with no other line break), or a line or paragraph separator
|
|
175
|
-
* (U+2028, U+2029), which a model may take for one. A new marked line where ingest removes the
|
|
176
|
-
* U+0085 instead does no harm.
|
|
177
|
-
*/
|
|
178
|
-
const HIDDEN_LINE_END = /[\r\n\x85\u2028\u2029]/g;
|
|
179
|
-
/** Where a line of hidden text starts: at a character that is not white space, nor a U+0085. */
|
|
180
|
-
const NOT_SPACE = /[^\s\x85]/g;
|
|
181
|
-
/**
|
|
182
|
-
* Reads one attribute of a tag as the tag goes past, a character at a time, in whatever pieces the
|
|
183
|
-
* XML comes: whether its value is one of those wanted. It keeps a few characters, whatever the
|
|
184
|
-
* length of the tag, and looks at names and values apart, so a value that holds `w:val="0"` is not
|
|
185
|
-
* read as the attribute.
|
|
186
|
-
*/
|
|
187
|
-
class AttributeReader {
|
|
188
|
-
wanted;
|
|
189
|
-
/** The name being read, or the last one read, cut after `MAX_ATTRIBUTE_PART` characters. */
|
|
190
|
-
name = "";
|
|
191
|
-
/** Whether the next character of a name starts a new one. */
|
|
192
|
-
ended = true;
|
|
193
|
-
/** Whether "=" came after the name wanted, so the next value is its value. */
|
|
194
|
-
assigned = false;
|
|
195
|
-
/** The value of the attribute wanted, while it is read. */
|
|
196
|
-
value;
|
|
197
|
-
/** Whether the attribute wanted has one of the values wanted. */
|
|
198
|
-
found = false;
|
|
199
|
-
constructor(wanted) {
|
|
200
|
-
this.wanted = wanted;
|
|
201
|
-
}
|
|
202
|
-
/** A character of the tag after its name, outside a value. A quote that opens a value is not one. */
|
|
203
|
-
outside(code) {
|
|
204
|
-
if (code === 32 || code === 9 || code === 10 || code === 13) {
|
|
205
|
-
this.ended = true;
|
|
206
|
-
}
|
|
207
|
-
else if (code === 61) {
|
|
208
|
-
this.assigned = this.name === this.wanted.name;
|
|
209
|
-
this.name = "";
|
|
210
|
-
this.ended = true;
|
|
211
|
-
}
|
|
212
|
-
else {
|
|
213
|
-
if (this.ended) {
|
|
214
|
-
this.name = "";
|
|
215
|
-
this.ended = false;
|
|
216
|
-
this.assigned = false;
|
|
217
|
-
}
|
|
218
|
-
if (this.name.length < MAX_ATTRIBUTE_PART)
|
|
219
|
-
this.name += String.fromCharCode(code);
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
/** A quote opens a value. */
|
|
223
|
-
open() {
|
|
224
|
-
if (this.assigned)
|
|
225
|
-
this.value = "";
|
|
226
|
-
this.assigned = false;
|
|
227
|
-
}
|
|
228
|
-
/** A character of a value. */
|
|
229
|
-
inValue(code) {
|
|
230
|
-
if (this.value !== undefined && this.value.length < MAX_ATTRIBUTE_PART)
|
|
231
|
-
this.value += String.fromCharCode(code);
|
|
232
|
-
}
|
|
233
|
-
/** The quote that closes a value. */
|
|
234
|
-
close() {
|
|
235
|
-
if (this.value !== undefined) {
|
|
236
|
-
this.found = this.wanted.values.includes(this.wanted.anyCase ? this.value.toLowerCase() : this.value);
|
|
237
|
-
this.value = undefined;
|
|
238
|
-
}
|
|
239
|
-
this.name = "";
|
|
240
|
-
this.ended = true;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
const NO_OFFICE_LIMITS = { kind: "file", maxCharacters: MAX_OFFICE_CHARACTERS, byTextLimit: false };
|
|
244
|
-
/**
|
|
245
|
-
* Collects the text of each paragraph of Office XML (`<w:p>` in Word, `<a:p>` in PowerPoint) in one
|
|
246
|
-
* pass, with no XML parser. The XML can come in pieces, as it is unpacked: a tag cut between two
|
|
247
|
-
* pieces is read whole. Every character is looked at once, so the time follows the length of the
|
|
248
|
-
* XML whatever its shape: a file of unclosed tags costs what a file of closed ones does.
|
|
249
|
-
*
|
|
250
|
-
* - A paragraph inside another one (the text box of a shape anchored in a paragraph) is a paragraph
|
|
251
|
-
* of its own, after the one it is anchored in, which keeps its text before and after the box.
|
|
252
|
-
* - `mc:Fallback` repeats `mc:Choice` for older programs, so it is skipped: a text box is read once.
|
|
253
|
-
* - Paragraph properties hold no text. Their tab stops are not tabs.
|
|
254
|
-
* - In Word, the text of a hidden run (`<w:vanish/>` in the run's own properties) comes after the
|
|
255
|
-
* text of its paragraph that shows, each line marked with `HIDDEN_TEXT`. Text hidden by a style
|
|
256
|
-
* is not told apart. In PowerPoint, `hiddenSlide` says whether the slide show skips the slide.
|
|
257
|
-
*
|
|
258
|
-
* What it keeps in memory is bounded by the text, not by the XML: a paragraph becomes one string
|
|
259
|
-
* when it closes, an empty one is dropped, and a file that nests paragraphs past
|
|
260
|
-
* `MAX_PARAGRAPH_DEPTH`, or has more text or paragraphs than one document holds, is refused.
|
|
261
|
-
*/
|
|
262
|
-
class OfficeText {
|
|
263
|
-
limits;
|
|
264
|
-
count;
|
|
265
|
-
paragraphTag;
|
|
266
|
-
paragraphEnd;
|
|
267
|
-
textTag;
|
|
268
|
-
textEnd;
|
|
269
|
-
propertiesTag;
|
|
270
|
-
propertiesEnd;
|
|
271
|
-
tabTag;
|
|
272
|
-
breakTags;
|
|
273
|
-
/** Word marks hidden runs; PowerPoint hides whole slides. */
|
|
274
|
-
word;
|
|
275
|
-
/** The one tag whose attributes are read: `w:vanish` in Word, the slide's `p:sld` in PowerPoint. */
|
|
276
|
-
attributesTag;
|
|
277
|
-
/** The attribute read of `attributesTag`, and the values that count. */
|
|
278
|
-
attribute;
|
|
279
|
-
/** The text of each paragraph, in the order the paragraphs start: null while it is open, "" when empty. */
|
|
280
|
-
paragraphs = [];
|
|
281
|
-
/**
|
|
282
|
-
* The paragraphs that are open, the innermost last: where each goes in `paragraphs`, its text so
|
|
283
|
-
* far (that which shows, and that which Word hides), and its length. In Word, also how many runs
|
|
284
|
-
* are open (a ruby's runs are inside a run), how deep the outermost hidden one is (0: none is
|
|
285
|
-
* hidden), and how deep in run properties the reading is.
|
|
286
|
-
*/
|
|
287
|
-
open = [];
|
|
288
|
-
/** Characters held in the paragraphs that are open, as written in the XML. */
|
|
289
|
-
pending = 0;
|
|
290
|
-
inText = false;
|
|
291
|
-
inProperties = 0;
|
|
292
|
-
inFallback = 0;
|
|
293
|
-
/**
|
|
294
|
-
* The tag being read, from its "<": its name so far, the quote of a value it is in, its last
|
|
295
|
-
* character, and for `attributesTag` the reader of its attribute.
|
|
296
|
-
*/
|
|
297
|
-
tag;
|
|
298
|
-
/** A PowerPoint slide that the slide show skips (`<p:sld show="0">`). */
|
|
299
|
-
hiddenSlide = false;
|
|
300
|
-
/** `count`: what the other parts of the same file held, shared with them. */
|
|
301
|
-
constructor(prefix, limits = NO_OFFICE_LIMITS, count = { characters: 0, paragraphs: 0 }) {
|
|
302
|
-
this.limits = limits;
|
|
303
|
-
this.count = count;
|
|
304
|
-
this.paragraphTag = `${prefix}:p`;
|
|
305
|
-
this.paragraphEnd = `/${prefix}:p`;
|
|
306
|
-
this.textTag = `${prefix}:t`;
|
|
307
|
-
this.textEnd = `/${prefix}:t`;
|
|
308
|
-
this.propertiesTag = `${prefix}:pPr`;
|
|
309
|
-
this.propertiesEnd = `/${prefix}:pPr`;
|
|
310
|
-
this.tabTag = `${prefix}:tab`;
|
|
311
|
-
this.breakTags = new Set([`${prefix}:br`, `${prefix}:cr`]);
|
|
312
|
-
this.word = prefix === "w";
|
|
313
|
-
this.attributesTag = this.word ? "w:vanish" : "p:sld";
|
|
314
|
-
this.attribute = this.word ? VANISH_OFF : SLIDE_NOT_SHOWN;
|
|
315
|
-
}
|
|
316
|
-
write(xml) {
|
|
317
|
-
const length = xml.length;
|
|
318
|
-
let at = 0;
|
|
319
|
-
while (at < length) {
|
|
320
|
-
const tag = this.tag;
|
|
321
|
-
if (!tag) {
|
|
322
|
-
const start = xml.indexOf("<", at);
|
|
323
|
-
const end = start === -1 ? length : start;
|
|
324
|
-
if (end > at && this.inText && this.inProperties === 0 && this.inFallback === 0)
|
|
325
|
-
this.add(xml.slice(at, end));
|
|
326
|
-
if (start === -1)
|
|
327
|
-
return;
|
|
328
|
-
this.tag = { name: "", named: false, quote: 0, last: 0, attributes: undefined };
|
|
329
|
-
at = start + 1;
|
|
330
|
-
continue;
|
|
331
|
-
}
|
|
332
|
-
for (; at < length; at++) {
|
|
333
|
-
const code = xml.charCodeAt(at);
|
|
334
|
-
if (tag.quote !== 0) {
|
|
335
|
-
if (code === tag.quote) {
|
|
336
|
-
tag.quote = 0;
|
|
337
|
-
tag.attributes?.close();
|
|
338
|
-
}
|
|
339
|
-
else {
|
|
340
|
-
tag.attributes?.inValue(code);
|
|
341
|
-
}
|
|
342
|
-
continue;
|
|
343
|
-
}
|
|
344
|
-
if (!tag.named) {
|
|
345
|
-
// A name ends at white space, at ">", or at the "/" of "<w:br/>". "</w:p>" starts with one.
|
|
346
|
-
if (code === 62 || code === 32 || code === 9 || code === 10 || code === 13 || (code === 47 && tag.name !== "")) {
|
|
347
|
-
tag.named = true;
|
|
348
|
-
if (tag.name === this.attributesTag)
|
|
349
|
-
tag.attributes = new AttributeReader(this.attribute);
|
|
350
|
-
}
|
|
351
|
-
else {
|
|
352
|
-
if (tag.name.length < MAX_TAG_NAME)
|
|
353
|
-
tag.name += xml[at];
|
|
354
|
-
continue;
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
if (code === 62)
|
|
358
|
-
break;
|
|
359
|
-
if (code === 34 || code === 39) {
|
|
360
|
-
tag.quote = code;
|
|
361
|
-
tag.attributes?.open();
|
|
362
|
-
}
|
|
363
|
-
else {
|
|
364
|
-
tag.attributes?.outside(code);
|
|
365
|
-
if (code !== 32 && code !== 9 && code !== 10 && code !== 13)
|
|
366
|
-
tag.last = code;
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
if (at === length)
|
|
370
|
-
return; // The tag goes on in the next piece.
|
|
371
|
-
this.tag = undefined;
|
|
372
|
-
this.read(tag.name, tag.last === 47, tag.attributes?.found ?? false);
|
|
373
|
-
at++;
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
/** The text of each paragraph that has some, in the order the paragraphs start. */
|
|
377
|
-
texts() {
|
|
378
|
-
// A paragraph never closed keeps the text it has, as when the file ends inside it.
|
|
379
|
-
while (this.open.length > 0)
|
|
380
|
-
this.close();
|
|
381
|
-
return this.paragraphs.filter((text) => !!text);
|
|
382
|
-
}
|
|
383
|
-
/** Adds text to the innermost open paragraph. */
|
|
384
|
-
add(piece) {
|
|
385
|
-
const paragraph = this.open.at(-1);
|
|
386
|
-
if (!paragraph)
|
|
387
|
-
return;
|
|
388
|
-
this.pending += piece.length;
|
|
389
|
-
paragraph.length += piece.length;
|
|
390
|
-
// The decoded text is counted when its paragraph closes. Until then, what is held is bounded too.
|
|
391
|
-
if (this.pending > this.limits.maxCharacters * MAX_ENTITY_GROWTH)
|
|
392
|
-
throw this.tooMuchText();
|
|
393
|
-
if (paragraph.hiddenFrom !== 0)
|
|
394
|
-
(paragraph.hidden ??= []).push(piece);
|
|
395
|
-
else
|
|
396
|
-
paragraph.pieces.push(piece);
|
|
397
|
-
}
|
|
398
|
-
tooMuchText() {
|
|
399
|
-
const { kind, maxCharacters, byTextLimit } = this.limits;
|
|
400
|
-
return new Error(byTextLimit
|
|
401
|
-
? `This ${kind} holds more than ${formatBytes(maxCharacters)} of text, more than is kept from one file. Split it, and attach the part you need.`
|
|
402
|
-
: `This ${kind} holds more than ${Math.round(maxCharacters / 1_000_000)} million characters of text, more than is read from one file. Split it, and attach the part you need.`);
|
|
403
|
-
}
|
|
404
|
-
/** Closes the innermost open paragraph: its text becomes one string, or it is dropped when empty. */
|
|
405
|
-
close() {
|
|
406
|
-
const paragraph = this.open.pop();
|
|
407
|
-
if (!paragraph)
|
|
408
|
-
return;
|
|
409
|
-
this.pending -= paragraph.length;
|
|
410
|
-
const shown = decodeXmlEntities(paragraph.pieces.join(""));
|
|
411
|
-
const text = paragraph.hidden ? this.withHiddenText(shown, decodeXmlEntities(paragraph.hidden.join(""))) : shown;
|
|
412
|
-
if (text.trim()) {
|
|
413
|
-
this.count.characters += text.length;
|
|
414
|
-
if (this.count.characters > this.limits.maxCharacters)
|
|
415
|
-
throw this.tooMuchText();
|
|
416
|
-
if (++this.count.paragraphs > MAX_OFFICE_PARAGRAPHS) {
|
|
417
|
-
throw new Error(`This ${this.limits.kind} has more than ${MAX_OFFICE_PARAGRAPHS.toLocaleString("en-US")} paragraphs, more than a document holds. It may be built to exhaust the server, so it is not read.`);
|
|
418
|
-
}
|
|
419
|
-
// A copy, not a slice of the piece of XML it came from: a slice would keep all that XML in memory.
|
|
420
|
-
this.paragraphs[paragraph.slot] = text.length < SLICE_COPIED_BELOW ? text : (" " + text).slice(1);
|
|
421
|
-
}
|
|
422
|
-
else if (paragraph.slot === this.paragraphs.length - 1) {
|
|
423
|
-
this.paragraphs.pop();
|
|
424
|
-
}
|
|
425
|
-
else {
|
|
426
|
-
this.paragraphs[paragraph.slot] = "";
|
|
427
|
-
}
|
|
428
|
-
}
|
|
429
|
-
/**
|
|
430
|
-
* A paragraph's text that shows, then each line of its hidden text, marked with `HIDDEN_TEXT`. A
|
|
431
|
-
* long hidden line is cut into pieces of `HIDDEN_PIECE` characters at most, each marked. The marks
|
|
432
|
-
* make the text longer than the XML it came from, so it is refused as soon as it holds more than
|
|
433
|
-
* the room left under the limit, not once it is built.
|
|
434
|
-
*/
|
|
435
|
-
withHiddenText(shown, hidden) {
|
|
436
|
-
const room = this.limits.maxCharacters - this.count.characters;
|
|
437
|
-
const lines = shown.trim() ? [shown] : [];
|
|
438
|
-
// The length of the lines joined with line breaks.
|
|
439
|
-
let length = lines.length > 0 ? shown.length : -1;
|
|
440
|
-
let marked = 0;
|
|
441
|
-
// Where the line being marked ends, found once a line: each of its pieces starts before it, as
|
|
442
|
-
// `NOT_SPACE` never stops at a line end. Searched again from each piece, it took seconds.
|
|
443
|
-
let lineEnd = -1;
|
|
444
|
-
// Line by line, without splitting the text first: a run can hold millions of empty lines.
|
|
445
|
-
for (let at = 0;;) {
|
|
446
|
-
NOT_SPACE.lastIndex = at;
|
|
447
|
-
const first = NOT_SPACE.exec(hidden);
|
|
448
|
-
if (!first)
|
|
449
|
-
break;
|
|
450
|
-
const start = first.index;
|
|
451
|
-
if (start >= lineEnd) {
|
|
452
|
-
HIDDEN_LINE_END.lastIndex = start;
|
|
453
|
-
lineEnd = HIDDEN_LINE_END.exec(hidden)?.index ?? hidden.length;
|
|
454
|
-
}
|
|
455
|
-
let end = lineEnd;
|
|
456
|
-
if (end - start > HIDDEN_PIECE) {
|
|
457
|
-
// Cut after a space near the end of the piece, and never between the two halves of an emoji.
|
|
458
|
-
const window = sliceWhole(hidden.slice(start, lineEnd), HIDDEN_PIECE);
|
|
459
|
-
const space = window.lastIndexOf(" ");
|
|
460
|
-
end = start + (space > HIDDEN_PIECE * 0.8 ? space + 1 : window.length);
|
|
461
|
-
}
|
|
462
|
-
const line = `${HIDDEN_TEXT} ${hidden.slice(start, end)}`;
|
|
463
|
-
length += 1 + line.length;
|
|
464
|
-
if (length > room)
|
|
465
|
-
throw this.tooMuchText();
|
|
466
|
-
lines.push(line);
|
|
467
|
-
marked++;
|
|
468
|
-
at = end;
|
|
469
|
-
}
|
|
470
|
-
return marked === 0 ? shown : lines.join("\n");
|
|
471
|
-
}
|
|
472
|
-
/**
|
|
473
|
-
* Acts on a tag that has been read. `empty` is a tag that closes itself, as `<w:br/>`.
|
|
474
|
-
* `found`: whether the tag is `attributesTag`, and its attribute has one of the values wanted.
|
|
475
|
-
*/
|
|
476
|
-
read(name, empty, found) {
|
|
477
|
-
if (name === "mc:Fallback") {
|
|
478
|
-
if (!empty)
|
|
479
|
-
this.inFallback++;
|
|
480
|
-
return;
|
|
481
|
-
}
|
|
482
|
-
if (name === "/mc:Fallback") {
|
|
483
|
-
if (this.inFallback > 0)
|
|
484
|
-
this.inFallback--;
|
|
485
|
-
return;
|
|
486
|
-
}
|
|
487
|
-
if (this.inFallback > 0)
|
|
488
|
-
return;
|
|
489
|
-
if (name === this.paragraphTag) {
|
|
490
|
-
if (!empty) {
|
|
491
|
-
if (this.open.length >= MAX_PARAGRAPH_DEPTH) {
|
|
492
|
-
throw new Error(`This ${this.limits.kind} nests paragraphs more than ${MAX_PARAGRAPH_DEPTH} deep, which no document does. It may be built to exhaust the server, so it is not read.`);
|
|
493
|
-
}
|
|
494
|
-
this.open.push({ slot: this.paragraphs.length, pieces: [], hidden: undefined, length: 0, runs: 0, hiddenFrom: 0, runProperties: 0 });
|
|
495
|
-
this.paragraphs.push(null);
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
else if (name === this.paragraphEnd) {
|
|
499
|
-
this.close();
|
|
500
|
-
this.inText = false;
|
|
501
|
-
this.inProperties = 0;
|
|
502
|
-
}
|
|
503
|
-
else if (name === this.textTag) {
|
|
504
|
-
this.inText = !empty;
|
|
505
|
-
}
|
|
506
|
-
else if (name === this.textEnd) {
|
|
507
|
-
this.inText = false;
|
|
508
|
-
}
|
|
509
|
-
else if (name === this.propertiesTag) {
|
|
510
|
-
if (!empty)
|
|
511
|
-
this.inProperties++;
|
|
512
|
-
}
|
|
513
|
-
else if (name === this.propertiesEnd) {
|
|
514
|
-
if (this.inProperties > 0)
|
|
515
|
-
this.inProperties--;
|
|
516
|
-
}
|
|
517
|
-
else if (this.inProperties === 0) {
|
|
518
|
-
if (name === this.tabTag)
|
|
519
|
-
this.add("\t");
|
|
520
|
-
else if (this.breakTags.has(name))
|
|
521
|
-
this.add("\n");
|
|
522
|
-
else if (this.word)
|
|
523
|
-
this.readRun(name, empty, found);
|
|
524
|
-
else if (name === "p:sld" && found)
|
|
525
|
-
this.hiddenSlide = true;
|
|
526
|
-
}
|
|
527
|
-
}
|
|
528
|
-
/**
|
|
529
|
-
* Follows the runs of a Word paragraph, to tell the text of a hidden run: `<w:vanish/>` in the
|
|
530
|
-
* run's own properties, not in those of a change it records (`w:rPrChange`), one level deeper.
|
|
531
|
-
* A run inside a hidden run (the text of a ruby) is hidden too, and the run around it stays
|
|
532
|
-
* hidden after it. `off`: the `w:vanish` turns hiding off.
|
|
533
|
-
*/
|
|
534
|
-
readRun(name, empty, off) {
|
|
535
|
-
const paragraph = this.open.at(-1);
|
|
536
|
-
if (!paragraph)
|
|
537
|
-
return;
|
|
538
|
-
if (name === "w:r") {
|
|
539
|
-
if (empty)
|
|
540
|
-
return;
|
|
541
|
-
paragraph.runs++;
|
|
542
|
-
paragraph.runProperties = 0;
|
|
543
|
-
}
|
|
544
|
-
else if (name === "/w:r") {
|
|
545
|
-
if (paragraph.runs > 0) {
|
|
546
|
-
if (paragraph.hiddenFrom === paragraph.runs)
|
|
547
|
-
paragraph.hiddenFrom = 0;
|
|
548
|
-
paragraph.runs--;
|
|
549
|
-
}
|
|
550
|
-
paragraph.runProperties = 0;
|
|
551
|
-
}
|
|
552
|
-
else if (name === "w:rPr") {
|
|
553
|
-
if (!empty && paragraph.runs > 0)
|
|
554
|
-
paragraph.runProperties++;
|
|
555
|
-
}
|
|
556
|
-
else if (name === "/w:rPr") {
|
|
557
|
-
if (paragraph.runProperties > 0)
|
|
558
|
-
paragraph.runProperties--;
|
|
559
|
-
}
|
|
560
|
-
else if (name === "w:vanish" && paragraph.runProperties === 1) {
|
|
561
|
-
if (!off) {
|
|
562
|
-
if (paragraph.hiddenFrom === 0)
|
|
563
|
-
paragraph.hiddenFrom = paragraph.runs;
|
|
564
|
-
}
|
|
565
|
-
else if (paragraph.hiddenFrom === paragraph.runs) {
|
|
566
|
-
paragraph.hiddenFrom = 0;
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
35
|
/**
|
|
572
|
-
*
|
|
573
|
-
*
|
|
36
|
+
* Picks a format from the file name, then the MIME type. Unknown text-like files are "text". Both
|
|
37
|
+
* come from the upload: only the tables' own keys count, not "constructor" or "__proto__", which
|
|
38
|
+
* every object has.
|
|
574
39
|
*/
|
|
575
|
-
export function
|
|
576
|
-
const
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
/** The most XML read from one DOCX or PPTX, whatever its size: a document of thousands of pages. */
|
|
582
|
-
const MAX_OFFICE_XML = 128 * 1024 * 1024;
|
|
583
|
-
/**
|
|
584
|
-
* The parts read from an Office file unpack to less than its size: pictures, fonts and styles stay
|
|
585
|
-
* packed. A generated report that repeats one paragraph 50,000 times unpacks to 90 times its size.
|
|
586
|
-
* A file that unpacks to more than this many times its size, past the first 16 MB, is taken for a
|
|
587
|
-
* zip bomb, as Apache POI does.
|
|
588
|
-
*/
|
|
589
|
-
const MAX_OFFICE_EXPANSION = 100;
|
|
590
|
-
const OFFICE_ALLOWANCE = 16 * 1024 * 1024;
|
|
591
|
-
const megabytes = (size) => `${Math.round(size / 1024 / 1024)} MB`;
|
|
592
|
-
/**
|
|
593
|
-
* Reads the paragraphs of the parts of one DOCX or PPTX, each a piece at a time as it is unpacked,
|
|
594
|
-
* counting what is unpacked: a file that grows far past its size is refused as it grows, before
|
|
595
|
-
* that much is in memory. JSZip can unpack megabytes of XML in one turn of the event loop, so the
|
|
596
|
-
* stream is paused every few milliseconds of reading, and other requests get a turn.
|
|
597
|
-
*/
|
|
598
|
-
function officeReader(archive, kind, size, input) {
|
|
599
|
-
const limit = Math.min(MAX_OFFICE_XML, Math.max(OFFICE_ALLOWANCE, size * MAX_OFFICE_EXPANSION));
|
|
600
|
-
const refusal = limit === MAX_OFFICE_XML
|
|
601
|
-
? `This ${kind} unpacks to more than ${megabytes(limit)} of XML, more than is read from one file. Save it as text or PDF, and attach that.`
|
|
602
|
-
: `This ${kind} unpacks to more than ${megabytes(limit)}, over ${MAX_OFFICE_EXPANSION} times its size. A file that grows that much is not read: it may be a zip bomb. Save it as text or PDF, and attach that.`;
|
|
603
|
-
const maxTextBytes = input?.maxTextBytes ?? Number.POSITIVE_INFINITY;
|
|
604
|
-
// A character is at least one byte: a text with more characters than the limit is past it.
|
|
605
|
-
const limits = {
|
|
606
|
-
kind,
|
|
607
|
-
maxCharacters: Math.min(MAX_OFFICE_CHARACTERS, maxTextBytes),
|
|
608
|
-
byTextLimit: maxTextBytes < MAX_OFFICE_CHARACTERS,
|
|
609
|
-
};
|
|
610
|
-
// One count for the whole file, across its parts.
|
|
611
|
-
const count = { characters: 0, paragraphs: 0 };
|
|
612
|
-
const slicer = new TimeSlicer(input?.signal);
|
|
613
|
-
let unpacked = 0;
|
|
614
|
-
return (name, prefix) => new Promise((resolve, reject) => {
|
|
615
|
-
const file = archive.file(name);
|
|
616
|
-
if (!file) {
|
|
617
|
-
resolve({ paragraphs: [], hiddenSlide: false });
|
|
618
|
-
return;
|
|
619
|
-
}
|
|
620
|
-
const text = new OfficeText(prefix, limits, count);
|
|
621
|
-
let stopped = false;
|
|
622
|
-
let pausing = false;
|
|
623
|
-
let ended = false;
|
|
624
|
-
const stream = file.internalStream("string");
|
|
625
|
-
const stop = (error) => {
|
|
626
|
-
if (stopped)
|
|
627
|
-
return;
|
|
628
|
-
stopped = true;
|
|
629
|
-
stream.pause();
|
|
630
|
-
reject(error);
|
|
631
|
-
};
|
|
632
|
-
const finish = () => {
|
|
633
|
-
try {
|
|
634
|
-
resolve({ paragraphs: text.texts(), hiddenSlide: text.hiddenSlide });
|
|
635
|
-
}
|
|
636
|
-
catch (error) {
|
|
637
|
-
stop(error);
|
|
638
|
-
}
|
|
639
|
-
};
|
|
640
|
-
stream
|
|
641
|
-
.on("data", (chunk) => {
|
|
642
|
-
if (stopped)
|
|
643
|
-
return;
|
|
644
|
-
if (input?.signal?.aborted) {
|
|
645
|
-
stop(input.signal.reason);
|
|
646
|
-
return;
|
|
647
|
-
}
|
|
648
|
-
unpacked += chunk.length;
|
|
649
|
-
if (unpacked > limit) {
|
|
650
|
-
stop(new Error(refusal));
|
|
651
|
-
return;
|
|
652
|
-
}
|
|
653
|
-
try {
|
|
654
|
-
text.write(chunk);
|
|
655
|
-
}
|
|
656
|
-
catch (error) {
|
|
657
|
-
stop(error);
|
|
658
|
-
return;
|
|
659
|
-
}
|
|
660
|
-
if (!pausing && slicer.due) {
|
|
661
|
-
pausing = true;
|
|
662
|
-
stream.pause();
|
|
663
|
-
slicer.pauseNow().then(() => {
|
|
664
|
-
pausing = false;
|
|
665
|
-
if (stopped)
|
|
666
|
-
return;
|
|
667
|
-
if (ended)
|
|
668
|
-
finish();
|
|
669
|
-
else
|
|
670
|
-
stream.resume();
|
|
671
|
-
}, stop);
|
|
672
|
-
}
|
|
673
|
-
})
|
|
674
|
-
.on("error", stop)
|
|
675
|
-
.on("end", () => {
|
|
676
|
-
ended = true;
|
|
677
|
-
if (!stopped && !pausing)
|
|
678
|
-
finish();
|
|
679
|
-
})
|
|
680
|
-
.resume();
|
|
681
|
-
});
|
|
682
|
-
}
|
|
683
|
-
/**
|
|
684
|
-
* The parts an Office file may have, at most. A deck of 2,000 slides with notes and pictures has
|
|
685
|
-
* about 12,000. JSZip reads the header of every part into memory before any part is unpacked:
|
|
686
|
-
* about 2 KB each, and 300,000 empty parts took over 500 MB.
|
|
687
|
-
*/
|
|
688
|
-
const MAX_ZIP_ENTRIES = 20_000;
|
|
689
|
-
/**
|
|
690
|
-
* The extra fields the parts of an Office file may have, together. Office writes none, other ZIP
|
|
691
|
-
* programs one to three for each part. JSZip keeps about 250 bytes for each field of 4 bytes: a
|
|
692
|
-
* file of 4 MB made only of them took 250 MB.
|
|
693
|
-
*/
|
|
694
|
-
const MAX_ZIP_EXTRA_FIELDS = 4 * MAX_ZIP_ENTRIES;
|
|
695
|
-
/**
|
|
696
|
-
* The bytes JSZip may turn into text, or go through one by one, from the directory of an Office
|
|
697
|
-
* file: names, comments, and the data of three kinds of extra field (see ZipDirectory). The Office
|
|
698
|
-
* files we tried had at most 68 KB. A name can be decoded from the same bytes for many parts, and
|
|
699
|
-
* the data of a field can run over the records after it, so the size of the file does not bound
|
|
700
|
-
* them: 2,000 parts of a 0.17 MB file took JSZip over 256 MB. A file just under this limit and the
|
|
701
|
-
* two above took JSZip under 0.5 s and 140 MB.
|
|
702
|
-
*/
|
|
703
|
-
const MAX_ZIP_TEXT_BYTES = 8 * 1024 * 1024;
|
|
704
|
-
async function loadZip(bytes, kind) {
|
|
705
|
-
let JSZip;
|
|
706
|
-
try {
|
|
707
|
-
JSZip = (await import("jszip")).default;
|
|
708
|
-
}
|
|
709
|
-
catch {
|
|
710
|
-
throw new Error("Reading DOCX and PPTX files needs the optional dependency \"jszip\".");
|
|
711
|
-
}
|
|
712
|
-
// The directory is read first, as JSZip will read it: the count of parts it gives may say
|
|
713
|
-
// anything.
|
|
714
|
-
const directory = readZipDirectory(bytes, { parts: MAX_ZIP_ENTRIES, extraFields: MAX_ZIP_EXTRA_FIELDS, textBytes: MAX_ZIP_TEXT_BYTES });
|
|
715
|
-
if (directory?.endless) {
|
|
716
|
-
throw new Error(`This ${kind} ends with a ZIP64 record that cannot be read, and reading it could hold the server without end. It may be built to exhaust the server, so it is not read.`);
|
|
717
|
-
}
|
|
718
|
-
if (directory && directory.parts > MAX_ZIP_ENTRIES) {
|
|
719
|
-
throw new Error(`This ${kind} has more than ${MAX_ZIP_ENTRIES.toLocaleString("en-US")} parts, more than an Office document has. It may be built to exhaust the server, so it is not read.`);
|
|
720
|
-
}
|
|
721
|
-
// A mass of extra fields, or of names, comments and field data: no Office program writes either.
|
|
722
|
-
if (directory && (directory.extraFields > MAX_ZIP_EXTRA_FIELDS || directory.textBytes > MAX_ZIP_TEXT_BYTES)) {
|
|
723
|
-
throw new Error(`This ${kind} lists its parts in a way that no Office program does: reading the list would take far more memory or time than an Office document needs. It may be built to exhaust the server, so it is not read.`);
|
|
724
|
-
}
|
|
725
|
-
return JSZip.loadAsync(bytes);
|
|
40
|
+
export function detectFormat(name, mimeType) {
|
|
41
|
+
const extension = name.toLowerCase().split(".").at(-1) ?? "";
|
|
42
|
+
const mime = mimeType.toLowerCase();
|
|
43
|
+
return (Object.hasOwn(EXTENSION_FORMATS, extension) ? EXTENSION_FORMATS[extension] : undefined)
|
|
44
|
+
?? (Object.hasOwn(MIME_FORMATS, mime) ? MIME_FORMATS[mime] : undefined)
|
|
45
|
+
?? "text";
|
|
726
46
|
}
|
|
727
|
-
const docx = async (bytes, input) => {
|
|
728
|
-
input?.signal?.throwIfAborted();
|
|
729
|
-
const archive = await loadZip(bytes, "DOCX");
|
|
730
|
-
input?.signal?.throwIfAborted();
|
|
731
|
-
const names = Object.keys(archive.files)
|
|
732
|
-
.filter((name) => /^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/i.test(name))
|
|
733
|
-
.sort((left, right) => left === "word/document.xml" ? -1 : right === "word/document.xml" ? 1 : left.localeCompare(right));
|
|
734
|
-
if (!names.includes("word/document.xml"))
|
|
735
|
-
throw new Error("This DOCX does not contain word/document.xml.");
|
|
736
|
-
const read = officeReader(archive, "DOCX", bytes.byteLength, input);
|
|
737
|
-
const sections = [];
|
|
738
|
-
for (const [index, name] of names.entries()) {
|
|
739
|
-
sections.push((await read(name, "w")).paragraphs.join("\n"));
|
|
740
|
-
input?.onProgress?.({ done: index + 1, total: names.length, unit: "parts" });
|
|
741
|
-
}
|
|
742
|
-
return { text: sections.filter(Boolean).join("\n\n") };
|
|
743
|
-
};
|
|
744
|
-
const pptx = async (bytes, input) => {
|
|
745
|
-
input?.signal?.throwIfAborted();
|
|
746
|
-
const archive = await loadZip(bytes, "PPTX");
|
|
747
|
-
input?.signal?.throwIfAborted();
|
|
748
|
-
const slideNumber = (name) => Number(/slide(\d+)\.xml$/i.exec(name)?.[1] ?? Number.MAX_SAFE_INTEGER);
|
|
749
|
-
const names = Object.keys(archive.files)
|
|
750
|
-
.filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))
|
|
751
|
-
.sort((left, right) => slideNumber(left) - slideNumber(right));
|
|
752
|
-
if (names.length === 0)
|
|
753
|
-
throw new Error("This PPTX does not contain any slides.");
|
|
754
|
-
const read = officeReader(archive, "PPTX", bytes.byteLength, input);
|
|
755
|
-
const slides = [];
|
|
756
|
-
for (const [index, name] of names.entries()) {
|
|
757
|
-
const { paragraphs, hiddenSlide } = await read(name, "a");
|
|
758
|
-
const text = paragraphs.join("\n");
|
|
759
|
-
// A hidden slide keeps its text, and says that the slide show skips it.
|
|
760
|
-
slides.push(`## Slide ${slideNumber(name)}${hiddenSlide ? ` ${HIDDEN_SLIDE}` : ""}\n${text || "[No text on this slide]"}`);
|
|
761
|
-
input?.onProgress?.({ done: index + 1, total: names.length, unit: "parts" });
|
|
762
|
-
}
|
|
763
|
-
return { text: slides.join("\n\n"), pages: names.length };
|
|
764
|
-
};
|
|
765
47
|
/**
|
|
766
48
|
* A page tree that lists one page more than once makes the text of that page come back each time:
|
|
767
49
|
* a 3 KB file built that way held 107 MB of text. PDF writers do not do this.
|
|
@@ -790,6 +72,17 @@ const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or
|
|
|
790
72
|
* not the model is later given a way to look at the page.
|
|
791
73
|
*/
|
|
792
74
|
export const PICTURE_ON_PAGE = "[Picture on this page. This text cannot show it.]";
|
|
75
|
+
/** A line of a page's text that reads as one the extractor writes: a page header, or one of the two notes above. */
|
|
76
|
+
const OWN_LINE = /^(?:--- Page \d+ ---|\[Picture on this page\. This text cannot show it\.\]|\[No text on this page\. It may be a scan, a photo, or a chart\.\])$/gm;
|
|
77
|
+
/**
|
|
78
|
+
* A page's text, with each line that reads as a line of the extractor's own moved by a space: a
|
|
79
|
+
* document that quotes "--- Page 3 ---" on page 2 must not start page 3 there, nor tell a model of a
|
|
80
|
+
* picture it does not have. Only the extractor's lines have the exact form, which search and
|
|
81
|
+
* `view_pages` look for.
|
|
82
|
+
*/
|
|
83
|
+
function ownLines(text) {
|
|
84
|
+
return text.includes("--- Page ") || text.includes("[Picture on this page") || text.includes("[No text on this page") ? text.replace(OWN_LINE, (line) => ` ${line}`) : text;
|
|
85
|
+
}
|
|
793
86
|
/**
|
|
794
87
|
* The progress of the pages of one stage of reading a PDF, for `ExtractInput.onProgress`. The page
|
|
795
88
|
* check and the picture marks give up quietly on an error of their own: an error of the listener is
|
|
@@ -856,18 +149,21 @@ export function createPdfExtractor(options = {}) {
|
|
|
856
149
|
const pictures = options.pictures ?? true;
|
|
857
150
|
const checkPages = options.checkPages ?? true;
|
|
858
151
|
return async (bytes, input) => {
|
|
859
|
-
|
|
860
|
-
try {
|
|
861
|
-
unpdf = await import("unpdf");
|
|
862
|
-
}
|
|
863
|
-
catch {
|
|
864
|
-
throw new Error("Reading PDF files needs the optional dependency \"unpdf\".");
|
|
865
|
-
}
|
|
152
|
+
const unpdf = await importPeer("unpdf", () => import("unpdf"), "Reading PDF files needs the optional dependency \"unpdf\".");
|
|
866
153
|
await checkUnpdf(unpdf);
|
|
867
154
|
const signal = input?.signal;
|
|
868
155
|
signal?.throwIfAborted();
|
|
869
156
|
// pdf.js may detach the buffer it reads, so give it a copy.
|
|
870
|
-
|
|
157
|
+
let document;
|
|
158
|
+
try {
|
|
159
|
+
document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
if (error?.name === "PasswordException") {
|
|
163
|
+
throw new Error("This PDF is protected by a password, so it cannot be read. Open it, print it to a new PDF without the password, and attach that.", { cause: error });
|
|
164
|
+
}
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
871
167
|
const maxPages = input?.maxPages;
|
|
872
168
|
if (maxPages !== undefined && document.numPages > maxPages) {
|
|
873
169
|
throw new Error(`This PDF has ${document.numPages.toLocaleString("en-US")} pages, more than the ${maxPages.toLocaleString("en-US")} read from one file. Split it, and attach the part you need.`);
|
|
@@ -961,7 +257,7 @@ export function createPdfExtractor(options = {}) {
|
|
|
961
257
|
const pictured = pictures ? await findPicturePages(parsed, geometry, signal, looked.report) : undefined;
|
|
962
258
|
signal?.throwIfAborted();
|
|
963
259
|
looked.rethrow();
|
|
964
|
-
const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text
|
|
260
|
+
const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text ? ownLines(text) : PAGE_WITHOUT_TEXT}`);
|
|
965
261
|
return { text: pages.join("\n\n"), pages: document.numPages };
|
|
966
262
|
};
|
|
967
263
|
}
|
|
@@ -974,6 +270,8 @@ export const defaultExtractors = {
|
|
|
974
270
|
pdf: createPdfExtractor(),
|
|
975
271
|
docx,
|
|
976
272
|
pptx,
|
|
273
|
+
xlsx,
|
|
274
|
+
html,
|
|
977
275
|
};
|
|
978
276
|
export async function extractText(bytes, input, extractors = {}) {
|
|
979
277
|
const extractor = extractors[input.format] ?? defaultExtractors[input.format];
|