llm-large-files 0.8.1 → 0.9.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 +631 -0
- package/README.md +9 -10
- package/dist/access.d.ts +86 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +131 -0
- package/dist/access.js.map +1 -0
- package/dist/ask.d.ts +45 -1
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +181 -20
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +57 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +217 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +72 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +102 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +35 -9
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +14 -3
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +46 -35
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +19 -3
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +84 -12
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +18 -6
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +2 -0
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +70 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +868 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +176 -34
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +332 -512
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -2
- package/dist/limiter.js +2 -2
- package/dist/map-reduce.js +3 -3
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +43 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +63 -3
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +234 -7
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +482 -121
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +18 -3
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +102 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +365 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +4 -3
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +7 -6
- package/dist/node/sse.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/ranged.d.ts +22 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +50 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +120 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +582 -139
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +25 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +135 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +116 -13
- package/dist/types.d.ts.map +1 -1
- package/docs/README.md +17 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +12 -8
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +16 -7
- package/docs/guides/deployment.md +309 -87
- package/docs/guides/errors-and-reliability.md +161 -23
- package/docs/guides/own-adapter-and-loop.md +27 -10
- package/docs/guides/pdfs.md +123 -29
- package/docs/guides/storage.md +634 -143
- package/docs/guides/testing.md +78 -129
- package/docs/guides/vertex-and-gemini.md +10 -7
- package/docs/guides/web-app.md +322 -77
- package/docs/how-it-works.md +35 -8
- package/docs/measurements.md +63 -8
- package/docs/publishing.md +112 -36
- package/docs/reference/ask.md +154 -13
- package/docs/reference/errors-and-retries.md +166 -14
- package/docs/reference/events.md +53 -20
- package/docs/reference/gemini.md +70 -21
- package/docs/reference/library.md +709 -165
- package/docs/reference/node.md +633 -104
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +15 -5
- package/docs/security.md +316 -70
- package/docs/troubleshooting.md +165 -58
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +12 -3
- package/src/access.ts +144 -0
- package/src/ask.ts +230 -19
- package/src/cache.ts +20 -5
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +255 -0
- package/src/errors.ts +129 -15
- package/src/events.ts +86 -21
- package/src/evidence.ts +14 -3
- package/src/extract.ts +50 -33
- package/src/gemini/adapter.ts +97 -11
- package/src/gemini/chat.ts +20 -6
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +9 -6
- package/src/ingest.ts +927 -0
- package/src/library.ts +482 -523
- package/src/limiter.ts +2 -2
- package/src/map-reduce.ts +3 -3
- package/src/model.ts +69 -5
- package/src/node/handlers.ts +691 -117
- package/src/node/index.ts +13 -2
- package/src/node/ingest-child.ts +23 -5
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +365 -0
- package/src/node/sse.ts +7 -6
- package/src/pdf-layout.ts +69 -11
- package/src/ranged.ts +42 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/source.ts +178 -0
- package/src/stores.ts +635 -140
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +150 -14
- package/src/types.ts +106 -13
package/dist/library.js
CHANGED
|
@@ -1,82 +1,25 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
|
|
1
|
+
import { callerOf, checkMetaVersion, documentContext, mayUse, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext } from "./access.js";
|
|
3
2
|
import { givenBudget, resolveBudget } from "./budget.js";
|
|
4
3
|
import { DocumentCache, documentVersion } from "./cache.js";
|
|
5
|
-
import {
|
|
6
|
-
import { EventEmitter, eventErrorOf, newRunId } from "./events.js";
|
|
7
|
-
import { detectFormat, extractText } from "./extract.js";
|
|
4
|
+
import { ingestDocument, LONGEST_TIMER_MS } from "./ingest.js";
|
|
8
5
|
import { Limiter } from "./limiter.js";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { measureQuality } from "./quality.js";
|
|
12
|
-
import { openRangedDocument, pieceKey } from "./ranged.js";
|
|
6
|
+
import { canBeReadWhole, CARD_LINES, documentToolsInstruction, planDocuments, renderCard, renderInline, TABLE_FORMATS } from "./plan.js";
|
|
7
|
+
import { DocumentGoneError, openRangedDocument, pieceKey, RangedDocument } from "./ranged.js";
|
|
13
8
|
import { numberLines, SearchableDocument } from "./search.js";
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
9
|
+
import { TimeSlicer } from "./pause.js";
|
|
10
|
+
import { checkScope } from "./scope.js";
|
|
11
|
+
import { isSha256, sha256InSlices } from "./source.js";
|
|
12
|
+
import { APP_DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
13
|
+
import { wellFormed } from "./text.js";
|
|
17
14
|
import { createDocumentTools } from "./tools.js";
|
|
18
15
|
export { DEFAULT_BUDGET } from "./budget.js";
|
|
19
|
-
export
|
|
20
|
-
return typeof value === "string" && DOCUMENT_ID_PATTERN.test(value);
|
|
21
|
-
}
|
|
22
|
-
/** The fields of a document that are safe to return to a browser. */
|
|
23
|
-
export function toDocumentSummary(meta) {
|
|
24
|
-
return {
|
|
25
|
-
id: meta.id,
|
|
26
|
-
name: meta.name,
|
|
27
|
-
mimeType: meta.mimeType,
|
|
28
|
-
format: meta.format,
|
|
29
|
-
bytes: meta.bytes,
|
|
30
|
-
lines: meta.lines,
|
|
31
|
-
estimatedTokens: meta.estimatedTokens,
|
|
32
|
-
...(meta.pages ? { pages: meta.pages } : {}),
|
|
33
|
-
...(meta.encoding ? { encoding: meta.encoding } : {}),
|
|
34
|
-
...(meta.replacedCharacters ? { replacedCharacters: meta.replacedCharacters } : {}),
|
|
35
|
-
expiresAt: meta.expiresAt,
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
/** An encoding's name as TextDecoder gives it ("windows-1255"): an extractor of your own may name another. */
|
|
39
|
-
const ENCODING_NAME = /^[a-z0-9][a-z0-9._:-]{0,39}$/i;
|
|
16
|
+
export { checkOwner, cleanFileName, cleanMimeType, NEVER_EXPIRES, toDocumentSummary } from "./ingest.js";
|
|
40
17
|
/**
|
|
41
|
-
* Whether the
|
|
42
|
-
*
|
|
18
|
+
* Whether `value` has the shape of a document ID: one the library makes ("doc_" and 32 hex digits),
|
|
19
|
+
* or one an application may give (`APP_DOCUMENT_ID_PATTERN`, since 0.9.0), which the library's fit too.
|
|
43
20
|
*/
|
|
44
|
-
function
|
|
45
|
-
|
|
46
|
-
return false;
|
|
47
|
-
let known;
|
|
48
|
-
try {
|
|
49
|
-
known = new TextDecoder(name).encoding;
|
|
50
|
-
}
|
|
51
|
-
catch {
|
|
52
|
-
// A name TextDecoder does not know: the extractor read the file itself.
|
|
53
|
-
return true;
|
|
54
|
-
}
|
|
55
|
-
return known !== "utf-8" && known !== "utf-16le" && known !== "utf-16be";
|
|
56
|
-
}
|
|
57
|
-
/** How the text of a file was read, as its extractor said, in the fields of `DocumentMeta`. */
|
|
58
|
-
function readingOf(extracted) {
|
|
59
|
-
const { encoding, replacedCharacters } = extracted;
|
|
60
|
-
return {
|
|
61
|
-
...(olderEncoding(encoding) ? { encoding } : {}),
|
|
62
|
-
...(typeof replacedCharacters === "number" && Number.isSafeInteger(replacedCharacters) && replacedCharacters > 0 ? { replacedCharacters } : {}),
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* A file name as one printable line: the last path segment. Control characters, line and paragraph
|
|
67
|
-
* separators, and text-direction controls (the marks of right-to-left text included) become a space.
|
|
68
|
-
* Names are shown to the model and in UIs, so a name must not be able to start a new line of the
|
|
69
|
-
* prompt, or disguise its extension. Most characters that show nothing are removed (tag characters,
|
|
70
|
-
* zero-width spaces); the variation selectors and joiners that scripts and emoji need are kept, and
|
|
71
|
-
* can still carry data a person does not see.
|
|
72
|
-
*/
|
|
73
|
-
export function cleanFileName(raw) {
|
|
74
|
-
const base = raw.split(/[\\/]/).at(-1) ?? "";
|
|
75
|
-
// Control characters, line and paragraph separators, and text-direction controls become a space.
|
|
76
|
-
const spaced = base.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ");
|
|
77
|
-
const name = removeInvisible(spaced).replace(/\s+/g, " ").trim();
|
|
78
|
-
// At most 255 characters, never half of an emoji. A flag cut short loses the tags left of it.
|
|
79
|
-
return (name.length > 255 ? removeInvisible(sliceWhole(name, 255)) : name) || "file";
|
|
21
|
+
export function isDocumentId(value) {
|
|
22
|
+
return typeof value === "string" && APP_DOCUMENT_ID_PATTERN.test(value);
|
|
80
23
|
}
|
|
81
24
|
/**
|
|
82
25
|
* Metadata with a whole file name. 0.5.0 and earlier cut a long name at 255 UTF-16 units, at times
|
|
@@ -87,173 +30,50 @@ function wholeName(meta) {
|
|
|
87
30
|
const name = wellFormed(meta.name);
|
|
88
31
|
return name === meta.name ? meta : { ...meta, name };
|
|
89
32
|
}
|
|
90
|
-
/**
|
|
91
|
-
* Refuses an owner that every caller without a user would share: an empty string (what
|
|
92
|
-
* `user?.id ?? ""` gives), one of spaces only, or null. Undefined is no owner. A number is let
|
|
93
|
-
* through, as before, for JavaScript code that passes numeric user IDs.
|
|
94
|
-
*/
|
|
95
|
-
export function checkOwner(owner) {
|
|
96
|
-
if (owner === undefined || (typeof owner === "string" && owner.trim() !== "") || (typeof owner === "number" && Number.isFinite(owner)))
|
|
97
|
-
return;
|
|
98
|
-
throw new TypeError("owner must be a string that is not empty or only spaces, such as the signed-in user's ID. To let anyone with the document's ID use it, leave owner out.");
|
|
99
|
-
}
|
|
100
33
|
/**
|
|
101
34
|
* A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
|
|
102
35
|
* could not be read is not a document that is gone, and its own error names paths or hosts.
|
|
103
36
|
*/
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
return await read();
|
|
107
|
-
}
|
|
108
|
-
catch (error) {
|
|
109
|
-
throw error instanceof DocumentStoreError ? error : new DocumentStoreError(error);
|
|
110
|
-
}
|
|
37
|
+
function reading(read) {
|
|
38
|
+
return storeCall("read", read);
|
|
111
39
|
}
|
|
40
|
+
/** The key a caller's copy of a document is kept under in memory: the key of its scope, then the ID. */
|
|
41
|
+
const documentKey = (caller, id) => `${caller.key}\u0000${id}`;
|
|
42
|
+
/** A caller with no owner and no scope. */
|
|
43
|
+
const NO_CALLER = Object.freeze({ context: storeContext(undefined, undefined), key: "" });
|
|
44
|
+
/**
|
|
45
|
+
* What `view_pages` answers for a file the application keeps (`IngestInput.original`) that is no
|
|
46
|
+
* longer the one that was ingested. New in 0.9.0.
|
|
47
|
+
*/
|
|
48
|
+
const changedOriginal = (file) => `${file} changed on the server since it was read. Attach it again to look at its pages.`;
|
|
112
49
|
/**
|
|
113
|
-
*
|
|
114
|
-
*
|
|
50
|
+
* Where the application keeps the uploaded file of a document (`DocumentMeta.original`), when its
|
|
51
|
+
* metadata says so in the shape the library writes. Undefined for one kept in the store, and for
|
|
52
|
+
* one written by hand in another shape, which reads as missing.
|
|
115
53
|
*/
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
54
|
+
function refOf(meta) {
|
|
55
|
+
const original = meta.original;
|
|
56
|
+
if (typeof original !== "object" || original === null)
|
|
57
|
+
return undefined;
|
|
58
|
+
const { ref, bytes, sha256 } = original;
|
|
59
|
+
return typeof ref === "string" && ref.length > 0 && typeof bytes === "number" && Number.isSafeInteger(bytes) && bytes >= 0 && isSha256(sha256)
|
|
60
|
+
? { ref, bytes, sha256 }
|
|
61
|
+
: undefined;
|
|
119
62
|
}
|
|
120
63
|
/** Default for `cacheBytes`. */
|
|
121
64
|
export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
|
|
122
|
-
/** The refusal of a file whose text is larger than `maxTextBytes`. */
|
|
123
|
-
const tooMuchText = (name, maxTextBytes) => new Error(`${name} holds more than ${formatBytes(maxTextBytes)} of text, more than is kept from one file. Split it, and attach the part you need.`);
|
|
124
65
|
/** Default for `maxPdfPages`. */
|
|
125
66
|
export const DEFAULT_MAX_PDF_PAGES = 5_000;
|
|
126
67
|
/** Default for `maxTextBytes`, when `maxUploadBytes` is not larger: 100 MB. */
|
|
127
68
|
export const DEFAULT_MAX_TEXT_BYTES = 100 * 1024 * 1024;
|
|
128
69
|
/** Default for `ingestTimeoutMs`: 2 minutes. */
|
|
129
70
|
export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
|
|
130
|
-
/** The longest a Node.js timer waits: a longer one fires at once. A limit past it is no limit. */
|
|
131
|
-
const LONGEST_TIMER_MS = 2 ** 31 - 1;
|
|
132
|
-
/** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
|
|
133
|
-
function formatDuration(ms) {
|
|
134
|
-
if (ms < 1_000)
|
|
135
|
-
return `${Math.max(1, Math.round(ms))} ms`;
|
|
136
|
-
if (ms < 120_000)
|
|
137
|
-
return `${Number((ms / 1_000).toFixed(1))} s`;
|
|
138
|
-
return `${Number((ms / 60_000).toFixed(1))} min`;
|
|
139
|
-
}
|
|
140
|
-
/**
|
|
141
|
-
* The signal one ingest runs under: aborted when the caller's is, or when `timeoutMs` has passed
|
|
142
|
-
* (with an error that says the file took too long). `dispose` stops the timer.
|
|
143
|
-
*/
|
|
144
|
-
function ingestSignal(name, caller, timeoutMs) {
|
|
145
|
-
const controller = new AbortController();
|
|
146
|
-
const onAbort = () => controller.abort(caller.reason);
|
|
147
|
-
if (caller?.aborted)
|
|
148
|
-
controller.abort(caller.reason);
|
|
149
|
-
else
|
|
150
|
-
caller?.addEventListener("abort", onAbort, { once: true });
|
|
151
|
-
const timer = timeoutMs > 0 && timeoutMs <= LONGEST_TIMER_MS
|
|
152
|
-
? setTimeout(() => controller.abort(new Error(`${name} took too long to read (more than ${formatDuration(timeoutMs)}). Split it, or save it as plain text, and attach that.`)), timeoutMs)
|
|
153
|
-
: undefined;
|
|
154
|
-
return {
|
|
155
|
-
signal: controller.signal,
|
|
156
|
-
dispose() {
|
|
157
|
-
clearTimeout(timer);
|
|
158
|
-
caller?.removeEventListener("abort", onAbort);
|
|
159
|
-
},
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* `work`, or the signal's reason as soon as it is aborted: an extractor of your own that does not
|
|
164
|
-
* look at the signal is no longer waited for (though the work it does cannot be stopped).
|
|
165
|
-
*/
|
|
166
|
-
function untilAborted(work, signal) {
|
|
167
|
-
if (signal.aborted)
|
|
168
|
-
return Promise.reject(signal.reason);
|
|
169
|
-
return new Promise((resolve, reject) => {
|
|
170
|
-
const onAbort = () => reject(signal.reason);
|
|
171
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
172
|
-
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
/** The message of `ingest.error` when the store failed to write the document. */
|
|
176
|
-
const STORE_WRITE_FAILED = "The document could not be stored. Try again later.";
|
|
177
|
-
/** The least time between two `ingest.progress` events of one stage, in milliseconds: a slice of `TimeSlicer`. */
|
|
178
|
-
const PROGRESS_MS = 12;
|
|
179
|
-
const EXTRACT_STAGES = new Set(["extract", "check", "pictures", "decode"]);
|
|
180
|
-
const EXTRACT_UNITS = new Set(["pages", "parts", "bytes"]);
|
|
181
|
-
const isCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
182
|
-
/** What `ingest.start` says of an ingest, worked out from whatever it was given: the checks come after it. */
|
|
183
|
-
function startOf(input) {
|
|
184
|
-
try {
|
|
185
|
-
const name = typeof input?.name === "string" ? cleanFileName(input.name) : "";
|
|
186
|
-
const mimeType = (typeof input?.mimeType === "string" ? input.mimeType.trim() : "") || "application/octet-stream";
|
|
187
|
-
const bytes = input?.bytes?.byteLength;
|
|
188
|
-
return { name, format: detectFormat(name, mimeType), bytes: isCount(bytes) ? bytes : 0 };
|
|
189
|
-
}
|
|
190
|
-
catch {
|
|
191
|
-
return { name: "", format: "text", bytes: 0 };
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Sends the `ingest.progress` events of one ingest: at most one every `PROGRESS_MS` for each stage,
|
|
196
|
-
* however the stages take turns, then the last progress of each stage when the stages end (`end`).
|
|
197
|
-
* A progress that completes its stage goes out at once, the first time, so that stages that run one
|
|
198
|
-
* after the other end in that order. Made only when someone listens.
|
|
199
|
-
*/
|
|
200
|
-
class IngestProgress {
|
|
201
|
-
events;
|
|
202
|
-
/** Each stage that reported, in the order it first did: when it last sent, and its last progress. */
|
|
203
|
-
stages = new Map();
|
|
204
|
-
/** Set once a stage after the extractor's began: an extract stage is not reported again. */
|
|
205
|
-
extractOver = false;
|
|
206
|
-
constructor(events) {
|
|
207
|
-
this.events = events;
|
|
208
|
-
}
|
|
209
|
-
report(stage, done, total, unit) {
|
|
210
|
-
if (!EXTRACT_STAGES.has(stage))
|
|
211
|
-
this.extractOver = true;
|
|
212
|
-
const last = { done, total, unit, sent: false };
|
|
213
|
-
let state = this.stages.get(stage);
|
|
214
|
-
if (!state) {
|
|
215
|
-
state = { sentAt: Number.NEGATIVE_INFINITY, completed: false, last };
|
|
216
|
-
this.stages.set(stage, state);
|
|
217
|
-
}
|
|
218
|
-
state.last = last;
|
|
219
|
-
const now = performance.now();
|
|
220
|
-
const completes = !state.completed && total !== undefined && done >= total;
|
|
221
|
-
if (completes)
|
|
222
|
-
state.completed = true;
|
|
223
|
-
if (completes || now - state.sentAt >= PROGRESS_MS) {
|
|
224
|
-
state.sentAt = now;
|
|
225
|
-
this.send(stage, last);
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
/** The progress an extractor reported (`ExtractInput.onProgress`). One of your own may send anything: what does not fit is left out. */
|
|
229
|
-
extracted(progress) {
|
|
230
|
-
if (this.extractOver)
|
|
231
|
-
return;
|
|
232
|
-
const stage = progress?.stage ?? "extract";
|
|
233
|
-
if (!EXTRACT_STAGES.has(stage) || !EXTRACT_UNITS.has(progress?.unit) || !isCount(progress?.done))
|
|
234
|
-
return;
|
|
235
|
-
this.report(stage, progress.done, isCount(progress.total) ? progress.total : undefined, progress.unit);
|
|
236
|
-
}
|
|
237
|
-
/** The stages so far are over: the last progress of each, when it was held back, goes out, in the order they began. */
|
|
238
|
-
end() {
|
|
239
|
-
const held = [...this.stages].filter(([, state]) => !state.last.sent);
|
|
240
|
-
this.stages.clear();
|
|
241
|
-
for (const [stage, state] of held)
|
|
242
|
-
this.send(stage, state.last);
|
|
243
|
-
}
|
|
244
|
-
send(stage, last) {
|
|
245
|
-
last.sent = true;
|
|
246
|
-
this.events.emit({
|
|
247
|
-
type: "ingest.progress",
|
|
248
|
-
stage,
|
|
249
|
-
done: last.done,
|
|
250
|
-
...(last.total !== undefined ? { total: last.total } : {}),
|
|
251
|
-
unit: last.unit,
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
71
|
/** Default for `wholeDocumentBytes`. */
|
|
256
72
|
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
73
|
+
/** Looks at pages that run at once in a library, unless `maxConcurrentPageLooks` says otherwise. */
|
|
74
|
+
const DEFAULT_PAGE_LOOKS = 1;
|
|
75
|
+
/** How long a look at pages waits for its turn, unless `pageLookWaitMs` says otherwise. */
|
|
76
|
+
const DEFAULT_PAGE_LOOK_WAIT_MS = 30_000;
|
|
257
77
|
/**
|
|
258
78
|
* A number option as it was given, or `fallback` when it was left out. NaN, which
|
|
259
79
|
* `Number(process.env.X)` gives for a variable that is not set, and a value that is not a number
|
|
@@ -283,360 +103,330 @@ export function createLargeFiles(options) {
|
|
|
283
103
|
const now = options.now ?? (() => new Date());
|
|
284
104
|
const { store } = options;
|
|
285
105
|
const cacheBytes = Math.max(0, numberOption("cacheBytes", options.cacheBytes, DEFAULT_CACHE_BYTES));
|
|
286
|
-
/**
|
|
106
|
+
/** What every call must name (`requireOwner`, `requireScope`). */
|
|
107
|
+
const rules = Object.freeze({ requireOwner: options.requireOwner === true, requireScope: options.requireScope === true });
|
|
108
|
+
/**
|
|
109
|
+
* Documents ready to search, and decoded pieces of documents read by range, in one memory budget.
|
|
110
|
+
* Each is kept under the key of the caller's scope and the document's ID (`documentKey`): one ID
|
|
111
|
+
* in two scopes is two documents, and the copy of one is never served to the other. Its version
|
|
112
|
+
* (`documentVersion`) holds the document's owner and scope too, so a copy is not served to
|
|
113
|
+
* another owner either, once another document is stored under the same ID.
|
|
114
|
+
*/
|
|
287
115
|
const cache = new DocumentCache(cacheBytes, Math.max(0, Math.trunc(numberOption("cacheSize", options.cacheSize, Number.POSITIVE_INFINITY))));
|
|
288
|
-
/** Forgets everything kept of
|
|
116
|
+
/** Forgets everything kept of the document of one key (`documentKey`): the document, and its pieces. */
|
|
117
|
+
const forgetKey = (key) => {
|
|
118
|
+
cache.delete(key);
|
|
119
|
+
cache.deletePrefix(pieceKey(key, 0).slice(0, -1));
|
|
120
|
+
};
|
|
121
|
+
/** Whether `key` is that of document `id`, or of one of its pieces, in any scope. */
|
|
122
|
+
const keyOfId = (key, id) => {
|
|
123
|
+
const rest = key.slice(key.indexOf("\u0000") + 1);
|
|
124
|
+
return rest === id || rest.startsWith(`${id}#`);
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Forgets everything kept of document `id`, in every scope: it was deleted, or written again.
|
|
128
|
+
* In a store that keeps no scopes apart, the copies of all scopes are of that one document.
|
|
129
|
+
*/
|
|
289
130
|
const forget = (id) => {
|
|
290
|
-
cache.
|
|
291
|
-
|
|
131
|
+
cache.deleteWhere((key) => keyOfId(key, id));
|
|
132
|
+
for (const key of rebuildIndex)
|
|
133
|
+
if (keyOfId(key, id))
|
|
134
|
+
rebuildIndex.delete(key);
|
|
292
135
|
};
|
|
293
136
|
/** Documents being opened, so that calls arriving together open each one once. */
|
|
294
137
|
const opening = new Map();
|
|
295
|
-
/**
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
138
|
+
/**
|
|
139
|
+
* The store, to read the text of a document by range rather than load it whole: each call carries
|
|
140
|
+
* `context`: the caller's scope, and the document's owner when it has one (`documentContext`).
|
|
141
|
+
*/
|
|
142
|
+
const rangeStore = (context) => ({
|
|
143
|
+
readTextRange: (id, start, end) => reading(() => store.readTextRange(id, start, end, context)),
|
|
144
|
+
...(store.getIndex ? { getIndex: (id) => reading(() => store.getIndex(id, context)) } : {}),
|
|
145
|
+
...(store.putIndex ? { putIndex: (id, index) => store.putIndex(id, index, context) } : {}),
|
|
146
|
+
});
|
|
301
147
|
/** The uploaded file of a document, when the store keeps such files. */
|
|
302
|
-
const loadOriginal =
|
|
148
|
+
const loadOriginal = (id, context) => reading(() => store.getOriginal(id, context));
|
|
303
149
|
const wholeDocumentBytes = Math.max(0, numberOption("wholeDocumentBytes", options.wholeDocumentBytes, DEFAULT_WHOLE_DOCUMENT_BYTES));
|
|
304
|
-
/** Documents whose saved index did not match their text: the next opening builds it from the text. */
|
|
150
|
+
/** Documents (by `documentKey`) whose saved index did not match their text: the next opening builds it from the text. */
|
|
305
151
|
const rebuildIndex = new Set();
|
|
306
152
|
const scan = {
|
|
307
153
|
chunkBytes: Math.max(1, Math.trunc(numberOption("scanChunkBytes", options.scanChunkBytes, 1024 * 1024, true))),
|
|
308
154
|
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentScans", options.maxConcurrentScans, 4)))),
|
|
309
|
-
onBroken: (
|
|
310
|
-
rebuildIndex.add(
|
|
311
|
-
|
|
155
|
+
onBroken: (key) => {
|
|
156
|
+
rebuildIndex.add(key);
|
|
157
|
+
forgetKey(key);
|
|
312
158
|
},
|
|
313
159
|
pieces: {
|
|
314
160
|
get: (key, version) => cache.get(key, version),
|
|
315
|
-
// A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with
|
|
316
|
-
|
|
161
|
+
// A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with
|
|
162
|
+
// it. The document's key is all before the last "#", which no ID holds, and no scope key either.
|
|
163
|
+
set: (key, version, piece) => cache.set(key, version, piece, key.slice(0, key.lastIndexOf("#"))),
|
|
317
164
|
// A quarter of the cache: a few documents can be kept, and no one pushes out all the rest.
|
|
318
165
|
maxDocumentBytes: cacheBytes / 4,
|
|
319
166
|
},
|
|
320
167
|
};
|
|
321
168
|
const keepOriginals = new Set(options.keepOriginals ?? []);
|
|
169
|
+
/** The ingests doing their work, and those waiting their turn (`maxConcurrentIngests`). */
|
|
170
|
+
const ingests = new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentIngests", options.maxConcurrentIngests, 2))));
|
|
171
|
+
/** How long work an ingest waits on, or gave up on, may keep its turn (see `IngestSlot`). */
|
|
172
|
+
const slotCapMs = ingestTimeoutMs > 0 && ingestTimeoutMs <= LONGEST_TIMER_MS ? ingestTimeoutMs : DEFAULT_INGEST_TIMEOUT_MS;
|
|
173
|
+
/**
|
|
174
|
+
* The looks at pages of every question of this library take their turns (`maxConcurrentPageLooks`).
|
|
175
|
+
* A look reads its original within the time the library gives its store calls (`slotCapMs`).
|
|
176
|
+
*/
|
|
177
|
+
const pageLooks = {
|
|
178
|
+
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentPageLooks", options.maxConcurrentPageLooks, DEFAULT_PAGE_LOOKS)))),
|
|
179
|
+
waitMs: Math.max(0, numberOption("pageLookWaitMs", options.pageLookWaitMs, DEFAULT_PAGE_LOOK_WAIT_MS)),
|
|
180
|
+
holdMs: slotCapMs,
|
|
181
|
+
};
|
|
322
182
|
const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
|
|
323
|
-
|
|
324
|
-
|
|
183
|
+
const { originals } = options;
|
|
184
|
+
if (originals !== undefined && (typeof originals !== "object" || originals === null || typeof originals.read !== "function")) {
|
|
185
|
+
throw new TypeError("originals must be an object with a read(ref, context) method, such as fileOriginals(root) gives.");
|
|
186
|
+
}
|
|
325
187
|
/**
|
|
326
|
-
*
|
|
327
|
-
*
|
|
188
|
+
* Whether the uploaded file of a document of this format is kept: by its ref (`IngestInput.original`),
|
|
189
|
+
* which `originals` reads back, or as a copy in the store (`putOriginal`).
|
|
328
190
|
*/
|
|
329
|
-
|
|
191
|
+
const keeps = (format, byRef) => keepOriginals.has(format) && (byRef ? originals !== undefined : typeof store.putOriginal === "function");
|
|
192
|
+
/**
|
|
193
|
+
* Whether the original of a document, which its metadata says is kept, can be read: by its ref,
|
|
194
|
+
* through `originals`, or from the store (`getOriginal`).
|
|
195
|
+
*/
|
|
196
|
+
const readable = (meta) => (meta.original !== undefined && meta.original !== null ? originals !== undefined : typeof store.getOriginal === "function");
|
|
197
|
+
/** Whether `view_pages` can show the pages of a document: a PDF whose original is kept, and can be read. */
|
|
198
|
+
const viewableMeta = (meta) => meta.format === "pdf" && meta.originalKept === true && readable(meta);
|
|
199
|
+
/** What `ingest` (src/ingest.ts) needs of this library. */
|
|
200
|
+
const ingestContext = {
|
|
201
|
+
store,
|
|
202
|
+
now,
|
|
203
|
+
ttlMs,
|
|
204
|
+
maxUploadBytes,
|
|
205
|
+
maxTextBytes,
|
|
206
|
+
maxPdfPages,
|
|
207
|
+
ingestTimeoutMs,
|
|
208
|
+
scannedPdfPages,
|
|
209
|
+
// Read at each ingest, as before the move: an application may set them after.
|
|
210
|
+
get extractors() {
|
|
211
|
+
return options.extractors;
|
|
212
|
+
},
|
|
213
|
+
ingests,
|
|
214
|
+
slotCapMs,
|
|
215
|
+
keeps,
|
|
216
|
+
readsRefs: originals !== undefined,
|
|
217
|
+
forget,
|
|
218
|
+
rules,
|
|
219
|
+
ingesting: new Set(),
|
|
220
|
+
};
|
|
221
|
+
/**
|
|
222
|
+
* The document as the store describes it now, asked with the caller's context: undefined when it
|
|
223
|
+
* was never there, has been deleted (by this server or another one sharing the store), or has
|
|
224
|
+
* expired. Whether the caller may use it is `metaFor`'s to say.
|
|
225
|
+
*/
|
|
226
|
+
async function currentMeta(id, caller) {
|
|
330
227
|
if (!isDocumentId(id))
|
|
331
228
|
return undefined;
|
|
332
|
-
const meta = await reading(() => store.getMeta(id));
|
|
229
|
+
const meta = metaOf(await reading(() => store.getMeta(id, caller.context)), id);
|
|
230
|
+
if (meta)
|
|
231
|
+
checkMetaVersion(meta);
|
|
333
232
|
if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
|
|
334
|
-
|
|
233
|
+
forgetKey(documentKey(caller, id));
|
|
335
234
|
return undefined;
|
|
336
235
|
}
|
|
337
236
|
return wholeName(meta);
|
|
338
237
|
}
|
|
238
|
+
/** The document, when `caller` may use it: one of another owner or scope is missing, not forbidden. */
|
|
239
|
+
async function metaFor(id, caller) {
|
|
240
|
+
const meta = await currentMeta(id, caller);
|
|
241
|
+
return meta && mayUse(meta, caller, rules) ? meta : undefined;
|
|
242
|
+
}
|
|
339
243
|
/**
|
|
340
|
-
* A document ready to read and search. The store is asked first,
|
|
341
|
-
* used only while the store still has the same document. `known` is
|
|
342
|
-
* the store, to save asking twice.
|
|
244
|
+
* A document ready to read and search, for `caller`, who may use it. The store is asked first,
|
|
245
|
+
* every time: a kept copy is used only while the store still has the same document. `known` is
|
|
246
|
+
* metadata just read from the store and checked, to save asking twice.
|
|
343
247
|
*/
|
|
344
|
-
async function load(id, known) {
|
|
345
|
-
const meta = known ?? await
|
|
248
|
+
async function load(id, caller, known) {
|
|
249
|
+
const meta = known ?? await metaFor(id, caller);
|
|
346
250
|
if (!meta)
|
|
347
251
|
return undefined;
|
|
252
|
+
const key = documentKey(caller, id);
|
|
348
253
|
const version = documentVersion(meta);
|
|
349
|
-
const cached = cache.get(
|
|
254
|
+
const cached = cache.get(key, version);
|
|
350
255
|
if (cached && !cached.broken)
|
|
351
256
|
return cached;
|
|
352
|
-
const
|
|
353
|
-
let pending = opening.get(
|
|
257
|
+
const opened = `${key}|${version}`;
|
|
258
|
+
let pending = opening.get(opened);
|
|
354
259
|
if (!pending) {
|
|
355
|
-
pending = open(id, meta).finally(() => opening.delete(
|
|
356
|
-
opening.set(
|
|
260
|
+
pending = open(id, meta, caller, key).finally(() => opening.delete(opened));
|
|
261
|
+
opening.set(opened, pending);
|
|
357
262
|
}
|
|
358
263
|
const document = await pending;
|
|
359
264
|
if (document)
|
|
360
|
-
cache.set(
|
|
265
|
+
cache.set(key, version, document);
|
|
361
266
|
return document;
|
|
362
267
|
}
|
|
363
|
-
/**
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
268
|
+
/**
|
|
269
|
+
* Reads a document from the store: its index, to read it by range, or all of it. `meta` is what
|
|
270
|
+
* `metaFor` found for `caller`. The reads carry the caller's scope, and the document's owner when it
|
|
271
|
+
* has one (`documentContext`): the copy is kept for every caller of the scope.
|
|
272
|
+
*/
|
|
273
|
+
async function open(id, meta, caller, key) {
|
|
274
|
+
const context = documentContext(meta, caller);
|
|
275
|
+
if (typeof store.readTextRange === "function" && meta.textBytes > wholeDocumentBytes) {
|
|
276
|
+
const rebuild = rebuildIndex.delete(key);
|
|
277
|
+
return openRangedDocument(rangeStore(context), meta, scan, { ignoreSavedIndex: rebuild, key });
|
|
368
278
|
}
|
|
369
|
-
const stored = await reading(() => store.get(id));
|
|
370
|
-
|
|
279
|
+
const stored = await reading(() => store.get(id, context));
|
|
280
|
+
// Another document is not this one: the metadata `get` gives must be of this ID, owner and
|
|
281
|
+
// scope, and of the version `meta` is (not one deleted and stored again since, by another
|
|
282
|
+
// server, nor one a store of your own gave from the wrong scope). And the text must be the one
|
|
283
|
+
// that metadata describes, of its length and its number of lines: a store that writes the text
|
|
284
|
+
// and the metadata apart can give one document's metadata with another's text (two servers that
|
|
285
|
+
// ingest one ID at once, a file read between two writes). A document read by range is checked
|
|
286
|
+
// too: its index against the metadata, and the end of its text against its index
|
|
287
|
+
// (openRangedDocument). Missing, as for a caller who may not use it.
|
|
288
|
+
const found = stored ? metaOf(stored.meta, id) : undefined;
|
|
289
|
+
if (!stored || !found || !mayUse(found, caller, rules) || documentVersion(found) !== documentVersion(meta))
|
|
290
|
+
return undefined;
|
|
291
|
+
if (typeof stored.text !== "string" || stored.text.length !== found.characters)
|
|
371
292
|
return undefined;
|
|
372
|
-
const named = wholeName(
|
|
373
|
-
|
|
293
|
+
const named = wholeName(found);
|
|
294
|
+
const document = new SearchableDocument(named === stored.meta ? stored : { ...stored, meta: named });
|
|
295
|
+
return document.lineCount === found.lines ? document : undefined;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* The uploaded file of document `id`, which `meta`, checked for `caller`, says is kept: read from
|
|
299
|
+
* where the application keeps it (`meta.original`, through `originals`), or from the store. Another
|
|
300
|
+
* server may delete the document and store another under its ID while the bytes are read: so the
|
|
301
|
+
* store is asked again once they are. "missing" unless it still describes the same document, of
|
|
302
|
+
* the same owner and scope, and the bytes are the size of the file that was ingested, and have its
|
|
303
|
+
* SHA-256 when it is known (0.9.0): a store that gives back other bytes of the same size is caught
|
|
304
|
+
* too. "changed" for a file kept by the application that is no longer the one that was ingested:
|
|
305
|
+
* of another size or another SHA-256.
|
|
306
|
+
*/
|
|
307
|
+
async function originalOf(id, caller, meta) {
|
|
308
|
+
const kept = refOf(meta);
|
|
309
|
+
let read;
|
|
310
|
+
if (kept) {
|
|
311
|
+
if (!originals)
|
|
312
|
+
return "missing";
|
|
313
|
+
const context = Object.freeze({ ...caller.context, id, bytes: kept.bytes });
|
|
314
|
+
read = await reading(() => originals.read(kept.ref, context));
|
|
315
|
+
}
|
|
316
|
+
else {
|
|
317
|
+
if (meta.original !== undefined && meta.original !== null)
|
|
318
|
+
return "missing";
|
|
319
|
+
if (!store.getOriginal)
|
|
320
|
+
return "missing";
|
|
321
|
+
read = await loadOriginal(id, caller.context);
|
|
322
|
+
}
|
|
323
|
+
if (!read)
|
|
324
|
+
return "missing";
|
|
325
|
+
const bytes = read;
|
|
326
|
+
const after = await metaFor(id, caller);
|
|
327
|
+
if (!after || documentVersion(after) !== documentVersion(meta))
|
|
328
|
+
return "missing";
|
|
329
|
+
// The SHA-256 of a file of up to the upload limit is taken a slice at a time.
|
|
330
|
+
const same = async (sha256) => await sha256InSlices(bytes, new TimeSlicer()) === sha256;
|
|
331
|
+
if (kept)
|
|
332
|
+
return bytes.byteLength === kept.bytes && await same(kept.sha256) ? bytes : "changed";
|
|
333
|
+
if (bytes.byteLength !== meta.bytes)
|
|
334
|
+
return "missing";
|
|
335
|
+
return typeof meta.sha256 === "string" && !await same(meta.sha256) ? "missing" : bytes;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Whether `document`, which a call of `caller` has just read, is still the one the store describes
|
|
339
|
+
* for `caller`. A document loaded whole was checked as it was read (see `open`). The bytes of one
|
|
340
|
+
* read by range carry nothing to check them by, and another server, or this one, may delete the
|
|
341
|
+
* document and store another under its ID while they are read, or between the look-up and the
|
|
342
|
+
* reads: so the store is asked again once they are, as `originalOf` does. When it no longer
|
|
343
|
+
* describes the same document, of the same owner and scope, what was read may be another's: the
|
|
344
|
+
* copy kept of it, read from the store too, is forgotten, and the read is missing.
|
|
345
|
+
*/
|
|
346
|
+
async function stillOpened(document, caller) {
|
|
347
|
+
if (!(document instanceof RangedDocument))
|
|
348
|
+
return true;
|
|
349
|
+
const after = await metaFor(document.meta.id, caller);
|
|
350
|
+
if (after && documentVersion(after) === documentVersion(document.meta))
|
|
351
|
+
return true;
|
|
352
|
+
forgetKey(documentKey(caller, document.meta.id));
|
|
353
|
+
return false;
|
|
374
354
|
}
|
|
375
355
|
/**
|
|
376
356
|
* What a document contributes to the prompt: its text, or its card. Undefined when it is gone
|
|
377
357
|
* by now. A copy found to disagree with the store is opened again once.
|
|
378
358
|
*/
|
|
379
|
-
async function block(id, meta, whole, viewable, wholeRead) {
|
|
359
|
+
async function block(id, meta, caller, whole, viewable, wholeRead) {
|
|
380
360
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
381
|
-
const document = await load(id, attempt === 0 ? meta : undefined);
|
|
361
|
+
const document = await load(id, caller, attempt === 0 ? meta : undefined);
|
|
382
362
|
if (!document)
|
|
383
363
|
return undefined;
|
|
364
|
+
let text;
|
|
384
365
|
try {
|
|
385
|
-
|
|
366
|
+
text = whole
|
|
386
367
|
? renderInline(document.meta, await document.readText())
|
|
387
368
|
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
|
|
388
369
|
}
|
|
389
370
|
catch (error) {
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
}
|
|
400
|
-
async function metaFor(id, access) {
|
|
401
|
-
const meta = await currentMeta(id);
|
|
402
|
-
return meta && allowed(meta, access) ? meta : undefined;
|
|
403
|
-
}
|
|
404
|
-
/**
|
|
405
|
-
* The work of `ingest`, once the file is named: `detected` is the format its name and type say.
|
|
406
|
-
* `progress` is given when someone listens to the events of the ingest. `storeFailed` is called
|
|
407
|
-
* when the store fails to write the document, whatever it throws.
|
|
408
|
-
*/
|
|
409
|
-
async function ingestFile(input, name, mimeType, detected, progress, storeFailed) {
|
|
410
|
-
if (input.bytes.byteLength === 0)
|
|
411
|
-
throw new Error(`${name} is empty.`);
|
|
412
|
-
if (input.bytes.byteLength > maxUploadBytes) {
|
|
413
|
-
throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
|
|
414
|
-
}
|
|
415
|
-
let format = detected;
|
|
416
|
-
const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
|
|
417
|
-
// Each long step works in slices, with pauses for other requests: one large upload no longer
|
|
418
|
-
// holds the whole server while it is read.
|
|
419
|
-
const slicer = new TimeSlicer(signal);
|
|
420
|
-
let pages;
|
|
421
|
-
let reading;
|
|
422
|
-
let text;
|
|
423
|
-
let wrapped;
|
|
424
|
-
let lines;
|
|
425
|
-
let measured;
|
|
426
|
-
let outline;
|
|
427
|
-
let logProfile;
|
|
428
|
-
let quality = {};
|
|
429
|
-
let index;
|
|
430
|
-
try {
|
|
431
|
-
signal.throwIfAborted();
|
|
432
|
-
// In a function of its own, so that the text as extracted is let go once it is prepared:
|
|
433
|
-
// the steps after it hold only the prepared text.
|
|
434
|
-
const read = async () => {
|
|
435
|
-
// What an extractor of your own reports once it has settled (from a timer, a worker) is
|
|
436
|
-
// not reported: the stages after it have begun.
|
|
437
|
-
let extracting = true;
|
|
438
|
-
let extracted;
|
|
439
|
-
try {
|
|
440
|
-
extracted = await untilAborted(extractText(input.bytes, {
|
|
441
|
-
name,
|
|
442
|
-
mimeType,
|
|
443
|
-
format,
|
|
444
|
-
// A scan is worth storing only if its pages can be shown later: that needs the file itself.
|
|
445
|
-
...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
|
|
446
|
-
signal,
|
|
447
|
-
maxTextBytes,
|
|
448
|
-
maxPages: maxPdfPages,
|
|
449
|
-
...(progress ? { onProgress: (report) => { if (extracting)
|
|
450
|
-
progress.extracted(report); } } : {}),
|
|
451
|
-
}, options.extractors), signal);
|
|
452
|
-
}
|
|
453
|
-
finally {
|
|
454
|
-
extracting = false;
|
|
455
|
-
}
|
|
456
|
-
progress?.end();
|
|
457
|
-
// A character is at least one byte: a text this long is too large whatever it holds.
|
|
458
|
-
if (extracted.text.length > maxTextBytes)
|
|
459
|
-
throw tooMuchText(name, maxTextBytes);
|
|
460
|
-
await slicer.pauseNow();
|
|
461
|
-
return { pages: extracted.pages, reading: readingOf(extracted), ...await prepareText(extracted.text, slicer, progress && ((done, total) => progress.report("prepare", done, total, "characters"))) };
|
|
462
|
-
};
|
|
463
|
-
({ pages, reading, text, wrapped, lines } = await read());
|
|
464
|
-
progress?.end();
|
|
465
|
-
if (!text.trim())
|
|
466
|
-
throw new Error(`${name} did not contain any text.`);
|
|
467
|
-
if (format === "text" && looksLikeLog(lines))
|
|
468
|
-
format = "log";
|
|
469
|
-
measured = await measureText(text, slicer);
|
|
470
|
-
if (measured.utf8 > maxTextBytes)
|
|
471
|
-
throw tooMuchText(name, maxTextBytes);
|
|
472
|
-
outline = await buildOutlineInSlices(lines, format, slicer);
|
|
473
|
-
logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
|
|
474
|
-
quality = await measureQuality(lines, format, slicer);
|
|
475
|
-
// The line index, so that the text can be read by range: a few bytes a line, built from the
|
|
476
|
-
// UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
|
|
477
|
-
// then loads whole, so that switching to reading by range finds it ready.
|
|
478
|
-
index = typeof store.putIndex === "function"
|
|
479
|
-
? await buildTextIndexInSlices(text, slicer, progress && ((done, total) => progress.report("index", done, total, "characters")))
|
|
480
|
-
: undefined;
|
|
481
|
-
progress?.end();
|
|
482
|
-
signal.throwIfAborted();
|
|
483
|
-
}
|
|
484
|
-
finally {
|
|
485
|
-
dispose();
|
|
486
|
-
}
|
|
487
|
-
const created = now();
|
|
488
|
-
const expires = created.getTime() + ttlMs;
|
|
489
|
-
const keepOriginal = keeps(format);
|
|
490
|
-
const meta = {
|
|
491
|
-
id: `doc_${randomUUID().replaceAll("-", "")}`,
|
|
492
|
-
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
493
|
-
name,
|
|
494
|
-
mimeType,
|
|
495
|
-
format,
|
|
496
|
-
bytes: input.bytes.byteLength,
|
|
497
|
-
textBytes: measured.utf8,
|
|
498
|
-
jsonBytes: measured.json,
|
|
499
|
-
characters: text.length,
|
|
500
|
-
lines: lines.length,
|
|
501
|
-
estimatedTokens: measured.tokens,
|
|
502
|
-
wrappedLines: wrapped,
|
|
503
|
-
...(pages ? { pages } : {}),
|
|
504
|
-
...reading,
|
|
505
|
-
...(keepOriginal ? { originalKept: true } : {}),
|
|
506
|
-
outline,
|
|
507
|
-
...(logProfile ? { logProfile } : {}),
|
|
508
|
-
...quality,
|
|
509
|
-
createdAt: created.toISOString(),
|
|
510
|
-
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
511
|
-
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
512
|
-
};
|
|
513
|
-
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
|
|
514
|
-
? serializeTextIndex(index)
|
|
515
|
-
: undefined;
|
|
516
|
-
// Each write is reported once done. What the listener of the events throws is not the store's failure.
|
|
517
|
-
const writes = (keepOriginal ? 1 : 0) + (savedIndex ? 1 : 0) + 1;
|
|
518
|
-
let written = 0;
|
|
519
|
-
let listenerFailed;
|
|
520
|
-
const wrote = (last) => {
|
|
521
|
-
if (!progress)
|
|
522
|
-
return;
|
|
523
|
-
try {
|
|
524
|
-
progress.report("store", ++written, writes, "parts");
|
|
525
|
-
if (last)
|
|
526
|
-
progress.end();
|
|
527
|
-
}
|
|
528
|
-
catch (error) {
|
|
529
|
-
listenerFailed = { error };
|
|
371
|
+
// The text is gone while its metadata is still there (removed outside the library): the
|
|
372
|
+
// same as missing. It was a plain Error, which failed the whole question.
|
|
373
|
+
if (error instanceof DocumentGoneError)
|
|
374
|
+
return undefined;
|
|
375
|
+
if (document.broken)
|
|
376
|
+
continue;
|
|
377
|
+
// Deleted between the look-up and the read: the same as missing.
|
|
378
|
+
if (!await metaFor(id, caller))
|
|
379
|
+
return undefined;
|
|
530
380
|
throw error;
|
|
531
381
|
}
|
|
532
|
-
|
|
533
|
-
try {
|
|
534
|
-
// The files first, the document last: a document is there once its metadata is.
|
|
535
|
-
if (keepOriginal) {
|
|
536
|
-
await store.putOriginal(meta.id, input.bytes);
|
|
537
|
-
wrote(false);
|
|
538
|
-
}
|
|
539
|
-
if (savedIndex) {
|
|
540
|
-
await store.putIndex(meta.id, savedIndex);
|
|
541
|
-
wrote(false);
|
|
542
|
-
}
|
|
543
|
-
await store.put({ meta, text });
|
|
544
|
-
wrote(true);
|
|
545
|
-
}
|
|
546
|
-
catch (error) {
|
|
547
|
-
// Do not leave a file of up to the upload limit, or a part of one, behind for a document
|
|
548
|
-
// that does not exist.
|
|
549
|
-
await store.delete(meta.id).catch(() => undefined);
|
|
550
|
-
if (listenerFailed?.error !== error) {
|
|
551
|
-
noteStoreWriteFailure(error);
|
|
552
|
-
storeFailed();
|
|
553
|
-
}
|
|
554
|
-
throw error;
|
|
382
|
+
return await stillOpened(document, caller) ? text : undefined;
|
|
555
383
|
}
|
|
556
|
-
return
|
|
384
|
+
return undefined;
|
|
557
385
|
}
|
|
558
386
|
return {
|
|
559
387
|
budget,
|
|
560
388
|
budgetFor,
|
|
561
389
|
maxUploadBytes,
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
try {
|
|
569
|
-
listener(event);
|
|
570
|
-
}
|
|
571
|
-
catch (error) {
|
|
572
|
-
listenerFailure ??= { error };
|
|
573
|
-
throw error;
|
|
574
|
-
}
|
|
575
|
-
}));
|
|
576
|
-
let storeFailed = false;
|
|
577
|
-
try {
|
|
578
|
-
if (events.active)
|
|
579
|
-
events.emit({ type: "ingest.start", ...startOf(input) });
|
|
580
|
-
checkOwner(input.owner);
|
|
581
|
-
const name = cleanFileName(input.name);
|
|
582
|
-
const mimeType = input.mimeType?.trim() || "application/octet-stream";
|
|
583
|
-
// A file whose name and type say nothing is known by its bytes: a PDF, an Office file, a page.
|
|
584
|
-
const format = detectFormat(name, mimeType, input.bytes instanceof Uint8Array ? input.bytes : undefined);
|
|
585
|
-
// Progress is worked out only for someone who listens.
|
|
586
|
-
const progress = events.active ? new IngestProgress(events) : undefined;
|
|
587
|
-
let meta;
|
|
588
|
-
try {
|
|
589
|
-
meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true));
|
|
590
|
-
}
|
|
591
|
-
catch (error) {
|
|
592
|
-
// A store that failed, and a caller that gave up (its own reason), are passed on as they
|
|
593
|
-
// are; a file that could not be read is told with a code.
|
|
594
|
-
if (storeFailed || (input.signal?.aborted && error === input.signal.reason) || isStoreWriteFailure(error) || (listenerFailure && error === listenerFailure.error))
|
|
595
|
-
throw error;
|
|
596
|
-
throw toIngestError(error);
|
|
597
|
-
}
|
|
598
|
-
try {
|
|
599
|
-
events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
|
|
600
|
-
}
|
|
601
|
-
catch (error) {
|
|
602
|
-
// The caller never gets the id: the document goes, as on a throw of the listener a moment earlier.
|
|
603
|
-
await store.delete(meta.id).catch(() => undefined);
|
|
604
|
-
forget(meta.id);
|
|
605
|
-
throw error;
|
|
606
|
-
}
|
|
607
|
-
return meta;
|
|
608
|
-
}
|
|
609
|
-
catch (error) {
|
|
610
|
-
// A store's own error may name a host or a path, whatever it is: the event, which a browser
|
|
611
|
-
// may see, says only that the document could not be stored.
|
|
612
|
-
events.emit({ type: "ingest.error", error: storeFailed ? { message: STORE_WRITE_FAILED } : eventErrorOf(error) });
|
|
613
|
-
throw error;
|
|
614
|
-
}
|
|
390
|
+
access: rules,
|
|
391
|
+
ingest(input) {
|
|
392
|
+
return ingestDocument(ingestContext, input);
|
|
393
|
+
},
|
|
394
|
+
async getMeta(id, access) {
|
|
395
|
+
return metaFor(id, callerOf(access, rules));
|
|
615
396
|
},
|
|
616
|
-
getMeta: metaFor,
|
|
617
397
|
async getOriginal(id, access) {
|
|
618
|
-
const
|
|
619
|
-
|
|
398
|
+
const caller = callerOf(access, rules);
|
|
399
|
+
const meta = await metaFor(id, caller);
|
|
400
|
+
if (!meta?.originalKept || !readable(meta))
|
|
401
|
+
return undefined;
|
|
402
|
+
const original = await originalOf(id, caller, meta);
|
|
403
|
+
return original instanceof Uint8Array ? original : undefined;
|
|
620
404
|
},
|
|
621
405
|
async delete(id, access) {
|
|
622
|
-
|
|
406
|
+
const caller = callerOf(access, rules);
|
|
407
|
+
if (!await metaFor(id, caller))
|
|
623
408
|
return false;
|
|
624
409
|
forget(id);
|
|
625
|
-
return
|
|
410
|
+
return storeCall("delete", () => store.delete(id, caller.context));
|
|
626
411
|
},
|
|
627
|
-
async sweep() {
|
|
628
|
-
|
|
412
|
+
async sweep(sweepOptions) {
|
|
413
|
+
// Upkeep of the store, not a user's access: allowed without a scope under `requireScope`.
|
|
414
|
+
const scope = checkScope(sweepOptions?.scope ?? undefined);
|
|
415
|
+
if (typeof store.sweep !== "function")
|
|
416
|
+
return 0;
|
|
417
|
+
return storeCall("sweep", () => store.sweep(now(), storeContext(scope, undefined)));
|
|
629
418
|
},
|
|
630
419
|
async prepare(ids, base, access) {
|
|
420
|
+
const caller = callerOf(access, rules);
|
|
631
421
|
const budget = budgetFor(access?.budget);
|
|
632
422
|
const analysis = access?.wholeDocumentAnalysis !== false;
|
|
633
423
|
const unique = [...new Set(ids)];
|
|
634
424
|
let documents = [];
|
|
635
425
|
const missing = [];
|
|
636
426
|
for (const id of unique) {
|
|
637
|
-
// A document
|
|
638
|
-
// read at all.
|
|
639
|
-
const meta = await metaFor(id,
|
|
427
|
+
// A document of another owner or scope is reported as missing, not as forbidden, and is
|
|
428
|
+
// not read at all.
|
|
429
|
+
const meta = await metaFor(id, caller);
|
|
640
430
|
if (meta)
|
|
641
431
|
documents.push(meta);
|
|
642
432
|
else
|
|
@@ -648,15 +438,13 @@ export function createLargeFiles(options) {
|
|
|
648
438
|
const plan = planDocuments(documents, budget, base);
|
|
649
439
|
const inline = new Set(plan.inline.map((meta) => meta.id));
|
|
650
440
|
// Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
|
|
651
|
-
const viewable = access?.viewPages
|
|
652
|
-
? documents.filter((meta) => meta.format === "pdf" && meta.originalKept)
|
|
653
|
-
: [];
|
|
441
|
+
const viewable = access?.viewPages ? documents.filter(viewableMeta) : [];
|
|
654
442
|
const shown = new Set(viewable.map((meta) => meta.id));
|
|
655
443
|
const blocks = new Map();
|
|
656
444
|
const gone = [];
|
|
657
445
|
for (const meta of documents) {
|
|
658
446
|
const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
|
|
659
|
-
const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), wholeRead);
|
|
447
|
+
const text = await block(meta.id, meta, caller, inline.has(meta.id), shown.has(meta.id), wholeRead);
|
|
660
448
|
if (text === undefined)
|
|
661
449
|
gone.push(meta.id);
|
|
662
450
|
else
|
|
@@ -673,30 +461,53 @@ export function createLargeFiles(options) {
|
|
|
673
461
|
}
|
|
674
462
|
},
|
|
675
463
|
tools(documents, toolOptions = {}) {
|
|
676
|
-
const { viewPages, budget: overrides, ...rest } = toolOptions;
|
|
464
|
+
const { viewPages, budget: overrides, access, ...rest } = toolOptions;
|
|
465
|
+
// Without `access`, the owner and scope of each document are those it was handed in with: a
|
|
466
|
+
// library that requires them takes them only from the caller.
|
|
467
|
+
if (access === undefined && (rules.requireOwner || rules.requireScope)) {
|
|
468
|
+
throw new TypeError(rules.requireOwner ? OWNER_REQUIRED : SCOPE_REQUIRED);
|
|
469
|
+
}
|
|
470
|
+
const asker = access !== undefined ? callerOf(access, rules) : undefined;
|
|
677
471
|
const budget = budgetFor(overrides);
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
//
|
|
682
|
-
//
|
|
683
|
-
|
|
684
|
-
|
|
472
|
+
// Which PDFs can be looked at, by the metadata handed in: each look reads the metadata the
|
|
473
|
+
// store holds, and the file it names, not the one handed in.
|
|
474
|
+
const viewable = (viewPages === true ? documents : viewPages || []).filter(viewableMeta);
|
|
475
|
+
// Without `access`, as before 0.9.0: the owner and scope each document was handed in with.
|
|
476
|
+
// The store is asked with them, and the owner and scope it holds are checked against them on
|
|
477
|
+
// every call, so metadata built from an ID alone cannot read another owner's document: such a
|
|
478
|
+
// document is answered as no longer available, as `getMeta` reports it missing. A handed scope
|
|
479
|
+
// that is not valid reads nothing.
|
|
480
|
+
const handed = new Map(asker ? [] : [...documents, ...viewable].map((meta) => [meta.id, handedCaller(meta)]));
|
|
481
|
+
const callerFor = (id) => asker ?? (handed.has(id) ? handed.get(id) : NO_CALLER);
|
|
685
482
|
// The metadata the store holds now, not that of a copy kept in memory.
|
|
686
483
|
const checkedLoad = async (id) => {
|
|
687
|
-
const
|
|
688
|
-
|
|
484
|
+
const caller = callerFor(id);
|
|
485
|
+
const meta = caller && await metaFor(id, caller);
|
|
486
|
+
return meta ? load(id, caller, meta) : undefined;
|
|
689
487
|
};
|
|
690
|
-
const checkedOriginal =
|
|
691
|
-
const
|
|
692
|
-
|
|
488
|
+
const checkedOriginal = (store.getOriginal || originals) && (async (id) => {
|
|
489
|
+
const caller = callerFor(id);
|
|
490
|
+
const meta = caller && await metaFor(id, caller);
|
|
491
|
+
if (!meta || !readable(meta))
|
|
492
|
+
return undefined;
|
|
493
|
+
const original = await originalOf(id, caller, meta);
|
|
494
|
+
// A file the application keeps that has changed since it was ingested: its pages are not
|
|
495
|
+
// those of the text the model has, and the model is told so.
|
|
496
|
+
if (original === "changed")
|
|
497
|
+
throw new Error(changedOriginal(meta.name));
|
|
498
|
+
return original === "missing" ? undefined : original;
|
|
693
499
|
});
|
|
694
500
|
return createDocumentTools({
|
|
695
501
|
load: checkedLoad,
|
|
502
|
+
// Once a call has read a document by range: the store is asked again (`stillOpened`).
|
|
503
|
+
checkRead: async (document) => {
|
|
504
|
+
const caller = callerFor(document.meta.id);
|
|
505
|
+
return caller !== undefined && await stillOpened(document, caller);
|
|
506
|
+
},
|
|
696
507
|
documentIds: documents.map((meta) => meta.id),
|
|
697
508
|
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
698
509
|
budget,
|
|
699
|
-
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
|
|
510
|
+
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal, pageLooks } : {}),
|
|
700
511
|
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
701
512
|
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
702
513
|
// `aggregate_table` only when one may hold a table.
|
|
@@ -705,5 +516,14 @@ export function createLargeFiles(options) {
|
|
|
705
516
|
});
|
|
706
517
|
},
|
|
707
518
|
};
|
|
519
|
+
/** The caller a document was handed to `tools` for (without `access`): its owner and scope. Undefined for a scope that is not valid. */
|
|
520
|
+
function handedCaller(meta) {
|
|
521
|
+
try {
|
|
522
|
+
return callerOf({ owner: meta.owner, scope: meta.scope }, rules);
|
|
523
|
+
}
|
|
524
|
+
catch {
|
|
525
|
+
return undefined;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
708
528
|
}
|
|
709
529
|
//# sourceMappingURL=library.js.map
|