llm-large-files 0.5.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
package/dist/search.js CHANGED
@@ -1,25 +1,44 @@
1
1
  import { createContext, Script } from "node:vm";
2
+ import { GroupCounter } from "./groups.js";
3
+ import { pause } from "./pause.js";
2
4
  import { PASSAGE_CHARACTERS, PASSAGE_MAX_LINES, positionOf } from "./text-index.js";
3
- import { foldCase, LineIndex } from "./text.js";
5
+ import { composed, foldCase, LineIndex, sliceWhole } from "./text.js";
4
6
  const MAX_OCCURRENCES_PER_TERM = 200_000;
5
7
  const MAX_EXACT_MATCHES = 1_000_000;
6
8
  const MAX_PHRASE_PASSAGES = 10_000;
7
9
  /** The most time one regex search may spend matching. */
8
10
  export const REGEX_TIME_LIMIT_MS = 3_000;
11
+ /**
12
+ * The most time one exact search with `wholeWord` or `groupBy` may spend. Exact search takes time in
13
+ * proportion to the text, but of a file of 100 MB, a whole-word search for "a" inside long words
14
+ * took 17 seconds, and a count of a million lines by message shape 10: it stops, as a regex search
15
+ * does. A plain exact search has no such limit: it pauses, and its count stays whole.
16
+ */
17
+ const EXACT_TIME_LIMIT_MS = 3_000;
9
18
  /**
10
19
  * A regex scan runs in slices of this length, and other work gets a turn between two slices. A
11
20
  * line that takes two whole slices is a pattern that backtracks without end on it: the search
12
21
  * stops there, long before its time limit.
13
22
  */
14
23
  const REGEX_SLICE_MS = 250;
24
+ /**
25
+ * A regex scan records the lines it found after this many, within its time slice (see `scanRegex`).
26
+ * Each batch is one run of the time limit, which costs about 0.3 ms to set up.
27
+ */
28
+ const REGEX_BATCH = 1 << 16;
29
+ /** An exact scan of a piece lets other work run after this much time, and goes on after. */
30
+ const EXACT_SLICE_MS = 15;
31
+ /** A scan of a document held in memory lets other work run between two pieces after this much time, as a scan of a document read by range does. */
32
+ const YIELD_AFTER_MS = 15;
33
+ /** About this many characters of a document held in memory are scanned as one piece. */
34
+ const PIECE_CHARACTERS = 1 << 20;
15
35
  const SHOWN_LINE_CHARACTERS = 400;
16
36
  const STOPWORDS = new Set([
17
37
  "the", "and", "for", "are", "was", "with", "that", "this", "what", "how", "why", "when", "where", "who",
18
38
  "from", "into", "about", "does", "did", "have", "has", "had", "you", "your", "can", "all", "any", "not",
19
39
  "של", "את", "על", "עם", "מה", "איך", "למה", "מתי", "איפה", "מי", "זה", "זאת", "גם", "או", "אם", "כל", "יש", "אין",
20
40
  ]);
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));
41
+ export { pause };
23
42
  /** Feeds a document's text, a piece at a time, to `feed` until it returns true or the text ends. */
