llm-large-files 0.3.6 → 0.4.1
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 +115 -0
- package/dist/cache.d.ts +49 -0
- package/dist/cache.d.ts.map +1 -0
- package/dist/cache.js +110 -0
- package/dist/cache.js.map +1 -0
- package/dist/errors.d.ts +21 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +44 -0
- package/dist/errors.js.map +1 -0
- package/dist/gemini/chat.d.ts +5 -0
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +17 -1
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -0
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +110 -25
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +1 -1
- package/dist/gemini/index.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +48 -2
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +192 -52
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +20 -0
- package/dist/limiter.d.ts.map +1 -0
- package/dist/limiter.js +55 -0
- package/dist/limiter.js.map +1 -0
- package/dist/map-reduce.d.ts +14 -4
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +99 -33
- package/dist/map-reduce.js.map +1 -1
- package/dist/plan.d.ts +25 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +51 -13
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts +102 -0
- package/dist/ranged.d.ts.map +1 -0
- package/dist/ranged.js +321 -0
- package/dist/ranged.js.map +1 -0
- package/dist/search.d.ts +93 -15
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +472 -131
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +26 -2
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +181 -21
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +64 -0
- package/dist/text-index.d.ts.map +1 -0
- package/dist/text-index.js +211 -0
- package/dist/text-index.js.map +1 -0
- package/dist/text.d.ts +14 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +50 -16
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +14 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +53 -21
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +20 -0
- package/dist/types.d.ts.map +1 -1
- package/docs/api.md +24 -10
- package/docs/configuration.md +50 -3
- package/docs/getting-started.md +2 -0
- package/docs/how-it-works.md +11 -3
- package/docs/security.md +21 -3
- package/package.json +7 -3
- package/src/cache.ts +107 -0
- package/src/errors.ts +42 -0
- package/src/gemini/chat.ts +22 -1
- package/src/gemini/generate.ts +107 -25
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +3 -2
- package/src/library.ts +229 -50
- package/src/limiter.ts +51 -0
- package/src/map-reduce.ts +101 -33
- package/src/plan.ts +54 -14
- package/src/ranged.ts +355 -0
- package/src/search.ts +524 -121
- package/src/stores.ts +178 -23
- package/src/text-index.ts +228 -0
- package/src/text.ts +46 -13
- package/src/tools.ts +61 -23
- package/src/types.ts +20 -0
package/dist/search.js
CHANGED
|
@@ -1,28 +1,80 @@
|
|
|
1
1
|
import { createContext, Script } from "node:vm";
|
|
2
|
+
import { PASSAGE_CHARACTERS, PASSAGE_MAX_LINES, positionOf } from "./text-index.js";
|
|
2
3
|
import { foldCase, LineIndex } from "./text.js";
|
|
3
|
-
const PASSAGE_CHARACTERS = 1_500;
|
|
4
|
-
const PASSAGE_MAX_LINES = 40;
|
|
5
4
|
const MAX_OCCURRENCES_PER_TERM = 200_000;
|
|
6
|
-
const
|
|
5
|
+
const MAX_EXACT_MATCHES = 1_000_000;
|
|
6
|
+
const MAX_PHRASE_PASSAGES = 10_000;
|
|
7
|
+
/** The most time one regex search may spend matching. */
|
|
8
|
+
export const REGEX_TIME_LIMIT_MS = 3_000;
|
|
9
|
+
/**
|
|
10
|
+
* A regex scan runs in slices of this length, and other work gets a turn between two slices. A
|
|
11
|
+
* line that takes two whole slices is a pattern that backtracks without end on it: the search
|
|
12
|
+
* stops there, long before its time limit.
|
|
13
|
+
*/
|
|
14
|
+
const REGEX_SLICE_MS = 250;
|
|
7
15
|
const SHOWN_LINE_CHARACTERS = 400;
|
|
8
16
|
const STOPWORDS = new Set([
|
|
9
17
|
"the", "and", "for", "are", "was", "with", "that", "this", "what", "how", "why", "when", "where", "who",
|
|
10
18
|
"from", "into", "about", "does", "did", "have", "has", "had", "you", "your", "can", "all", "any", "not",
|
|
11
19
|
"של", "את", "על", "עם", "מה", "איך", "למה", "מתי", "איפה", "מי", "זה", "זאת", "גם", "או", "אם", "כל", "יש", "אין",
|
|
12
20
|
]);
|
|
13
|
-
/**
|
|
21
|
+
/** Lets other work on the server run (an answer streaming to another user) before going on. */
|
|
22
|
+
export const pause = () => new Promise((resolve) => setImmediate(resolve));
|
|
23
|
+
/** Feeds a document's text, a piece at a time, to `feed` until it returns true or the text ends. */
|
|
24
|
+
export async function scanSource(source, feed, signal) {
|
|
25
|
+
if (source.scan)
|
|
26
|
+
return source.scan(feed, signal);
|
|
27
|
+
for await (const chunk of source.chunks(signal)) {
|
|
28
|
+
let more = feed(chunk);
|
|
29
|
+
while (more === "again") {
|
|
30
|
+
await pause();
|
|
31
|
+
signal?.throwIfAborted();
|
|
32
|
+
more = feed(chunk);
|
|
33
|
+
}
|
|
34
|
+
if (more === true)
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Lines as the tools show them: "12| text", one a line. */
|
|
39
|
+
export function numberLines(lines, from) {
|
|
40
|
+
return lines.map((text, index) => `${from + index}| ${text}`).join("\n");
|
|
41
|
+
}
|
|
42
|
+
/** The pages a range of lines is on, as "12" or "12-14", from the first line of each page. */
|
|
43
|
+
export function pagesOfLines(pageStarts, from, to) {
|
|
44
|
+
const page = (line) => (pageStarts.length === 0 || line < pageStarts[0] ? undefined : positionOf(pageStarts, line));
|
|
45
|
+
const last = page(to);
|
|
46
|
+
if (last === undefined)
|
|
47
|
+
return undefined;
|
|
48
|
+
const first = page(from) ?? 1;
|
|
49
|
+
return first === last ? String(last) : `${first}-${last}`;
|
|
50
|
+
}
|
|
51
|
+
/** A stored document held whole in memory, with lazily built search structures. */
|
|
14
52
|
export class SearchableDocument {
|
|
15
53
|
meta;
|
|
16
54
|
text;
|
|
17
55
|
lines;
|
|
18
56
|
lowerText;
|
|
19
|
-
|
|
57
|
+
passageStartList;
|
|
20
58
|
pageStarts;
|
|
21
59
|
constructor(document) {
|
|
22
60
|
this.meta = document.meta;
|
|
23
61
|
this.text = document.text;
|
|
24
62
|
this.lines = new LineIndex(document.text);
|
|
25
63
|
}
|
|
64
|
+
get lineCount() {
|
|
65
|
+
return this.lines.lineCount;
|
|
66
|
+
}
|
|
67
|
+
get characters() {
|
|
68
|
+
return this.text.length;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Memory this document takes once it has been searched: the text, its lowercased copy, and the
|
|
72
|
+
* line index. A text of ASCII only is held at one byte a character, any other at two.
|
|
73
|
+
*/
|
|
74
|
+
get memoryBytes() {
|
|
75
|
+
const ascii = this.meta.textBytes !== undefined && this.meta.textBytes === this.text.length;
|
|
76
|
+
return this.text.length * (ascii ? 1 : 2) * 2 + this.lines.lineCount * 4 + 1_024;
|
|
77
|
+
}
|
|
26
78
|
/** The text lowercased for case-insensitive search. Same length as `text`, so offsets match. */
|
|
27
79
|
get lower() {
|
|
28
80
|
this.lowerText ??= foldCase(this.text);
|
|
@@ -30,7 +82,7 @@ export class SearchableDocument {
|
|
|
30
82
|
}
|
|
31
83
|
/** First line of each passage: groups of lines up to about 1,500 characters. */
|
|
32
84
|
get passages() {
|
|
33
|
-
if (!this.
|
|
85
|
+
if (!this.passageStartList) {
|
|
34
86
|
const starts = [];
|
|
35
87
|
let line = 1;
|
|
36
88
|
while (line <= this.lines.lineCount) {
|
|
@@ -43,26 +95,19 @@ export class SearchableDocument {
|
|
|
43
95
|
line++;
|
|
44
96
|
}
|
|
45
97
|
}
|
|
46
|
-
this.
|
|
98
|
+
this.passageStartList = starts;
|
|
47
99
|
}
|
|
48
|
-
return this.
|
|
100
|
+
return this.passageStartList;
|
|
101
|
+
}
|
|
102
|
+
get passageStarts() {
|
|
103
|
+
return this.passages;
|
|
49
104
|
}
|
|
50
105
|
passageRange(index) {
|
|
51
106
|
const starts = this.passages;
|
|
52
107
|
return { from: starts[index], to: (starts[index + 1] ?? this.lines.lineCount + 1) - 1 };
|
|
53
108
|
}
|
|
54
109
|
passageOfLine(line) {
|
|
55
|
-
|
|
56
|
-
let low = 0;
|
|
57
|
-
let high = starts.length - 1;
|
|
58
|
-
while (low < high) {
|
|
59
|
-
const middle = (low + high + 1) >> 1;
|
|
60
|
-
if (starts[middle] <= line)
|
|
61
|
-
low = middle;
|
|
62
|
-
else
|
|
63
|
-
high = middle - 1;
|
|
64
|
-
}
|
|
65
|
-
return low;
|
|
110
|
+
return positionOf(this.passages, line) - 1;
|
|
66
111
|
}
|
|
67
112
|
/**
|
|
68
113
|
* The page a line is on, from the "--- Page N ---" lines the PDF extractor writes. Undefined for
|
|
@@ -70,6 +115,30 @@ export class SearchableDocument {
|
|
|
70
115
|
* used, so a line of the document that happens to read "--- Page 7 ---" is not taken for one.
|
|
71
116
|
*/
|
|
72
117
|
pageOfLine(line) {
|
|
118
|
+
const starts = this.pageLines();
|
|
119
|
+
return starts.length === 0 || line < starts[0] ? undefined : positionOf(starts, line);
|
|
120
|
+
}
|
|
121
|
+
/** The pages a range of lines is on, as "12" or "12-14". Undefined for a text without page lines. */
|
|
122
|
+
pagesOfLines(from, to) {
|
|
123
|
+
return pagesOfLines(this.pageLines(), from, to);
|
|
124
|
+
}
|
|
125
|
+
async readLines(from, to) {
|
|
126
|
+
const out = [];
|
|
127
|
+
for (let line = Math.max(1, from); line <= Math.min(to, this.lines.lineCount); line++)
|
|
128
|
+
out.push(this.lines.line(line));
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
async readText() {
|
|
132
|
+
return this.text;
|
|
133
|
+
}
|
|
134
|
+
/** The whole text as one piece. */
|
|
135
|
+
wholeChunk() {
|
|
136
|
+
return { firstLine: 1, startCharacter: 0, text: this.text, lines: this.lines, lower: () => this.lower };
|
|
137
|
+
}
|
|
138
|
+
async *chunks() {
|
|
139
|
+
yield this.wholeChunk();
|
|
140
|
+
}
|
|
141
|
+
pageLines() {
|
|
73
142
|
if (!this.pageStarts) {
|
|
74
143
|
const starts = [];
|
|
75
144
|
const marker = "--- Page ";
|
|
@@ -82,27 +151,7 @@ export class SearchableDocument {
|
|
|
82
151
|
}
|
|
83
152
|
this.pageStarts = starts;
|
|
84
153
|
}
|
|
85
|
-
|
|
86
|
-
if (starts.length === 0 || line < starts[0])
|
|
87
|
-
return undefined;
|
|
88
|
-
let low = 0;
|
|
89
|
-
let high = starts.length - 1;
|
|
90
|
-
while (low < high) {
|
|
91
|
-
const middle = (low + high + 1) >> 1;
|
|
92
|
-
if (starts[middle] <= line)
|
|
93
|
-
low = middle;
|
|
94
|
-
else
|
|
95
|
-
high = middle - 1;
|
|
96
|
-
}
|
|
97
|
-
return low + 1;
|
|
98
|
-
}
|
|
99
|
-
/** The pages a range of lines is on, as "12" or "12-14". Undefined for a text without page lines. */
|
|
100
|
-
pagesOfLines(from, to) {
|
|
101
|
-
const last = this.pageOfLine(to);
|
|
102
|
-
if (last === undefined)
|
|
103
|
-
return undefined;
|
|
104
|
-
const first = this.pageOfLine(from) ?? 1;
|
|
105
|
-
return first === last ? String(last) : `${first}-${last}`;
|
|
154
|
+
return this.pageStarts;
|
|
106
155
|
}
|
|
107
156
|
}
|
|
108
157
|
function clip(line, column) {
|
|
@@ -126,7 +175,7 @@ function withinTimeLimit(scan, milliseconds) {
|
|
|
126
175
|
scanContext ??= createContext(scanSandbox);
|
|
127
176
|
scanSandbox.scan = scan;
|
|
128
177
|
try {
|
|
129
|
-
RUN_SCAN.runInContext(scanContext, { timeout: milliseconds });
|
|
178
|
+
RUN_SCAN.runInContext(scanContext, { timeout: Math.max(1, Math.ceil(milliseconds)) });
|
|
130
179
|
return true;
|
|
131
180
|
}
|
|
132
181
|
catch (error) {
|
|
@@ -156,113 +205,405 @@ export function unsafeRegexReason(pattern) {
|
|
|
156
205
|
}
|
|
157
206
|
return null;
|
|
158
207
|
}
|
|
159
|
-
/**
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
208
|
+
/**
|
|
209
|
+
* The pattern as a regular expression. With the Unicode flag when the pattern allows it, so that
|
|
210
|
+
* `\p{L}` means a letter and a character outside the basic plane is one character; without it for
|
|
211
|
+
* a pattern that is only valid the old way (`[\w-.]`, `\-`).
|
|
212
|
+
*/
|
|
213
|
+
function compileRegex(pattern, flags) {
|
|
214
|
+
try {
|
|
215
|
+
return new RegExp(pattern, `${flags}u`);
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return new RegExp(pattern, flags);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const newlinesIn = (text) => text.split("\n").length - 1;
|
|
222
|
+
/**
|
|
223
|
+
* The text of the `keep` lines before a piece, with their line breaks, and the number of its
|
|
224
|
+
* first line: what a needle across lines may start in.
|
|
225
|
+
*/
|
|
226
|
+
function carried(recent, keep) {
|
|
227
|
+
const lines = recent.slice(-keep);
|
|
228
|
+
if (lines.length === 0)
|
|
229
|
+
return undefined;
|
|
230
|
+
return { text: lines.map(([, text]) => `${text}\n`).join(""), firstLine: lines[0][0] };
|
|
231
|
+
}
|
|
232
|
+
/** The lines read last, for lines shown before a hit and for needles across lines. */
|
|
233
|
+
function remember(recent, chunk, keep) {
|
|
234
|
+
if (keep === 0)
|
|
235
|
+
return recent;
|
|
236
|
+
const count = chunk.lines.lineCount;
|
|
237
|
+
const fresh = [];
|
|
238
|
+
for (let local = Math.max(1, count - keep + 1); local <= count; local++)
|
|
239
|
+
fresh.push([chunk.firstLine + local - 1, chunk.lines.line(local)]);
|
|
240
|
+
return [...recent, ...fresh].slice(-keep);
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Lines that contain `query` (exact text) or match it (regex), counted over a whole document fed
|
|
244
|
+
* a piece at a time. The pieces must come in order. Given the whole text as one piece, it does
|
|
245
|
+
* what `grep` always did; given it in pieces, it finds the same lines.
|
|
246
|
+
*/
|
|
247
|
+
class LineSearch {
|
|
248
|
+
settings;
|
|
249
|
+
lineCount;
|
|
250
|
+
hits = [];
|
|
251
|
+
total = 0;
|
|
252
|
+
stoppedEarly = false;
|
|
253
|
+
/** True once nothing more is to be found or counted: the rest of the text need not be read. */
|
|
254
|
+
done = false;
|
|
255
|
+
context;
|
|
256
|
+
/** Lines shown around the hits, by number: undefined until their piece has been read. */
|
|
257
|
+
shown = new Map();
|
|
258
|
+
unfilled = 0;
|
|
259
|
+
recent = [];
|
|
260
|
+
keep;
|
|
261
|
+
needle = "";
|
|
262
|
+
newlines = 0;
|
|
263
|
+
/** Exact mode: where the next match may start in the whole text, as the scan of one string skips past each match. */
|
|
264
|
+
nextAllowed = 0;
|
|
265
|
+
lastLine = 0;
|
|
266
|
+
pattern;
|
|
267
|
+
timeLeft;
|
|
268
|
+
/** Regex mode: the piece whose scan stopped at the end of a time slice, and the next line of it to look at. */
|
|
269
|
+
unfinished;
|
|
270
|
+
/** Regex mode: the line that took a whole slice without being finished. A second such slice ends the search. */
|
|
271
|
+
stuck;
|
|
272
|
+
constructor(query, settings, lineCount) {
|
|
273
|
+
this.settings = settings;
|
|
274
|
+
this.lineCount = lineCount;
|
|
275
|
+
if (!query)
|
|
276
|
+
throw new Error("The search query is empty.");
|
|
277
|
+
if (settings.regex) {
|
|
278
|
+
const problem = unsafeRegexReason(query);
|
|
279
|
+
if (problem)
|
|
280
|
+
throw new Error(problem);
|
|
281
|
+
this.pattern = compileRegex(query, settings.caseSensitive ? "" : "i");
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
this.needle = settings.caseSensitive ? query : foldCase(query);
|
|
285
|
+
this.newlines = newlinesIn(this.needle);
|
|
286
|
+
}
|
|
287
|
+
this.timeLeft = settings.timeLimitMs ?? REGEX_TIME_LIMIT_MS;
|
|
288
|
+
this.context = Math.max(0, Math.min(5, settings.contextLines));
|
|
289
|
+
this.keep = this.context + this.newlines;
|
|
290
|
+
}
|
|
291
|
+
/** Scans a piece to its end, without a pause: for a caller that cannot wait. See `addSome`. */
|
|
292
|
+
add(chunk) {
|
|
293
|
+
while (!this.addSome(chunk)) {
|
|
294
|
+
// The next slice of a regex scan.
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Scans a piece, or goes on scanning it. False means that a regex scan reached the end of a time
|
|
299
|
+
* slice with lines of this piece still to look at: let other work run, then call this again with
|
|
300
|
+
* the same piece. Exact search always finishes the piece.
|
|
301
|
+
*/
|
|
302
|
+
addSome(chunk) {
|
|
303
|
+
if (this.done)
|
|
304
|
+
return true;
|
|
305
|
+
if (this.pattern) {
|
|
306
|
+
if (!this.scanRegex(chunk))
|
|
307
|
+
return false;
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
this.scanExact(chunk);
|
|
311
|
+
}
|
|
312
|
+
if (this.unfilled > 0) {
|
|
313
|
+
const last = chunk.firstLine + chunk.lines.lineCount - 1;
|
|
314
|
+
for (const [line, text] of this.shown) {
|
|
315
|
+
if (text !== undefined)
|
|
316
|
+
continue;
|
|
317
|
+
const found = line >= chunk.firstLine && line <= last
|
|
318
|
+
? chunk.lines.line(line - chunk.firstLine + 1)
|
|
319
|
+
: this.recent.find(([number]) => number === line)?.[1];
|
|
320
|
+
if (found !== undefined)
|
|
321
|
+
this.fill(line, found);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
this.recent = remember(this.recent, chunk, this.keep);
|
|
325
|
+
return true;
|
|
326
|
+
}
|
|
327
|
+
/** Lines to show that were not in the pieces read (the scan stopped early). Read them and `fill` them. */
|
|
328
|
+
missing() {
|
|
329
|
+
if (this.unfilled === 0)
|
|
330
|
+
return [];
|
|
331
|
+
return [...this.shown].filter(([, text]) => text === undefined).map(([line]) => line).sort((left, right) => left - right);
|
|
332
|
+
}
|
|
333
|
+
fill(line, text) {
|
|
334
|
+
if (this.shown.get(line) !== undefined || !this.shown.has(line))
|
|
335
|
+
return;
|
|
336
|
+
this.shown.set(line, text);
|
|
337
|
+
this.unfilled--;
|
|
338
|
+
}
|
|
339
|
+
result() {
|
|
340
|
+
const lineText = (line) => this.shown.get(line) ?? "";
|
|
341
|
+
const matches = this.hits.map(({ line, column, text }) => {
|
|
342
|
+
const match = { line, text: clip(text, column) };
|
|
343
|
+
if (this.context > 0) {
|
|
344
|
+
match.before = [];
|
|
345
|
+
match.after = [];
|
|
346
|
+
for (let other = Math.max(1, line - this.context); other < line; other++)
|
|
347
|
+
match.before.push(`${other}| ${clip(lineText(other), 0)}`);
|
|
348
|
+
for (let other = line + 1; other <= Math.min(this.lineCount, line + this.context); other++)
|
|
349
|
+
match.after.push(`${other}| ${clip(lineText(other), 0)}`);
|
|
182
350
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
if (line
|
|
351
|
+
return match;
|
|
352
|
+
});
|
|
353
|
+
return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches };
|
|
354
|
+
}
|
|
355
|
+
record(line, column, text) {
|
|
356
|
+
this.total++;
|
|
357
|
+
if (this.hits.length >= this.settings.maxResults)
|
|
358
|
+
return;
|
|
359
|
+
this.hits.push({ line, column, text });
|
|
360
|
+
for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
|
|
361
|
+
if (other !== line && !this.shown.has(other)) {
|
|
362
|
+
this.shown.set(other, undefined);
|
|
363
|
+
this.unfilled++;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
scanExact(chunk) {
|
|
368
|
+
const { needle } = this;
|
|
369
|
+
const caseSensitive = this.settings.caseSensitive === true;
|
|
370
|
+
let text = caseSensitive ? chunk.text : chunk.lower();
|
|
371
|
+
let lines = chunk.lines;
|
|
372
|
+
let firstLine = chunk.firstLine;
|
|
373
|
+
let start = chunk.startCharacter;
|
|
374
|
+
// A needle across lines can start in the lines before this piece.
|
|
375
|
+
const before = this.newlines > 0 ? carried(this.recent, this.newlines) : undefined;
|
|
376
|
+
if (before) {
|
|
377
|
+
text = (caseSensitive ? before.text : foldCase(before.text)) + text;
|
|
378
|
+
lines = new LineIndex(before.text + chunk.text);
|
|
379
|
+
firstLine = before.firstLine;
|
|
380
|
+
start = chunk.startCharacter - before.text.length;
|
|
381
|
+
}
|
|
382
|
+
for (let at = text.indexOf(needle, Math.max(0, this.nextAllowed - start)); at !== -1; at = text.indexOf(needle, at + needle.length)) {
|
|
383
|
+
this.nextAllowed = start + at + needle.length;
|
|
384
|
+
const local = lines.lineAt(at);
|
|
385
|
+
const line = firstLine + local - 1;
|
|
386
|
+
if (line === this.lastLine)
|
|
194
387
|
continue;
|
|
195
|
-
lastLine = line;
|
|
196
|
-
record(line, at - lines.startOf(line));
|
|
197
|
-
if (total >=
|
|
198
|
-
stoppedEarly = true;
|
|
199
|
-
|
|
388
|
+
this.lastLine = line;
|
|
389
|
+
this.record(line, at - lines.startOf(local), lines.line(local));
|
|
390
|
+
if (this.total >= MAX_EXACT_MATCHES) {
|
|
391
|
+
this.stoppedEarly = true;
|
|
392
|
+
this.done = true;
|
|
393
|
+
return;
|
|
200
394
|
}
|
|
201
395
|
}
|
|
202
396
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
397
|
+
/**
|
|
398
|
+
* One time slice of a regex scan of a piece. True when the piece is finished, or the search is
|
|
399
|
+
* (out of time, or stopped at a line the pattern cannot get past); false when lines of the piece
|
|
400
|
+
* are left for the next slice.
|
|
401
|
+
*/
|
|
402
|
+
scanRegex(chunk) {
|
|
403
|
+
const stop = () => {
|
|
404
|
+
this.stoppedEarly = true;
|
|
405
|
+
this.done = true;
|
|
406
|
+
return true;
|
|
407
|
+
};
|
|
408
|
+
// Where to go on: in a piece that was left at the end of a slice, or at the start of a new one.
|
|
409
|
+
let next = this.unfinished?.chunk === chunk ? this.unfinished.next : 1;
|
|
410
|
+
this.unfinished = undefined;
|
|
411
|
+
if (this.timeLeft <= 0)
|
|
412
|
+
return stop();
|
|
413
|
+
const pattern = this.pattern;
|
|
414
|
+
const { lines, firstLine } = chunk;
|
|
415
|
+
const from = next;
|
|
416
|
+
const slice = Math.min(this.timeLeft, REGEX_SLICE_MS);
|
|
417
|
+
const started = performance.now();
|
|
418
|
+
const finished = withinTimeLimit(() => {
|
|
419
|
+
for (; next <= lines.lineCount; next++) {
|
|
420
|
+
const line = firstLine + next - 1;
|
|
421
|
+
const text = lines.line(next);
|
|
422
|
+
const match = pattern.exec(text);
|
|
423
|
+
// A line is recorded once, also when a slice ended while it was being recorded and it is looked at again.
|
|
424
|
+
if (match && line > this.lastLine) {
|
|
425
|
+
this.lastLine = line;
|
|
426
|
+
this.record(line, match.index, text);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}, slice);
|
|
430
|
+
const spent = performance.now() - started;
|
|
431
|
+
this.timeLeft -= spent;
|
|
432
|
+
if (this.settings.regexClock)
|
|
433
|
+
this.settings.regexClock.usedMs += spent;
|
|
434
|
+
if (finished)
|
|
435
|
+
return true;
|
|
436
|
+
if (this.timeLeft <= 0)
|
|
437
|
+
return stop();
|
|
438
|
+
// The slice ended in the middle of line `next`. A whole slice without one line finished can be
|
|
439
|
+
// a stall of the machine, once. Twice on the same line, it is the pattern.
|
|
440
|
+
if (next === from && slice >= REGEX_SLICE_MS) {
|
|
441
|
+
const line = firstLine + next - 1;
|
|
442
|
+
if (this.stuck === line)
|
|
443
|
+
return stop();
|
|
444
|
+
this.stuck = line;
|
|
213
445
|
}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
446
|
+
this.unfinished = { chunk, next };
|
|
447
|
+
return false;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
/** Reads the given lines (sorted) from a document, a run of neighbouring lines at a time. */
|
|
451
|
+
async function readSome(source, lines, use) {
|
|
452
|
+
for (let at = 0; at < lines.length;) {
|
|
453
|
+
let end = at;
|
|
454
|
+
while (end + 1 < lines.length && lines[end + 1] <= lines[end] + 1)
|
|
455
|
+
end++;
|
|
456
|
+
const texts = await source.readLines(lines[at], lines[end]);
|
|
457
|
+
texts.forEach((text, index) => use(lines[at] + index, text));
|
|
458
|
+
at = end + 1;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
/** Lines that contain `query` (exact text) or match it (regex), in a document held in memory. */
|
|
462
|
+
export function grep(document, query, options) {
|
|
463
|
+
const search = new LineSearch(query, options, document.lines.lineCount);
|
|
464
|
+
search.add(document.wholeChunk());
|
|
465
|
+
for (const line of search.missing())
|
|
466
|
+
search.fill(line, document.lines.line(line));
|
|
467
|
+
return search.result();
|
|
468
|
+
}
|
|
469
|
+
/** `grep` over any document: one held in memory, or one read from the store a piece at a time. */
|
|
470
|
+
export async function grepSource(source, query, options) {
|
|
471
|
+
const search = new LineSearch(query, options, source.lineCount);
|
|
472
|
+
if (source instanceof SearchableDocument) {
|
|
473
|
+
const chunk = source.wholeChunk();
|
|
474
|
+
// A regex scan runs a slice at a time, and other work gets a turn between two slices.
|
|
475
|
+
while (!search.addSome(chunk)) {
|
|
476
|
+
await pause();
|
|
477
|
+
options.signal?.throwIfAborted();
|
|
478
|
+
}
|
|
479
|
+
for (const line of search.missing())
|
|
480
|
+
search.fill(line, source.lines.line(line));
|
|
481
|
+
return search.result();
|
|
482
|
+
}
|
|
483
|
+
await scanSource(source, (chunk) => (search.addSome(chunk) ? search.done : "again"), options.signal);
|
|
484
|
+
const missing = search.missing();
|
|
485
|
+
if (missing.length)
|
|
486
|
+
await readSome(source, missing, (line, text) => search.fill(line, text));
|
|
487
|
+
return search.result();
|
|
217
488
|
}
|
|
218
489
|
export function queryTerms(query) {
|
|
219
490
|
const terms = foldCase(query).split(/[^\p{L}\p{N}_]+/u).filter((term) => term.length >= 2 && !STOPWORDS.has(term));
|
|
220
491
|
return [...new Set(terms)].slice(0, 12);
|
|
221
492
|
}
|
|
222
493
|
/**
|
|
223
|
-
* BM25 over fixed passages, computed at query time from substring hits
|
|
224
|
-
*
|
|
494
|
+
* BM25 over fixed passages, computed at query time from substring hits, over a document fed a
|
|
495
|
+
* piece at a time (pieces start at passage starts). No index to build or store, works for any
|
|
496
|
+
* language, and a term also matches longer words ("timeout" → "timeouts").
|
|
225
497
|
*/
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
498
|
+
class PassageRank {
|
|
499
|
+
source;
|
|
500
|
+
terms;
|
|
501
|
+
/** Passage lengths in characters, for the passages that have a hit. */
|
|
502
|
+
lengths = new Map();
|
|
503
|
+
phrase;
|
|
504
|
+
recent = [];
|
|
505
|
+
constructor(query, source) {
|
|
506
|
+
this.source = source;
|
|
507
|
+
this.terms = queryTerms(query).map((term) => ({ term, seen: 0, frequency: new Map() }));
|
|
508
|
+
// Passages that contain the whole phrase rank above passages with scattered terms.
|
|
509
|
+
const phrase = foldCase(query.trim());
|
|
510
|
+
if (this.terms.length > 1 && phrase.length <= 200)
|
|
511
|
+
this.phrase = { needle: phrase, newlines: newlinesIn(phrase), passages: new Set(), nextAllowed: 0 };
|
|
512
|
+
}
|
|
513
|
+
get empty() {
|
|
514
|
+
return this.terms.length === 0;
|
|
515
|
+
}
|
|
516
|
+
add(chunk) {
|
|
517
|
+
if (this.empty)
|
|
518
|
+
return;
|
|
519
|
+
const haystack = chunk.lower();
|
|
520
|
+
for (const entry of this.terms) {
|
|
521
|
+
const { term } = entry;
|
|
522
|
+
for (let at = haystack.indexOf(term); at !== -1 && entry.seen < MAX_OCCURRENCES_PER_TERM; at = haystack.indexOf(term, at + term.length)) {
|
|
523
|
+
entry.seen++;
|
|
524
|
+
const passage = this.passageOf(chunk.firstLine + chunk.lines.lineAt(at) - 1);
|
|
525
|
+
entry.frequency.set(passage, (entry.frequency.get(passage) ?? 0) + 1);
|
|
526
|
+
if (!this.lengths.has(passage))
|
|
527
|
+
this.lengths.set(passage, this.lengthOf(passage, chunk));
|
|
528
|
+
}
|
|
241
529
|
}
|
|
242
|
-
const
|
|
243
|
-
if (
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
const
|
|
249
|
-
|
|
250
|
-
|
|
530
|
+
const phrase = this.phrase;
|
|
531
|
+
if (phrase && phrase.passages.size < MAX_PHRASE_PASSAGES) {
|
|
532
|
+
let text = haystack;
|
|
533
|
+
let lines = chunk.lines;
|
|
534
|
+
let firstLine = chunk.firstLine;
|
|
535
|
+
let start = chunk.startCharacter;
|
|
536
|
+
const before = phrase.newlines > 0 ? carried(this.recent, phrase.newlines) : undefined;
|
|
537
|
+
if (before) {
|
|
538
|
+
text = foldCase(before.text) + haystack;
|
|
539
|
+
lines = new LineIndex(before.text + chunk.text);
|
|
540
|
+
firstLine = before.firstLine;
|
|
541
|
+
start = chunk.startCharacter - before.text.length;
|
|
542
|
+
}
|
|
543
|
+
for (let at = text.indexOf(phrase.needle, Math.max(0, phrase.nextAllowed - start)); at !== -1 && phrase.passages.size < MAX_PHRASE_PASSAGES; at = text.indexOf(phrase.needle, at + phrase.needle.length)) {
|
|
544
|
+
phrase.nextAllowed = start + at + phrase.needle.length;
|
|
545
|
+
phrase.passages.add(this.passageOf(firstLine + lines.lineAt(at) - 1));
|
|
546
|
+
}
|
|
547
|
+
this.recent = remember(this.recent, chunk, phrase.newlines);
|
|
251
548
|
}
|
|
252
549
|
}
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
const
|
|
257
|
-
|
|
258
|
-
|
|
550
|
+
result(topK) {
|
|
551
|
+
if (this.empty)
|
|
552
|
+
return [];
|
|
553
|
+
const passageCount = this.source.passageStarts.length;
|
|
554
|
+
const averageLength = Math.max(1, this.source.characters / passageCount);
|
|
555
|
+
const scores = new Map();
|
|
556
|
+
for (const { frequency } of this.terms) {
|
|
557
|
+
const df = frequency.size;
|
|
558
|
+
if (df === 0)
|
|
559
|
+
continue;
|
|
560
|
+
const idf = Math.log(1 + (passageCount - df + 0.5) / (df + 0.5));
|
|
561
|
+
for (const [passage, tf] of frequency) {
|
|
562
|
+
const length = this.lengths.get(passage);
|
|
563
|
+
const score = idf * (tf * 2.2) / (tf + 1.2 * (0.25 + 0.75 * (length / averageLength)));
|
|
564
|
+
scores.set(passage, (scores.get(passage) ?? 0) + score);
|
|
565
|
+
}
|
|
259
566
|
}
|
|
260
|
-
|
|
261
|
-
|
|
567
|
+
if (this.phrase)
|
|
568
|
+
for (const passage of this.phrase.passages)
|
|
569
|
+
scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
|
|
570
|
+
return [...scores.entries()]
|
|
571
|
+
.sort((left, right) => right[1] - left[1])
|
|
572
|
+
.slice(0, topK)
|
|
573
|
+
.map(([passage, score]) => ({ ...this.range(passage), score: Math.round(score * 100) / 100 }));
|
|
574
|
+
}
|
|
575
|
+
passageOf(line) {
|
|
576
|
+
return positionOf(this.source.passageStarts, line) - 1;
|
|
577
|
+
}
|
|
578
|
+
range(passage) {
|
|
579
|
+
const starts = this.source.passageStarts;
|
|
580
|
+
return { from: starts[passage], to: (passage + 1 < starts.length ? starts[passage + 1] : this.source.lineCount + 1) - 1 };
|
|
262
581
|
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
.
|
|
266
|
-
|
|
582
|
+
lengthOf(passage, chunk) {
|
|
583
|
+
const { from, to } = this.range(passage);
|
|
584
|
+
const first = from - chunk.firstLine + 1;
|
|
585
|
+
const last = to - chunk.firstLine + 1;
|
|
586
|
+
if (first < 1 || last > chunk.lines.lineCount)
|
|
587
|
+
throw new Error("A piece of the text does not hold whole passages.");
|
|
588
|
+
return chunk.lines.endOf(last) - chunk.lines.startOf(first) + 1;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
/** BM25 passage ranking over a document held in memory. */
|
|
592
|
+
export function rankPassages(document, query, topK) {
|
|
593
|
+
const rank = new PassageRank(query, document);
|
|
594
|
+
rank.add(document.wholeChunk());
|
|
595
|
+
return rank.result(topK);
|
|
596
|
+
}
|
|
597
|
+
/** `rankPassages` over any document: one held in memory, or one read from the store a piece at a time. */
|
|
598
|
+
export async function rankSource(source, query, topK, signal) {
|
|
599
|
+
if (source instanceof SearchableDocument)
|
|
600
|
+
return rankPassages(source, query, topK);
|
|
601
|
+
const rank = new PassageRank(query, source);
|
|
602
|
+
if (rank.empty)
|
|
603
|
+
return [];
|
|
604
|
+
await scanSource(source, (chunk) => {
|
|
605
|
+
rank.add(chunk);
|
|
606
|
+
}, signal);
|
|
607
|
+
return rank.result(topK);
|
|
267
608
|
}
|
|
268
609
|
//# sourceMappingURL=search.js.map
|