24
43
  export async function scanSource(source, feed, signal) {
25
44
  if (source.scan)
@@ -53,9 +72,14 @@ export class SearchableDocument {
53
72
  meta;
54
73
  text;
55
74
  lines;
56
- lowerText;
57
75
  passageStartList;
58
76
  pageStarts;
77
+ /** The first and the last line of each piece a search scans (see `pieces`). */
78
+ pieceLines;
79
+ /** Each piece lowercased with `foldCase`, once a search has needed it. */
80
+ lowerPieces = [];
81
+ /** Each piece's text and line table, made once: a search of a document of short lines rebuilt every table. */
82
+ madePieces = [];
59
83
  constructor(document) {
60
84
  this.meta = document.meta;
61
85
  this.text = document.text;
@@ -68,17 +92,13 @@ export class SearchableDocument {
68
92
  return this.text.length;
69
93
  }
70
94
  /**
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.
95
+ * Memory this document takes once it has been searched: the text, its lowercased copy (a piece
96
+ * at a time), and the line index with each piece's copy of it. A text of ASCII only is held at
97
+ * one byte a character, any other at two.
73
98
  */
74
99
  get memoryBytes() {
75
100
  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
- }
78
- /** The text lowercased for case-insensitive search. Same length as `text`, so offsets match. */
79
- get lower() {
80
- this.lowerText ??= foldCase(this.text);
81
- return this.lowerText;
101
+ return this.text.length * (ascii ? 1 : 2) * 2 + this.lines.lineCount * 8 + 1_024;
82
102
  }
83
103
  /** First line of each passage: groups of lines up to about 1,500 characters. */
84
104
  get passages() {
@@ -102,13 +122,6 @@ export class SearchableDocument {
102
122
  get passageStarts() {
103
123
  return this.passages;
104
124
  }
105
- passageRange(index) {
106
- const starts = this.passages;
107
- return { from: starts[index], to: (starts[index + 1] ?? this.lines.lineCount + 1) - 1 };
108
- }
109
- passageOfLine(line) {
110
- return positionOf(this.passages, line) - 1;
111
- }
112
125
  /**
113
126
  * The page a line is on, from the "--- Page N ---" lines the PDF extractor writes. Undefined for
114
127
  * a text without them, and for lines above the first one. Only markers that count up from 1 are
@@ -131,12 +144,70 @@ export class SearchableDocument {
131
144
  async readText() {
132
145
  return this.text;
133
146
  }
134
- /** The whole text as one piece. */
147
+ /**
148
+ * The whole text as one piece, for a caller that reads every line of it. Its lowercased copy is
149
+ * not kept: searches lowercase the text a piece at a time (see `pieces`).
150
+ */
135
151
  wholeChunk() {
136
- return { firstLine: 1, startCharacter: 0, text: this.text, lines: this.lines, lower: () => this.lower };
152
+ return { firstLine: 1, startCharacter: 0, text: this.text, lines: this.lines, lower: () => foldCase(this.text) };
153
+ }
154
+ /**
155
+ * The text in pieces of whole passages, about 1M characters each (one passage at least), as a
156
+ * document read by range is scanned. A search scans them one at a time, and other work runs
157
+ * between them (see `scan`): a search of 100 MB held as one piece kept the server from all
158
+ * other work for up to 17 seconds. Each piece is lowercased the first time a search needs it.
159
+ */
160
+ *pieces() {
161
+ const ranges = this.pieceRanges();
162
+ for (let index = 0; index < ranges.length; index++) {
163
+ const [firstLine, lastLine] = ranges[index];
164
+ const { text, lines } = (this.madePieces[index] ??= this.lines.piece(firstLine, lastLine));
165
+ yield { firstLine, startCharacter: this.lines.startOf(firstLine), text, lines, lower: () => (this.lowerPieces[index] ??= foldCase(text)) };
166
+ }
137
167
  }
138
168
  async *chunks() {
139
- yield this.wholeChunk();
169
+ yield* this.pieces();
170
+ }
171
+ /**
172
+ * Feeds the pieces in order to `feed` until it returns true or the text ends, and lets other
173
+ * work run between two pieces every 15 ms or so, and whenever `feed` asks for a piece again.
174
+ */
175
+ async scan(feed, signal) {
176
+ let slice = performance.now();
177
+ for (const chunk of this.pieces()) {
178
+ signal?.throwIfAborted();
179
+ let more = feed(chunk);
180
+ // A scan that asks for the same piece again has stopped part-way to let other work run.
181
+ while (more === "again") {
182
+ await pause();
183
+ signal?.throwIfAborted();
184
+ slice = performance.now();
185
+ more = feed(chunk);
186
+ }
187
+ if (more === true)
188
+ return;
189
+ if (performance.now() - slice > YIELD_AFTER_MS) {
190
+ await pause();
191
+ slice = performance.now();
192
+ }
193
+ }
194
+ }
195
+ /** The first and the last line of each piece of `pieces`: whole passages, about `PIECE_CHARACTERS` each. */
196
+ pieceRanges() {
197
+ if (!this.pieceLines) {
198
+ const starts = this.passages;
199
+ const ranges = [];
200
+ for (let passage = 0; passage < starts.length;) {
201
+ const start = this.lines.startOf(starts[passage]);
202
+ let next = passage + 1;
203
+ while (next < starts.length && this.lines.startOf(starts[next]) - start < PIECE_CHARACTERS)
204
+ next++;
205
+ ranges.push([starts[passage], next < starts.length ? starts[next] - 1 : this.lines.lineCount]);
206
+ passage = next;
207
+ }
208
+ this.pieceLines = ranges;
209
+ }
210
+ return this.pieceLines;
140
211
  }
141
212
  pageLines() {
142
213
  if (!this.pageStarts) {
@@ -157,8 +228,13 @@ export class SearchableDocument {
157
228
  function clip(line, column) {
158
229
  if (line.length <= SHOWN_LINE_CHARACTERS)
159
230
  return line;
160
- const start = Math.max(0, Math.min(column - SHOWN_LINE_CHARACTERS / 2, line.length - SHOWN_LINE_CHARACTERS));
161
- return `${start > 0 ? "…" : ""}${line.slice(start, start + SHOWN_LINE_CHARACTERS)}${start + SHOWN_LINE_CHARACTERS < line.length ? "…" : ""}`;
231
+ let start = Math.max(0, Math.min(column - SHOWN_LINE_CHARACTERS / 2, line.length - SHOWN_LINE_CHARACTERS));
232
+ // Never inside a character outside the basic plane (an emoji): half of one is refused by Claude's API.
233
+ const code = line.charCodeAt(start);
234
+ if (start > 0 && code >= 0xdc00 && code <= 0xdfff)
235
+ start++;
236
+ const end = start + SHOWN_LINE_CHARACTERS;
237
+ return `${start > 0 ? "…" : ""}${sliceWhole(line, end).slice(start)}${end < line.length ? "…" : ""}`;
162
238
  }
163
239
  const RUN_SCAN = new Script("scan()");
164
240
  let scanSandbox;
@@ -187,15 +263,70 @@ function withinTimeLimit(scan, milliseconds) {
187
263
  scanSandbox.scan = () => undefined;
188
264
  }
189
265
  }
266
+ /** A group that holds a quantifier and is repeated itself: `(a+)+`, `(\d{1,3}\.){3}`. Group 1 is its body. */
267
+ const NESTED_QUANTIFIER = /\(((?:[^()\\]|\\.)*[+*}](?:[^()\\]|\\.)*)\)\s*[+*{]/g;
268
+ /** An atom of a pattern, as `regexAtoms` splits it: an escape, a class, or one character. */
269
+ const REGEX_ATOM = /\\[pPu]\{[^}]*\}|\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}|\\.|\[(?:[^\]\\]|\\.)*\]|\{\d*,?\d*\}|[\s\S]/gu;
270
+ /** Escapes that stand for many characters, not for one. */
271
+ const CLASS_ESCAPE = /^\\[dDwWsSbBpP]/;
272
+ const QUANTIFIER = /^(?:[+*?]|\{\d*,?\d*\})$/;
273
+ /**
274
+ * Whether a repeated group cannot backtrack without end: its body ends in a literal character that
275
+ * none of the quantified atoms before it can match, and has no alternation. Each repeat then ends at
276
+ * the next such character, so the match takes time in proportion to the line. `(\d{1,3}\.){3}`,
277
+ * `(\w+\.)+com` and `(\d+-)+\d+` pass; `(a+)+`, `(\w+\s?)+`, `(.+x)+` and `(\d+\d)+` do not.
278
+ */
279
+ function separatedRepeat(body) {
280
+ const atoms = body.match(REGEX_ATOM) ?? [];
281
+ if (atoms.includes("|"))
282
+ return false;
283
+ const last = atoms.at(-1);
284
+ if (last === undefined)
285
+ return false;
286
+ // The separator: one character, written plainly or escaped, not a class, a dot or a quantifier.
287
+ let separator;
288
+ if (last.startsWith("\\")) {
289
+ if (last.length !== 2 || CLASS_ESCAPE.test(last) || /^\\[0-9ck]$/.test(last))
290
+ return false;
291
+ separator = last[1];
292
+ }
293
+ else {
294
+ if (last.length !== 1 || ".?*+{}()[]|^$".includes(last))
295
+ return false;
296
+ separator = last;
297
+ }
298
+ for (let index = 0; index < atoms.length - 1; index++) {
299
+ const next = atoms[index + 1];
300
+ if (!QUANTIFIER.test(next) || QUANTIFIER.test(atoms[index]))
301
+ continue;
302
+ try {
303
+ if (new RegExp(`^(?:${atoms[index]})$`, "iu").test(separator))
304
+ return false;
305
+ }
306
+ catch {
307
+ return false;
308
+ }
309
+ }
310
+ return true;
311
+ }
190
312
  /**
191
313
  * A quick refusal for the most common catastrophic shape, a nested quantifier such as (a+)+.
192
- * It does not catch every slow pattern; the time limit in `grep` is what bounds the search.
314
+ * A repeated group whose repeats are separated by a literal character none of its quantified parts
315
+ * matches, as in an IPv4 address or a domain, is linear, and passes (see `separatedRepeat`). It does
316
+ * not catch every slow pattern; the time limit in `grep` is what bounds the search.
193
317
  */
194
- export function unsafeRegexReason(pattern) {
195
- if (pattern.length > 300)
318
+ export function unsafeRegexReason(given) {
319
+ if (given.length > 300)
196
320
  return "Regex is longer than 300 characters.";
197
- if (/\((?:[^()\\]|\\.)*[+*}](?:[^()\\]|\\.)*\)\s*[+*{]/.test(pattern)) {
198
- return "Regex has a nested quantifier like (a+)+, which can hang on large files. Simplify it.";
321
+ // Checked as it is compiled (`compileRegex`): composed. As typed, `(\p{L}+e` and a combining
322
+ // acute `)+$` ends in a mark that \p{L} does not match, and passed; composed, it ends in "é",
323
+ // and backtracks without end.
324
+ const pattern = composed(given);
325
+ for (const [, body] of pattern.matchAll(NESTED_QUANTIFIER)) {
326
+ // Checked with \\w and \\W as the pattern is compiled, for letters of every script: (\\w+é)+ is
327
+ // not separated, though é is not an ASCII word character.
328
+ if (!separatedRepeat(unicodeWordPattern(body, false) ?? body))
329
+ return "Regex has a nested quantifier like (a+)+, which can hang on large files. Simplify it.";
199
330
  }
200
331
  try {
201
332
  new RegExp(pattern);
@@ -205,12 +336,87 @@ export function unsafeRegexReason(pattern) {
205
336
  }
206
337
  return null;
207
338
  }
339
+ /** A letter, a mark or a digit of any script, or "_": as a class, what `\w` means inside a class of a pattern compiled here. */
340
+ const WORD_CLASS = "\\p{L}\\p{M}\\p{N}_";
341
+ /**
342
+ * Marks that belong to a symbol, not to a letter: the variation selectors (U+FE0F makes "⚠" an
343
+ * emoji, and an ideograph's variant is chosen with one from U+E0100) and the enclosing marks (the
344
+ * keycap U+20E3 of "1️⃣"). They are not word characters: "Warning" in "⚠️Warning" is a whole word.
345
+ */
346
+ const SYMBOL_MARKS = "\\uFE00-\\uFE0F\\u{E0100}-\\u{E01EF}\\p{Me}";
347
+ /** A word character, with the `u` flag: a letter, a mark or a digit of any script, or "_", but not a mark of `SYMBOL_MARKS`. What `\w` means outside a class. */
348
+ const WORD_PATTERN = `(?:(?![${SYMBOL_MARKS}])[${WORD_CLASS}])`;
349
+ /** A character that is not one of `WORD_PATTERN`: what `\W` means. */
350
+ const NOT_WORD_PATTERN = `(?:[${SYMBOL_MARKS}]|[^${WORD_CLASS}])`;
351
+ /**
352
+ * The pattern with `\w`, `\W`, `\b` and `\B` meaning letters of every script, not only ASCII:
353
+ * in JavaScript, `\bחוזה\b` matches nothing and `\w+` stops at "é". Undefined when the pattern
354
+ * cannot be rewritten that way (`\W` inside a class): it is then compiled as it is. Inside a class,
355
+ * `\w` keeps every mark: a class cannot leave some out.
356
+ *
357
+ * `exact` false is for `unsafeRegexReason`, which splits a pattern into atoms: `\w` and `\W` are
358
+ * each one class there, of what they may match and more, and `\b` and `\B` are left as they are.
359
+ */
360
+ export function unicodeWordPattern(pattern, exact = true) {
361
+ let out = "";
362
+ let inClass = false;
363
+ for (let at = 0; at < pattern.length; at++) {
364
+ const character = pattern[at];
365
+ if (character === "\\") {
366
+ const next = pattern[at + 1];
367
+ if (next === undefined)
368
+ return undefined;
369
+ at++;
370
+ if (inClass) {
371
+ if (next === "w")
372
+ out += WORD_CLASS;
373
+ else if (next === "W")
374
+ return undefined;
375
+ else
376
+ out += `\\${next}`;
377
+ }
378
+ else if (next === "w") {
379
+ out += exact ? WORD_PATTERN : `[${WORD_CLASS}]`;
380
+ }
381
+ else if (next === "W") {
382
+ out += exact ? NOT_WORD_PATTERN : "[^\\p{L}\\p{N}_]";
383
+ }
384
+ else if (next === "b" && exact) {
385
+ out += `(?:(?<=${WORD_PATTERN})(?!${WORD_PATTERN})|(?<!${WORD_PATTERN})(?=${WORD_PATTERN}))`;
386
+ }
387
+ else if (next === "B" && exact) {
388
+ out += `(?:(?<=${WORD_PATTERN})(?=${WORD_PATTERN})|(?<!${WORD_PATTERN})(?!${WORD_PATTERN}))`;
389
+ }
390
+ else {
391
+ out += `\\${next}`;
392
+ }
393
+ continue;
394
+ }
395
+ if (character === "[" && !inClass)
396
+ inClass = true;
397
+ else if (character === "]" && inClass)
398
+ inClass = false;
399
+ out += character;
400
+ }
401
+ return out;
402
+ }
208
403
  /**
209
404
  * 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-.]`, `\-`).
405
+ * `\p{L}` means a letter, a character outside the basic plane is one character, and `\w` and `\b`
406
+ * know the letters of every script (see `unicodeWordPattern`); without it for a pattern that is
407
+ * only valid the old way (`[\w-.]`, `\-`). The pattern is composed (NFC) first, as the text is.
212
408
  */
213
- function compileRegex(pattern, flags) {
409
+ function compileRegex(given, flags) {
410
+ const pattern = composed(given);
411
+ const unicode = unicodeWordPattern(pattern);
412
+ if (unicode !== undefined) {
413
+ try {
414
+ return new RegExp(unicode, `${flags}u`);
415
+ }
416
+ catch {
417
+ // Below: as it is.
418
+ }
419
+ }
214
420
  try {
215
421
  return new RegExp(pattern, `${flags}u`);
216
422
  }
@@ -218,6 +424,27 @@ function compileRegex(pattern, flags) {
218
424
  return new RegExp(pattern, flags);
219
425
  }
220
426
  }
427
+ /** A letter, mark, digit or "_" of any script, but not a mark of a symbol: what a whole word is made of (see `WORD_PATTERN`). */
428
+ const WORD_CHARACTER = new RegExp(`^${WORD_PATTERN}`, "u");
429
+ /**
430
+ * A word character but "_", for the pattern a whole-word search finds its candidates with in the
431
+ * lowercased text, where "_" is "_": a candidate next to "_" is checked as written (`scanExact`).
432
+ */
433
+ const WORD_BUT_LOW_LINE = `(?:(?![${SYMBOL_MARKS}])[\\p{L}\\p{M}\\p{N}])`;
434
+ /** Whether the character that ends just before `at` is a word character. */
435
+ function wordBefore(text, at) {
436
+ if (at <= 0)
437
+ return false;
438
+ const low = text.charCodeAt(at - 1);
439
+ const from = low >= 0xdc00 && low <= 0xdfff && at >= 2 ? at - 2 : at - 1;
440
+ return WORD_CHARACTER.test(text.slice(from, at));
441
+ }
442
+ /** Whether the character that starts at `at` is a word character. */
443
+ function wordAt(text, at) {
444
+ if (at >= text.length)
445
+ return false;
446
+ return WORD_CHARACTER.test(String.fromCodePoint(text.codePointAt(at)));
447
+ }
221
448
  const newlinesIn = (text) => text.split("\n").length - 1;
222
449
  /**
223
450
  * The text of the `keep` lines before a piece, with their line breaks, and the number of its
@@ -248,6 +475,14 @@ class LineSearch {
248
475
  settings;
249
476
  lineCount;
250
477
  hits = [];
478
+ /** The latest matching line past the first `maxResults`: the last one of the document, once the scan is over. */
479
+ last;
480
+ /** The lines around `last`, by number, kept from the pieces as they are read: they need not be read again. */
481
+ aroundLast = new Map();
482
+ /** The line of the match whose lines `aroundLast` holds. */
483
+ aroundLine = 0;
484
+ /** True once the lines around `last` are among the lines to show. */
485
+ lastShown = false;
251
486
  total = 0;
252
487
  stoppedEarly = false;
253
488
  /** True once nothing more is to be found or counted: the rest of the text need not be read. */
@@ -269,6 +504,24 @@ class LineSearch {
269
504
  unfinished;
270
505
  /** Regex mode: the line that took a whole slice without being finished. A second such slice ends the search. */
271
506
  stuck;
507
+ /** Regex mode: the lines of a piece found in a slice, before they are recorded, by line of the piece; their columns, and their groups with `groupBy`. */
508
+ batch;
509
+ /** Exact mode: the scan of the piece that stopped at the end of a time slice. */
510
+ exactLeft;
511
+ /** The lines looked at: matches outside them are neither counted nor shown. */
512
+ fromLine;
513
+ toLine;
514
+ /** `order: "last"`: the matches are the last ones, and this is the first. */
515
+ lastOnes;
516
+ firstHit;
517
+ /** `order: "last"`: whether the lines around the matches kept have been put among the lines to show. */
518
+ lastOnesShown = false;
519
+ groups;
520
+ /** Exact mode, `wholeWord`: whether the needle starts and ends with a word character, where a word must start and end. */
521
+ wordStart = false;
522
+ wordEnd = false;
523
+ /** Exact mode, `wholeWord`: the needle where no word character but "_" touches it, a pattern that finds the candidates (see `find`). */
524
+ wholeWords;
272
525
  constructor(query, settings, lineCount) {
273
526
  this.settings = settings;
274
527
  this.lineCount = lineCount;
@@ -281,34 +534,66 @@ class LineSearch {
281
534
  this.pattern = compileRegex(query, settings.caseSensitive ? "" : "i");
282
535
  }
283
536
  else {
284
- this.needle = settings.caseSensitive ? query : foldCase(query);
537
+ // Composed, as the text is at ingest (`composed`): "café" typed either way finds both.
538
+ const needle = composed(query);
539
+ this.needle = settings.caseSensitive ? needle : foldCase(needle);
285
540
  this.newlines = newlinesIn(this.needle);
541
+ if (settings.wholeWord) {
542
+ // As written, as the text is checked (`scanExact`): lowercased, "_" is "_", a word character.
543
+ this.wordStart = wordAt(needle, 0);
544
+ this.wordEnd = wordBefore(needle, needle.length);
545
+ const pattern = this.needle.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&");
546
+ if (this.wordStart || this.wordEnd)
547
+ this.wholeWords = new RegExp(`${this.wordStart ? `(?<!${WORD_BUT_LOW_LINE})` : ""}${pattern}${this.wordEnd ? `(?!${WORD_BUT_LOW_LINE})` : ""}`, "gu");
548
+ }
549
+ }
550
+ // A plain exact search runs to the end, in slices with pauses: its time follows the text, and its
551
+ // count must be whole. Only the work that grows with each occurrence (a whole-word check, a group
552
+ // key) has a limit, as a regex search does.
553
+ this.timeLeft = settings.timeLimitMs ?? (settings.regex ? REGEX_TIME_LIMIT_MS : settings.wholeWord || settings.groupBy ? EXACT_TIME_LIMIT_MS : Number.POSITIVE_INFINITY);
554
+ this.lastOnes = settings.order === "last";
555
+ if (settings.groupBy) {
556
+ if (settings.groupBy === "capture" && !settings.regex)
557
+ throw new Error("group_by \"capture\" counts by the first group of a regex: use mode \"regex\" with a group, as in PAY-(\\d+).");
558
+ this.groups = new GroupCounter(settings.groupBy);
286
559
  }
287
- this.timeLeft = settings.timeLimitMs ?? REGEX_TIME_LIMIT_MS;
288
- this.context = Math.max(0, Math.min(5, settings.contextLines));
560
+ // Lines around matches are not shown when no match is.
561
+ this.context = this.groups ? 0 : Math.max(0, Math.min(5, settings.contextLines));
289
562
  this.keep = this.context + this.newlines;
563
+ this.fromLine = Math.max(1, Math.trunc(settings.fromLine ?? 1));
564
+ this.toLine = Math.min(lineCount, Math.trunc(settings.toLine ?? lineCount));
565
+ if (this.toLine < this.fromLine)
566
+ this.done = true;
290
567
  }
291
568
  /** Scans a piece to its end, without a pause: for a caller that cannot wait. See `addSome`. */
292
569
  add(chunk) {
293
570
  while (!this.addSome(chunk)) {
294
- // The next slice of a regex scan.
571
+ // The next slice of the scan.
295
572
  }
296
573
  }
297
574
  /**
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.
575
+ * Scans a piece, or goes on scanning it. False means that the scan reached the end of a time
576
+ * slice with text of this piece still to look at: let other work run, then call this again with
577
+ * the same piece.
301
578
  */
302
579
  addSome(chunk) {
303
580
  if (this.done)
304
581
  return true;
305
- if (this.pattern) {
306
- if (!this.scanRegex(chunk))
307
- return false;
582
+ const chunkEnd = chunk.firstLine + chunk.lines.lineCount - 1;
583
+ // A needle across lines that starts on `toLine` ends in the piece after it, when `toLine` is the
584
+ // last line of a piece: that piece is scanned for it, with the lines carried before it.
585
+ if (chunk.firstLine - this.newlines > this.toLine) {
586
+ this.done = true;
587
+ return true;
308
588
  }
309
- else {
310
- this.scanExact(chunk);
589
+ // A piece that ends before the lines searched is not scanned; its last lines are still kept,
590
+ // for lines shown before a match and for a needle across lines.
591
+ if (chunkEnd < this.fromLine) {
592
+ this.recent = remember(this.recent, chunk, this.keep);
593
+ return true;
311
594
  }
595
+ if (!(this.pattern ? this.scanRegex(chunk) : this.scanExact(chunk)))
596
+ return false;
312
597
  if (this.unfilled > 0) {
313
598
  const last = chunk.firstLine + chunk.lines.lineCount - 1;
314
599
  for (const [line, text] of this.shown) {
@@ -321,11 +606,46 @@ class LineSearch {
321
606
  this.fill(line, found);
322
607
  }
323
608
  }
609
+ if (this.last && this.context > 0)
610
+ this.keepAroundLast(chunk);
324
611
  this.recent = remember(this.recent, chunk, this.keep);
325
612
  return true;
326
613
  }
327
- /** Lines to show that were not in the pieces read (the scan stopped early). Read them and `fill` them. */
614
+ /** Keeps the lines around `last` that are in this piece or in the lines read just before it. */
615
+ keepAroundLast(chunk) {
616
+ const { line } = this.last;
617
+ if (this.aroundLine !== line) {
618
+ this.aroundLast.clear();
619
+ this.aroundLine = line;
620
+ }
621
+ const end = chunk.firstLine + chunk.lines.lineCount - 1;
622
+ for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
623
+ if (other === line || this.aroundLast.has(other))
624
+ continue;
625
+ const found = other >= chunk.firstLine && other <= end
626
+ ? chunk.lines.line(other - chunk.firstLine + 1)
627
+ : this.recent.find(([number]) => number === other)?.[1];
628
+ if (found !== undefined)
629
+ this.aroundLast.set(other, found);
630
+ }
631
+ }
632
+ /**
633
+ * Lines to show that were not in the pieces read: those of a scan that stopped early, and those
634
+ * around the last match, which is known only once the scan is over. Read them and `fill` them.
635
+ */
328
636
  missing() {
637
+ if (this.lastOnes && !this.lastOnesShown) {
638
+ this.lastOnesShown = true;
639
+ for (const hit of this.hits)
640
+ this.showAround(hit.line);
641
+ }
642
+ if (this.last && !this.lastShown && !this.stoppedEarly) {
643
+ this.lastShown = true;
644
+ this.showAround(this.last.line);
645
+ if (this.aroundLine === this.last.line)
646
+ for (const [line, text] of this.aroundLast)
647
+ this.fill(line, text);
648
+ }
329
649
  if (this.unfilled === 0)
330
650
  return [];
331
651
  return [...this.shown].filter(([, text]) => text === undefined).map(([line]) => line).sort((left, right) => left - right);
@@ -338,7 +658,7 @@ class LineSearch {
338
658
  }
339
659
  result() {
340
660
  const lineText = (line) => this.shown.get(line) ?? "";
341
- const matches = this.hits.map(({ line, column, text }) => {
661
+ const show = ({ line, column, text }) => {
342
662
  const match = { line, text: clip(text, column) };
343
663
  if (this.context > 0) {
344
664
  match.before = [];
@@ -349,14 +669,49 @@ class LineSearch {
349
669
  match.after.push(`${other}| ${clip(lineText(other), 0)}`);
350
670
  }
351
671
  return match;
352
- });
353
- return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches };
672
+ };
673
+ if (this.groups)
674
+ return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches: [], groups: this.groups.result() };
675
+ if (this.lastOnes) {
676
+ const first = this.firstHit && this.firstHit.line < (this.hits[0]?.line ?? 0) ? { first: show(this.firstHit) } : {};
677
+ return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches: this.hits.map(show), ...first };
678
+ }
679
+ const last = this.last && !this.stoppedEarly ? { last: show(this.last) } : {};
680
+ return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches: this.hits.map(show), ...last };
354
681
  }
355
- record(line, column, text) {
682
+ /**
683
+ * A matching line. Lines outside `fromLine`-`toLine` are left out, and the first past `toLine`
684
+ * ends the search. `key`: with `groupBy`, the line's group, from `GroupCounter.keyOf`.
685
+ */
686
+ record(line, column, text, key) {
687
+ if (line < this.fromLine)
688
+ return;
689
+ if (line > this.toLine) {
690
+ this.done = true;
691
+ return;
692
+ }
356
693
  this.total++;
357
- if (this.hits.length >= this.settings.maxResults)
694
+ if (this.groups) {
695
+ this.groups.addKey(line, key);
358
696
  return;
697
+ }
698
+ if (this.lastOnes) {
699
+ // The last ones kept so far; the lines around them are known once the scan is over (`missing`).
700
+ this.firstHit ??= { line, column, text };
701
+ this.hits.push({ line, column, text });
702
+ if (this.hits.length > this.settings.maxResults)
703
+ this.hits.shift();
704
+ return;
705
+ }
706
+ if (this.hits.length >= this.settings.maxResults) {
707
+ this.last = { line, column, text };
708
+ return;
709
+ }
359
710
  this.hits.push({ line, column, text });
711
+ this.showAround(line);
712
+ }
713
+ /** Puts the lines around a match among the lines to show. */
714
+ showAround(line) {
360
715
  for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
361
716
  if (other !== line && !this.shown.has(other)) {
362
717
  this.shown.set(other, undefined);
@@ -364,35 +719,102 @@ class LineSearch {
364
719
  }
365
720
  }
366
721
  }
722
+ /** Ends the search before the end of the text: the counts are lower bounds. */
723
+ stop() {
724
+ this.stoppedEarly = true;
725
+ this.done = true;
726
+ return true;
727
+ }
728
+ /**
729
+ * One time slice of an exact scan of a piece. True when the piece is finished, or the search is
730
+ * (out of time, or past `toLine`, or at the most matches counted); false when text of the piece
731
+ * is left for the next slice. The time spent counts against the search's time limit: lowercasing
732
+ * the piece, finding the occurrences, and recording the lines, by group too.
733
+ */
367
734
  scanExact(chunk) {
735
+ if (this.timeLeft <= 0)
736
+ return this.stop();
737
+ const slice = Math.min(this.timeLeft, EXACT_SLICE_MS);
738
+ const started = performance.now();
739
+ // Where to go on: in a piece that was left at the end of a slice, or at the start of a new one.
740
+ const scan = this.exactLeft?.chunk === chunk ? this.exactLeft : this.startExact(chunk);
741
+ this.exactLeft = undefined;
368
742
  const { needle } = this;
743
+ const { text, written, lines, firstLine, start } = scan;
744
+ let at = scan.at;
745
+ let steps = 0;
746
+ while (at !== -1) {
747
+ // A look at the clock now and then: a step can record a line, by group too, which takes microseconds.
748
+ if ((++steps & 63) === 0 && performance.now() - started >= slice)
749
+ break;
750
+ // Words are checked as written: lowercased, "_" is "_", a word character, and "ID_2041"
751
+ // held no whole word "ID" for a search that ignores case, but did for one that does not.
752
+ if ((this.wordStart && wordBefore(written, at)) || (this.wordEnd && wordAt(written, at + needle.length))) {
753
+ // Part of a longer word: the next occurrence may be a whole one, on this line too. Past a
754
+ // whole character: in the middle of an emoji, the pattern would start at the emoji again.
755
+ at = this.find(text, at + (text.codePointAt(at) > 0xffff ? 2 : 1));
756
+ continue;
757
+ }
758
+ const local = lines.lineAt(at);
759
+ const line = firstLine + local - 1;
760
+ // A line is counted once, where an occurrence starts: the search goes on at the start of the
761
+ // next line. Overlapping occurrences of a needle across lines ("a\na" in "a\na\na") each
762
+ // count on their own line, and further occurrences on a counted line cost nothing.
763
+ const next = lines.startOf(local + 1);
764
+ this.nextAllowed = start + next;
765
+ if (line > this.lastLine) {
766
+ this.lastLine = line;
767
+ const lineText = lines.line(local);
768
+ this.record(line, at - lines.startOf(local), lineText, this.groups?.keyOf(lineText, undefined));
769
+ if (this.done)
770
+ break;
771
+ if (this.total >= MAX_EXACT_MATCHES) {
772
+ this.stop();
773
+ break;
774
+ }
775
+ }
776
+ at = next >= text.length ? -1 : this.find(text, next);
777
+ }
778
+ this.timeLeft -= performance.now() - started;
779
+ if (this.done || at === -1)
780
+ return true;
781
+ if (this.timeLeft <= 0)
782
+ return this.stop();
783
+ this.exactLeft = { ...scan, at };
784
+ return false;
785
+ }
786
+ /** The start of an exact scan of a piece: its text, with the lines before it that a needle across lines may start in, and the first occurrence. */
787
+ startExact(chunk) {
369
788
  const caseSensitive = this.settings.caseSensitive === true;
370
789
  let text = caseSensitive ? chunk.text : chunk.lower();
790
+ let written = chunk.text;
371
791
  let lines = chunk.lines;
372
792
  let firstLine = chunk.firstLine;
373
793
  let start = chunk.startCharacter;
374
- // A needle across lines can start in the lines before this piece.
375
794
  const before = this.newlines > 0 ? carried(this.recent, this.newlines) : undefined;
376
795
  if (before) {
377
- text = (caseSensitive ? before.text : foldCase(before.text)) + text;
378
- lines = new LineIndex(before.text + chunk.text);
796
+ written = before.text + chunk.text;
797
+ text = caseSensitive ? written : foldCase(before.text) + text;
798
+ lines = new LineIndex(written);
379
799
  firstLine = before.firstLine;
380
800
  start = chunk.startCharacter - before.text.length;
381
801
  }
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)
387
- continue;
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;
394
- }
395
- }
802
+ // An occurrence that starts before `fromLine` is not counted: the scan starts there.
803
+ const from = Math.max(0, this.nextAllowed - start, this.fromLine > firstLine ? lines.startOf(this.fromLine - firstLine + 1) : 0);
804
+ return { chunk, text, written, lines, firstLine, start, at: this.find(text, from) };
805
+ }
806
+ /**
807
+ * Where the next occurrence of the needle at or after `from` starts, or -1. With `wholeWord`,
808
+ * only one that no word character but "_" touches where the needle starts or ends with one: the
809
+ * pattern goes past those inside longer words at the speed of the regex engine. Looked at one by
810
+ * one, each cost a step, and a search for "a" in 100 MB of long words took 17 seconds.
811
+ */
812
+ find(text, from) {
813
+ const pattern = this.wholeWords;
814
+ if (!pattern)
815
+ return text.indexOf(this.needle, from);
816
+ pattern.lastIndex = from;
817
+ return pattern.exec(text)?.index ?? -1;
396
818
  }
397
819
  /**
398
820
  * One time slice of a regex scan of a piece. True when the piece is finished, or the search is
@@ -400,47 +822,77 @@ class LineSearch {
400
822
  * are left for the next slice.
401
823
  */
402
824
  scanRegex(chunk) {
403
- const stop = () => {
404
- this.stoppedEarly = true;
405
- this.done = true;
406
- return true;
407
- };
408
825
  // 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
826
  let next = this.unfinished?.chunk === chunk ? this.unfinished.next : 1;
410
827
  this.unfinished = undefined;
411
828
  if (this.timeLeft <= 0)
412
- return stop();
829
+ return this.stop();
413
830
  const pattern = this.pattern;
414
831
  const { lines, firstLine } = chunk;
832
+ // Lines before those searched are not matched at all.
833
+ if (firstLine + next - 1 < this.fromLine)
834
+ next = this.fromLine - firstLine + 1;
415
835
  const from = next;
416
836
  const slice = Math.min(this.timeLeft, REGEX_SLICE_MS);
417
837
  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);
838
+ const last = Math.min(lines.lineCount, this.toLine - firstLine + 1);
839
+ // Only the matching runs inside the time limit, which can stop it anywhere: the lines found are
840
+ // kept in a batch there, with their groups (by shape or time, microseconds a line), and
841
+ // recorded after, so a stop never leaves a count or a list half done. A batch is a number of
842
+ // lines, kept in typed arrays: then they are recorded, at a fraction of a microsecond each, and
843
+ // the matching goes on within the slice. Kept as an object each for the whole slice, half a
844
+ // million lines a slice made a scan twice as slow, as the garbage collector copied them; and
845
+ // grouped after the slice, outside the time limit, they held the server for seconds. A line
846
+ // found twice (the slice ended after it was put in the batch, before it was passed) is
847
+ // recorded once.
848
+ const batch = (this.batch ??= { lines: new Int32Array(REGEX_BATCH), columns: new Int32Array(REGEX_BATCH), keys: [] });
849
+ const groups = this.groups;
850
+ let finished = true;
851
+ while (next <= last && !this.done) {
852
+ const left = slice - (performance.now() - started);
853
+ if (left <= 0) {
854
+ finished = false;
855
+ break;
856
+ }
857
+ let count = 0;
858
+ finished = withinTimeLimit(() => {
859
+ for (; next <= last && count < REGEX_BATCH; next++) {
860
+ const text = lines.line(next);
861
+ const match = pattern.exec(text);
862
+ if (match) {
863
+ batch.lines[count] = next;
864
+ batch.columns[count] = match.index;
865
+ if (groups)
866
+ batch.keys[count] = groups.keyOf(text, match[1]);
867
+ count++;
868
+ }
427
869
  }
870
+ }, left);
871
+ for (let index = 0; index < count && !this.done; index++) {
872
+ const local = batch.lines[index];
873
+ const line = firstLine + local - 1;
874
+ if (line <= this.lastLine)
875
+ continue;
876
+ this.lastLine = line;
877
+ this.record(line, batch.columns[index], lines.line(local), groups ? batch.keys[index] : undefined);
428
878
  }
429
- }, slice);
879
+ if (!finished)
880
+ break;
881
+ }
430
882
  const spent = performance.now() - started;
431
883
  this.timeLeft -= spent;
432
884
  if (this.settings.regexClock)
433
885
  this.settings.regexClock.usedMs += spent;
434
- if (finished)
886
+ if (finished || this.done)
435
887
  return true;
436
888
  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.
889
+ return this.stop();
890
+ // The slice ended before line `next`, or in the middle of it. A whole slice without one line
891
+ // finished can be a stall of the machine, once. Twice on the same line, it is the pattern.
440
892
  if (next === from && slice >= REGEX_SLICE_MS) {
441
893
  const line = firstLine + next - 1;
442
894
  if (this.stuck === line)
443
- return stop();
895
+ return this.stop();
444
896
  this.stuck = line;
445
897
  }
446
898
  this.unfinished = { chunk, next };
@@ -461,34 +913,176 @@ async function readSome(source, lines, use) {
461
913
  /** Lines that contain `query` (exact text) or match it (regex), in a document held in memory. */
462
914
  export function grep(document, query, options) {
463
915
  const search = new LineSearch(query, options, document.lines.lineCount);
464
- search.add(document.wholeChunk());
916
+ for (const chunk of document.pieces()) {
917
+ if (search.done)
918
+ break;
919
+ search.add(chunk);
920
+ }
465
921
  for (const line of search.missing())
466
922
  search.fill(line, document.lines.line(line));
467
923
  return search.result();
468
924
  }
469
- /** `grep` over any document: one held in memory, or one read from the store a piece at a time. */
925
+ /**
926
+ * `grep` over any document: one held in memory, or one read from the store a piece at a time.
927
+ * Other work gets a turn between two pieces, and between two time slices of a piece.
928
+ */
470
929
  export async function grepSource(source, query, options) {
471
930
  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
931
  await scanSource(source, (chunk) => (search.addSome(chunk) ? search.done : "again"), options.signal);
484
932
  const missing = search.missing();
485
933
  if (missing.length)
486
934
  await readSome(source, missing, (line, text) => search.fill(line, text));
487
935
  return search.result();
488
936
  }
937
+ /**
938
+ * Hebrew points and cantillation marks, and the combining grapheme joiner that pointed texts put
939
+ * between two points of a letter. Not the maqaf, paseq, sof pasuq or nun hafukha, which are
940
+ * punctuation and split words.
941
+ */
942
+ const HEBREW_POINT = "\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u034f";
943
+ const HEBREW_LETTER = "\\u05d0-\\u05ea";
944
+ /**
945
+ * What splits a query into words: anything but letters, marks, digits and "_" (a mark stays with
946
+ * its letter: Hindi, Thai, pointed Hebrew), except a geresh or a gershayim between two Hebrew
947
+ * letters, folded to ' and ", as in the acronyms עו״ד and ש״ח, or in ג׳ורג׳. Split there, ש״ח gave
948
+ * no term, as each part has one letter, and עו״ד gave only עו, which most lines with עוד have.
949
+ */
950
+ const QUERY_SPLIT = new RegExp(`(?:(?!['"])[^\\p{L}\\p{M}\\p{N}_])+|(?<![${HEBREW_LETTER}][${HEBREW_POINT}]*)['"]|['"](?![${HEBREW_LETTER}])`, "u");
951
+ /** Two gereshes between two Hebrew letters: a gershayim as many keyboards type it (ש''ח). */
952
+ const DOUBLE_GERESH = new RegExp(`(?<=[${HEBREW_LETTER}][${HEBREW_POINT}]*)''(?=[${HEBREW_LETTER}])`, "gu");
953
+ /** Scripts written without spaces between words: a word of them is split by `Intl.Segmenter`. */
954
+ const WITHOUT_SPACES = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u;
955
+ /** Han and kana: one character can be a word. */
956
+ const IDEOGRAPHS = /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+$/u;
957
+ let wordSegmenter;
958
+ /** The words of a run of a script written without spaces, or the run itself where Node has no word segmenter. */
959
+ function segmentWords(run) {
960
+ if (wordSegmenter === undefined) {
961
+ try {
962
+ wordSegmenter = new Intl.Segmenter("und", { granularity: "word" });
963
+ }
964
+ catch {
965
+ wordSegmenter = null;
966
+ }
967
+ }
968
+ if (!wordSegmenter)
969
+ return [run];
970
+ const words = [];
971
+ for (const piece of wordSegmenter.segment(run))
972
+ if (piece.isWordLike)
973
+ words.push(piece.segment);
974
+ return words.length > 0 ? words : [run];
975
+ }
976
+ const codePoints = (text) => {
977
+ let count = 0;
978
+ for (const _ of text)
979
+ count++;
980
+ return count;
981
+ };
982
+ /** A word of Hebrew letters, with or without points, and with the geresh or gershayim of an acronym (folded to ' and "). */
983
+ const HEBREW_WORD = new RegExp(`^[${HEBREW_LETTER}${HEBREW_POINT}'"]+$`, "u");
984
+ const HEBREW_POINTS = new RegExp(`[${HEBREW_POINT}]`, "gu");
985
+ const HAS_HEBREW_LETTER = new RegExp(`[${HEBREW_LETTER}]`, "u");
986
+ /** Letters that Hebrew writes before a word: and, the, in, as, to, from, that (ו ה ב כ ל מ ש). */
987
+ const HEBREW_PREFIXES = "והבכלמש";
988
+ /** Final letters, and the form each takes inside a longer word: כסף, כספים. */
989
+ const HEBREW_FINALS = { "ך": "כ", "ם": "מ", "ן": "נ", "ף": "פ", "ץ": "צ" };
990
+ function hebrewVariants(word) {
991
+ const final = HEBREW_FINALS[word.at(-1)];
992
+ return final ? [word, word.slice(0, -1) + final] : [word];
993
+ }
994
+ /**
995
+ * The terms of a keyword search: the words of the query, folded as the text is searched, without
996
+ * stop words and words of one letter (a Han or kana word can be one character). A Hebrew word that
997
+ * starts with prefix letters (בחוזה, והחוזה) also gives its stem without them (חוזה) as a term of its
998
+ * own, while at least 3 letters are left: the stem finds the word with any prefix, and passages
999
+ * with the word as written still rank first, as they hold both terms. The letter before the
1000
+ * geresh or gershayim of an acronym is never a prefix: בש״ח gives ש״ח, and ב״ש stays as it is.
1001
+ */
1002
+ export function searchTerms(query) {
1003
+ const terms = new Map();
1004
+ const add = (term, variants, hebrew = false) => {
1005
+ if (!terms.has(term))
1006
+ terms.set(term, { term, variants, ...(hebrew ? { hebrew } : {}) });
1007
+ };
1008
+ for (const word of foldCase(composed(query)).replace(DOUBLE_GERESH, "\"").split(QUERY_SPLIT)) {
1009
+ for (const piece of WITHOUT_SPACES.test(word) ? segmentWords(word) : [word]) {
1010
+ if (!piece || STOPWORDS.has(piece) || codePoints(piece) < (IDEOGRAPHS.test(piece) ? 1 : 2))
1011
+ continue;
1012
+ if (!HEBREW_WORD.test(piece)) {
1013
+ add(piece, [piece]);
1014
+ continue;
1015
+ }
1016
+ const bare = piece.replace(HEBREW_POINTS, "");
1017
+ if (bare.length < 2 || STOPWORDS.has(bare))
1018
+ continue;
1019
+ add(bare, hebrewVariants(bare), true);
1020
+ // Prefix letters before a quoted word (ה"ספק, ב"הסכם: a defined term of a contract): the word
1021
+ // itself is a term too, as the text may write it without the quote or the prefix.
1022
+ const quote = bare.search(/["']/);
1023
+ if (quote > 0 && quote <= 3 && [...bare.slice(0, quote)].every((letter) => HEBREW_PREFIXES.includes(letter)) && bare.length - quote - 1 >= 2) {
1024
+ const word = bare.slice(quote + 1);
1025
+ if (!/["']/.test(word))
1026
+ add(word, hebrewVariants(word), true);
1027
+ }
1028
+ // Prefix letters are stripped while at least 3 letters are left (בש"ח gives ש"ח). An acronym
1029
+ // whose first letter is one (מע"מ) also gives a stem (ע"מ): its own term ranks its passages first.
1030
+ let stem = bare;
1031
+ for (let stripped = 0; stripped < 3 && stem.length > 3 && HEBREW_PREFIXES.includes(stem[0]) && !"'\"".includes(stem[1]); stripped++)
1032
+ stem = stem.slice(1);
1033
+ if (stem !== bare)
1034
+ add(stem, hebrewVariants(stem), true);
1035
+ }
1036
+ }
1037
+ return [...terms.values()].slice(0, 12);
1038
+ }
1039
+ /**
1040
+ * A text to search for as a pattern that also finds it with points after its Hebrew letters, as a
1041
+ * pointed text writes them (a Bible, a prayer book, poetry, a book for children): the query loses
1042
+ * its points, and the text keeps them. A gershayim between two Hebrew letters is also found as two
1043
+ * gereshes.
1044
+ */
1045
+ function pointedPattern(text) {
1046
+ const characters = [...text];
1047
+ const hebrew = (character) => character !== undefined && character >= "א" && character <= "ת";
1048
+ let out = "";
1049
+ characters.forEach((character, index) => {
1050
+ if (character === "\"" && hebrew(characters[index - 1]) && hebrew(characters[index + 1]))
1051
+ out += "(?:\"|'')";
1052
+ else
1053
+ out += character.replace(/[\\^$.*+?()[\]{}|/-]/g, "\\$&");
1054
+ if (hebrew(character) && index + 1 < characters.length)
1055
+ out += `[${HEBREW_POINT}]*`;
1056
+ });
1057
+ return out;
1058
+ }
1059
+ /** Finds a text in a piece: as it is, or, given a pattern, by the pattern (see `pointedPattern`). */
1060
+ class Finder {
1061
+ text;
1062
+ /** The length of the occurrence found last. */
1063
+ length;
1064
+ pattern;
1065
+ constructor(text, pattern) {
1066
+ this.text = text;
1067
+ this.length = text.length;
1068
+ if (pattern !== undefined)
1069
+ this.pattern = new RegExp(pattern, "g");
1070
+ }
1071
+ /** Where the first occurrence at or after `from` starts, or -1. */
1072
+ find(haystack, from) {
1073
+ if (!this.pattern)
1074
+ return haystack.indexOf(this.text, from);
1075
+ this.pattern.lastIndex = from;
1076
+ const match = this.pattern.exec(haystack);
1077
+ if (!match)
1078
+ return -1;
1079
+ this.length = match[0].length;
1080
+ return match.index;
1081
+ }
1082
+ }
1083
+ /** The terms of a keyword search, as text. See `searchTerms`. */
489
1084
  export function queryTerms(query) {
490
- const terms = foldCase(query).split(/[^\p{L}\p{N}_]+/u).filter((term) => term.length >= 2 && !STOPWORDS.has(term));
491
- return [...new Set(terms)].slice(0, 12);
1085
+ return searchTerms(query).map(({ term }) => term);
492
1086
  }
493
1087
  /**
494
1088
  * BM25 over fixed passages, computed at query time from substring hits, over a document fed a
@@ -497,55 +1091,104 @@ export function queryTerms(query) {
497
1091
  */
498
1092
  class PassageRank {
499
1093
  source;
1094
+ range;
500
1095
  terms;
501
1096
  /** Passage lengths in characters, for the passages that have a hit. */
502
1097
  lengths = new Map();
503
1098
  phrase;
504
1099
  recent = [];
505
- constructor(query, source) {
1100
+ /**
1101
+ * `range`: the lines to rank passages of; a passage that has none of them is left out, one that
1102
+ * has some keeps all its lines. Only the hits on its lines count, phrases included.
1103
+ */
1104
+ constructor(query, source, range) {
506
1105
  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 };
1106
+ this.range = range;
1107
+ this.terms = searchTerms(query).map(({ variants, hebrew }) => ({
1108
+ finders: variants.map((variant) => new Finder(variant, hebrew ? pointedPattern(variant) : undefined)),
1109
+ seen: 0,
1110
+ frequency: new Map(),
1111
+ }));
1112
+ // Passages that contain the whole phrase rank above passages with scattered terms. A phrase
1113
+ // with Hebrew loses its points, as its terms do, and is found with or without them.
1114
+ const phrase = foldCase(composed(query.trim()));
1115
+ if (this.terms.length > 1 && phrase.length <= 200) {
1116
+ const hebrew = HAS_HEBREW_LETTER.test(phrase);
1117
+ const bare = hebrew ? phrase.replace(HEBREW_POINTS, "") : phrase;
1118
+ this.phrase = { finder: new Finder(bare, hebrew ? pointedPattern(bare) : undefined), newlines: newlinesIn(bare), passages: new Set(), nextAllowed: 0 };
1119
+ }
512
1120
  }
513
1121
  get empty() {
514
1122
  return this.terms.length === 0;
515
1123
  }
1124
+ /**
1125
+ * Counts the hits of a piece. True when the pieces after it have nothing to count: they are past
1126
+ * the lines ranked, and past the end of a phrase across lines that starts on one of them. Only
1127
+ * the lines ranked are looked at: a search of the last 100 lines of a file full of the terms
1128
+ * went through every occurrence of them in the file.
1129
+ */
516
1130
  add(chunk) {
517
1131
  if (this.empty)
518
- return;
1132
+ return true;
1133
+ const range = this.range;
1134
+ const { lines, firstLine } = chunk;
1135
+ const chunkEnd = firstLine + lines.lineCount - 1;
1136
+ // The lines of this piece whose hits count.
1137
+ const first = range ? Math.max(1, range.from - firstLine + 1) : 1;
1138
+ const last = range ? Math.min(lines.lineCount, range.to - firstLine + 1) : lines.lineCount;
1139
+ if (first <= last)
1140
+ this.countTerms(chunk, lines.startOf(first), lines.endOf(last));
1141
+ const phrase = this.phrase;
1142
+ const phraseOpen = phrase !== undefined && phrase.passages.size < MAX_PHRASE_PASSAGES;
1143
+ if (phraseOpen && (!range || (chunkEnd >= range.from && firstLine - phrase.newlines <= range.to)))
1144
+ this.findPhrase(chunk);
1145
+ return range !== undefined && chunkEnd >= range.to + (phraseOpen ? phrase.newlines : 0);
1146
+ }
1147
+ /** Counts the occurrences of the terms in a piece that start from `from` to before `to`, up to the cap of each. */
1148
+ countTerms(chunk, from, to) {
519
1149
  const haystack = chunk.lower();
520
1150
  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));
1151
+ for (const finder of entry.finders) {
1152
+ for (let at = finder.find(haystack, from); at !== -1 && at < to && entry.seen < MAX_OCCURRENCES_PER_TERM; at = finder.find(haystack, at + finder.length)) {
1153
+ entry.seen++;
1154
+ const passage = this.passageOf(chunk.firstLine + chunk.lines.lineAt(at) - 1);
1155
+ entry.frequency.set(passage, (entry.frequency.get(passage) ?? 0) + 1);
1156
+ if (!this.lengths.has(passage))
1157
+ this.lengths.set(passage, this.lengthOf(passage, chunk));
1158
+ }
528
1159
  }
529
1160
  }
1161
+ }
1162
+ /**
1163
+ * Finds the passages of a piece where the whole phrase starts, on a line ranked. A phrase across
1164
+ * lines may start in the lines carried from the piece before. Hits before the range no longer
1165
+ * fill the cap on passages, so that one in it still gets its boost.
1166
+ */
1167
+ findPhrase(chunk) {
530
1168
  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;
1169
+ const range = this.range;
1170
+ let text = chunk.lower();
1171
+ let lines = chunk.lines;
1172
+ let firstLine = chunk.firstLine;
1173
+ let start = chunk.startCharacter;
1174
+ const before = phrase.newlines > 0 ? carried(this.recent, phrase.newlines) : undefined;
1175
+ if (before) {
1176
+ text = foldCase(before.text) + text;
1177
+ lines = new LineIndex(before.text + chunk.text);
1178
+ firstLine = before.firstLine;
1179
+ start = chunk.startCharacter - before.text.length;
1180
+ }
1181
+ const lastLine = range ? Math.min(lines.lineCount, range.to - firstLine + 1) : lines.lineCount;
1182
+ if (lastLine >= 1) {
1183
+ const from = range && range.from > firstLine ? lines.startOf(range.from - firstLine + 1) : 0;
1184
+ const to = lines.endOf(lastLine);
1185
+ const { finder } = phrase;
1186
+ for (let at = finder.find(text, Math.max(from, phrase.nextAllowed - start)); at !== -1 && at <= to && phrase.passages.size < MAX_PHRASE_PASSAGES; at = finder.find(text, at + finder.length)) {
1187
+ phrase.nextAllowed = start + at + finder.length;
545
1188
  phrase.passages.add(this.passageOf(firstLine + lines.lineAt(at) - 1));
546
1189
  }
547
- this.recent = remember(this.recent, chunk, phrase.newlines);
548
1190
  }
1191
+ this.recent = remember(this.recent, chunk, phrase.newlines);
549
1192
  }
550
1193
  result(topK) {
551
1194
  if (this.empty)
@@ -553,9 +1196,12 @@ class PassageRank {
553
1196
  const passageCount = this.source.passageStarts.length;
554
1197
  const averageLength = Math.max(1, this.source.characters / passageCount);
555
1198
  const scores = new Map();
556
- for (const { frequency } of this.terms) {
1199
+ for (const { frequency, seen } of this.terms) {
557
1200
  const df = frequency.size;
558
- if (df === 0)
1201
+ // A term found this often is in a large share of the passages, and tells little about any of
1202
+ // them; and it was counted only up to the cap, in the passages before it. Scored, it pushed
1203
+ // passages from the start of the file above better ones.
1204
+ if (df === 0 || seen >= MAX_OCCURRENCES_PER_TERM)
559
1205
  continue;
560
1206
  const idf = Math.log(1 + (passageCount - df + 0.5) / (df + 0.5));
561
1207
  for (const [passage, tf] of frequency) {
@@ -567,20 +1213,27 @@ class PassageRank {
567
1213
  if (this.phrase)
568
1214
  for (const passage of this.phrase.passages)
569
1215
  scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
1216
+ const range = this.range;
570
1217
  return [...scores.entries()]
1218
+ .filter(([passage]) => {
1219
+ if (!range)
1220
+ return true;
1221
+ const { from, to } = this.rangeOf(passage);
1222
+ return to >= range.from && from <= range.to;
1223
+ })
571
1224
  .sort((left, right) => right[1] - left[1])
572
1225
  .slice(0, topK)
573
- .map(([passage, score]) => ({ ...this.range(passage), score: Math.round(score * 100) / 100 }));
1226
+ .map(([passage, score]) => ({ ...this.rangeOf(passage), score: Math.round(score * 100) / 100 }));
574
1227
  }
575
1228
  passageOf(line) {
576
1229
  return positionOf(this.source.passageStarts, line) - 1;
577
1230
  }
578
- range(passage) {
1231
+ rangeOf(passage) {
579
1232
  const starts = this.source.passageStarts;
580
1233
  return { from: starts[passage], to: (passage + 1 < starts.length ? starts[passage + 1] : this.source.lineCount + 1) - 1 };
581
1234
  }
582
1235
  lengthOf(passage, chunk) {
583
- const { from, to } = this.range(passage);
1236
+ const { from, to } = this.rangeOf(passage);
584
1237
  const first = from - chunk.firstLine + 1;
585
1238
  const last = to - chunk.firstLine + 1;
586
1239
  if (first < 1 || last > chunk.lines.lineCount)
@@ -588,22 +1241,23 @@ class PassageRank {
588
1241
  return chunk.lines.endOf(last) - chunk.lines.startOf(first) + 1;
589
1242
  }
590
1243
  }
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());
1244
+ /** BM25 passage ranking over a document held in memory. `range`: only passages with lines in it. */
1245
+ export function rankPassages(document, query, topK, range) {
1246
+ const rank = new PassageRank(query, document, range);
1247
+ for (const chunk of document.pieces())
1248
+ if (rank.add(chunk))
1249
+ break;
595
1250
  return rank.result(topK);
596
1251
  }
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);
1252
+ /**
1253
+ * `rankPassages` over any document: one held in memory, or one read from the store a piece at a
1254
+ * time. Other work gets a turn between two pieces, and nothing past the lines ranked is read.
1255
+ */
1256
+ export async function rankSource(source, query, topK, signal, range) {
1257
+ const rank = new PassageRank(query, source, range);
602
1258
  if (rank.empty)
603
1259
  return [];
604
- await scanSource(source, (chunk) => {
605
- rank.add(chunk);
606
- }, signal);
1260
+ await scanSource(source, (chunk) => rank.add(chunk), signal);
607
1261
  return rank.result(topK);
608
1262
  }
609
1263
  //# sourceMappingURL=search.js.map